method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ABICallElection { public void clear() { this.votes = new HashMap<>(); } ABICallElection(AddressBasedAuthorizer authorizer, Map<ABICallSpec, List<RskAddress>> votes); ABICallElection(AddressBasedAuthorizer authorizer); Map<ABICallSpec, List<RskAddress>> getVotes(); void clear(); boolean vote(ABICallSpec callSpec, RskAddress voter); ABICallSpec getWinner(); void clearWinners(); }### Answer:
@Test public void clear() { election.clear(); Assert.assertEquals(0, election.getVotes().size()); }
|
### Question:
ABICallSpec { public String getFunction() { return function; } ABICallSpec(String function, byte[][] arguments); String getFunction(); byte[][] getArguments(); byte[] getEncoded(); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); static final Comparator<ABICallSpec> byBytesComparator; }### Answer:
@Test public void getFunction() { ABICallSpec spec = new ABICallSpec("a-function", new byte[][]{}); Assert.assertEquals("a-function", spec.getFunction()); }
|
### Question:
ABICallSpec { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } ABICallSpec otherSpec = ((ABICallSpec) other); return otherSpec.getFunction().equals(getFunction()) && areEqual(arguments, otherSpec.arguments); } ABICallSpec(String function, byte[][] arguments); String getFunction(); byte[][] getArguments(); byte[] getEncoded(); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); static final Comparator<ABICallSpec> byBytesComparator; }### Answer:
@Test public void testEquals() { ABICallSpec specA = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccddee") }); ABICallSpec specB = new ABICallSpec("function-b", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccddee") }); ABICallSpec specC = new ABICallSpec("function-a", new byte[][]{ Hex.decode("ccddee"), Hex.decode("aabb") }); ABICallSpec specD = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccdd") }); ABICallSpec specE = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb") }); ABICallSpec specF = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccddee") }); Assert.assertEquals(specA, specF); Assert.assertNotEquals(specA, specB); Assert.assertNotEquals(specA, specC); Assert.assertNotEquals(specA, specD); Assert.assertNotEquals(specA, specE); }
|
### Question:
PendingFederation { public List<FederationMember> getMembers() { return members; } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); }### Answer:
@Test public void membersImmutable() { boolean exception = false; try { pendingFederation.getMembers().add(new FederationMember(new BtcECKey(), new ECKey(), new ECKey())); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); exception = false; try { pendingFederation.getMembers().remove(0); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); }
|
### Question:
PendingFederation { public boolean isComplete() { return this.members.size() >= MIN_MEMBERS_REQUIRED; } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); }### Answer:
@Test public void isComplete() { Assert.assertTrue(pendingFederation.isComplete()); }
@Test public void isComplete_not() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(200)); Assert.assertFalse(otherPendingFederation.isComplete()); }
|
### Question:
PendingFederation { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } return this.members.equals(((PendingFederation) other).members); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); }### Answer:
@Test public void testEquals_basic() { Assert.assertTrue(pendingFederation.equals(pendingFederation)); Assert.assertFalse(pendingFederation.equals(null)); Assert.assertFalse(pendingFederation.equals(new Object())); Assert.assertFalse(pendingFederation.equals("something else")); }
@Test public void testEquals_differentNumberOfMembers() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600, 700)); Assert.assertFalse(pendingFederation.equals(otherPendingFederation)); }
@Test public void testEquals_differentMembers() { List<FederationMember> members = FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500); members.add(new FederationMember(BtcECKey.fromPrivate(BigInteger.valueOf(610)), ECKey.fromPrivate(BigInteger.valueOf(600)), ECKey.fromPrivate(BigInteger.valueOf(620)))); PendingFederation otherPendingFederation = new PendingFederation(members); members.remove(members.size()-1); members.add(new FederationMember(BtcECKey.fromPrivate(BigInteger.valueOf(600)), ECKey.fromPrivate(BigInteger.valueOf(610)), ECKey.fromPrivate(BigInteger.valueOf(630)))); PendingFederation yetOtherPendingFederation = new PendingFederation(members); Assert.assertFalse(otherPendingFederation.equals(yetOtherPendingFederation)); Assert.assertFalse(pendingFederation.equals(otherPendingFederation)); Assert.assertFalse(pendingFederation.equals(yetOtherPendingFederation)); }
@Test public void testEquals_same() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600)); Assert.assertTrue(pendingFederation.equals(otherPendingFederation)); }
|
### Question:
PendingFederation { @Override public String toString() { return String.format("%d signatures pending federation (%s)", members.size(), isComplete() ? "complete" : "incomplete"); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); }### Answer:
@Test public void testToString() { Assert.assertEquals("6 signatures pending federation (complete)", pendingFederation.toString()); PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100)); Assert.assertEquals("1 signatures pending federation (incomplete)", otherPendingFederation.toString()); }
|
### Question:
PendingFederation { public Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams) { if (!this.isComplete()) { throw new IllegalStateException("PendingFederation is incomplete"); } return new Federation( members, creationTime, blockNumber, btcParams ); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); }### Answer:
@Test public void buildFederation_ok_a() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600)); Federation expectedFederation = new Federation( FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600), Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ); Assert.assertEquals( expectedFederation, otherPendingFederation.buildFederation( Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ) ); }
@Test public void buildFederation_ok_b() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks( 100, 200, 300, 400, 500, 600, 700, 800, 900 )); Federation expectedFederation = new Federation( FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600, 700, 800, 900), Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ); Assert.assertEquals( expectedFederation, otherPendingFederation.buildFederation( Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ) ); }
@Test public void buildFederation_incomplete() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100)); try { otherPendingFederation.buildFederation(Instant.ofEpochMilli(12L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); } catch (Exception e) { Assert.assertEquals("PendingFederation is incomplete", e.getMessage()); return; } Assert.fail(); }
|
### Question:
ECKey { @Nullable public byte[] getPrivKeyBytes() { return bigIntegerToBytes(priv, 32); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer:
@Test public void testGetPrivKeyBytes() { ECKey key = new ECKey(); assertNotNull(key.getPrivKeyBytes()); assertEquals(32, key.getPrivKeyBytes().length); }
|
### Question:
PendingFederation { public Keccak256 getHash() { byte[] encoded = BridgeSerializationUtils.serializePendingFederationOnlyBtcKeys(this); return new Keccak256(HashUtil.keccak256(encoded)); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); }### Answer:
@PrepareForTest({ BridgeSerializationUtils.class }) @Test public void getHash() { PowerMockito.mockStatic(BridgeSerializationUtils.class); PowerMockito.when(BridgeSerializationUtils.serializePendingFederationOnlyBtcKeys(pendingFederation)).thenReturn(new byte[] { (byte) 0xaa }); Keccak256 expectedHash = new Keccak256(HashUtil.keccak256(new byte[] { (byte) 0xaa })); Assert.assertEquals(expectedHash, pendingFederation.getHash()); }
|
### Question:
BIUtil { public static boolean isIn20PercentRange(BigInteger first, BigInteger second) { BigInteger five = BigInteger.valueOf(5); BigInteger limit = first.add(first.divide(five)); return !isMoreThan(second, limit); } static boolean isZero(BigInteger value); static boolean isEqual(BigInteger valueA, BigInteger valueB); static boolean isNotEqual(BigInteger valueA, BigInteger valueB); static boolean isLessThan(BigInteger valueA, BigInteger valueB); static boolean isMoreThan(BigInteger valueA, BigInteger valueB); static BigInteger sum(BigInteger valueA, BigInteger valueB); static BigInteger toBI(byte[] data); static BigInteger toBI(long data); static boolean isPositive(BigInteger value); static boolean isCovers(Coin covers, Coin value); static boolean isNotCovers(Coin covers, Coin value); static boolean isIn20PercentRange(BigInteger first, BigInteger second); static BigInteger max(BigInteger first, BigInteger second); }### Answer:
@Test public void testIsIn20PercentRange() { assertTrue(isIn20PercentRange(BigInteger.valueOf(20000), BigInteger.valueOf(24000))); assertTrue(isIn20PercentRange(BigInteger.valueOf(24000), BigInteger.valueOf(20000))); assertFalse(isIn20PercentRange(BigInteger.valueOf(20000), BigInteger.valueOf(25000))); assertTrue(isIn20PercentRange(BigInteger.valueOf(20), BigInteger.valueOf(24))); assertTrue(isIn20PercentRange(BigInteger.valueOf(24), BigInteger.valueOf(20))); assertFalse(isIn20PercentRange(BigInteger.valueOf(20), BigInteger.valueOf(25))); assertTrue(isIn20PercentRange(BigInteger.ZERO, BigInteger.ZERO)); assertFalse(isIn20PercentRange(BigInteger.ZERO, BigInteger.ONE)); assertTrue(isIn20PercentRange(BigInteger.ONE, BigInteger.ZERO)); }
@Test public void test1() { assertFalse(isIn20PercentRange(BigInteger.ONE, BigInteger.valueOf(5))); assertTrue(isIn20PercentRange(BigInteger.valueOf(5), BigInteger.ONE)); assertTrue(isIn20PercentRange(BigInteger.valueOf(5), BigInteger.valueOf(6))); assertFalse(isIn20PercentRange(BigInteger.valueOf(5), BigInteger.valueOf(7))); }
|
### Question:
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 = ByteUtil.nibblesToPrettyString(keyNibbles); stringBuilder.append(keyString); stringBuilder.append(","); Value val = new Value(list[1]); stringBuilder.append(val.toString()); stringBuilder.append(" ]"); return stringBuilder.toString(); } stringBuilder.append(" ["); for (int i = 0; i < list.length; ++i) { Value val = new Value(list[i]); if (val.isString() || val.isEmpty()) { stringBuilder.append("'").append(val.toString()).append("'"); } else { stringBuilder.append(val.toString()); } if (i < list.length - 1) { stringBuilder.append(", "); } } stringBuilder.append("] "); return stringBuilder.toString(); } else if (isEmpty()) { return ""; } else if (isBytes()) { StringBuilder output = new StringBuilder(); if (isHashCode()) { output.append(ByteUtil.toHexString(asBytes())); } else if (isReadableString()) { output.append("'"); for (byte oneByte : asBytes()) { if (oneByte < 16) { output.append("\\x").append(ByteUtil.oneByteToHexString(oneByte)); } else { output.append(Character.valueOf((char) oneByte)); } } output.append("'"); return output.toString(); } return ByteUtil.toHexString(this.asBytes()); } else if (isString()) { return asString(); } return "Unexpected type"; } Value(); Value(Object obj); static Value fromRlpEncoded(byte[] data); void init(byte[] rlp); Object asObj(); List<Object> asList(); int asInt(); long asLong(); BigInteger asBigInt(); String asString(); byte[] asBytes(); String getHex(); byte[] getData(); int[] asSlice(); Value get(int index); byte[] encode(); byte[] hash(); boolean isList(); boolean isString(); boolean isInt(); boolean isLong(); boolean isBigInt(); boolean isBytes(); boolean isReadableString(); boolean isHexString(); boolean isHashCode(); boolean isNull(); boolean isEmpty(); int length(); String toString(); }### Answer:
@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 String[] {"hello", "world", "!"}); String str = val.toString(); assertEquals(" ['hello', 'world', '!'] ", str); }
@Test public void toString_UnsupportedType() { Value val = new Value('a'); String str = val.toString(); assertEquals("Unexpected type", str); }
|
### Question:
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); boolean isAuthorized(Transaction tx); int getNumberOfAuthorizedKeys(); int getRequiredAuthorizedKeys(); }### Answer:
@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 = 100L; n <= 102L; n++) { Transaction mockedTx = mock(Transaction.class); when(mockedTx.getSender()).thenReturn(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(n)).getAddress())); Assert.assertTrue(auth.isAuthorized(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(n)).getAddress()))); Assert.assertTrue(auth.isAuthorized(mockedTx)); } Assert.assertFalse(auth.isAuthorized(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(50L)).getAddress()))); Transaction mockedTx = mock(Transaction.class); when(mockedTx.getSender()).thenReturn(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(50L)).getAddress())); Assert.assertFalse(auth.isAuthorized(mockedTx)); }
|
### Question:
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 = deserializeFederationMember(element.getRLPData()); members.add(member); } return new PendingFederation(members); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); }### Answer:
@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.assertTrue(e.getMessage().contains("Invalid serialized FederationMember")); } }
|
### Question:
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> listener); }### Answer:
@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, TimeUnit.MILLISECONDS); Transport.waitForConnection(transport); Duration duration = Duration.between(start, Instant.now()); System.out.println(duration); Assert.assertTrue(duration.compareTo(Duration.ofMillis(100)) > 0); } finally { executor.shutdown(); } }
|
### Question:
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<String> segments); static Topic of(final String first, final String... strings); static String ensureNotSpecial(final String segment); }### Answer:
@Test public void testStream() { final String result = Topic.split("foo/bar").stream().collect(Collectors.joining()); assertEquals("foobar", result); }
|
### Question:
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(); @Override String toString(); static Payload of(final String key, final Object value); static Payload of(final Map<String, ?> values); static Payload of(final Instant timestamp, final String key, final Object value); static Payload of(final Instant timestamp, final Map<String, ?> values); }### Answer:
@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 = NullPointerException.class) public void testNull4() { Payload.of((Instant) null, null); }
|
### Question:
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); }### Answer:
@Test public void test1() { Errors.ignore().handleError(new Exception(), Optional.empty()); }
|
### Question:
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 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); }### Answer:
@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()); }
|
### Question:
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); }### Answer:
@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 givenSslEnabledInConfiguration_whenHttpsPortIsSetInConfiguration_thenShouldUsePortFromConfiguration() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configuration.put(HTTPS_PORT, DEFAULT_TEST_SSL_PORT); configureServer(); assertThat(options.getPort()).isEqualTo(DEFAULT_TEST_SSL_PORT); }
|
### Question:
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<Record>> handler); void getHttpClient(Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler); void getWebClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getWebClient(jsonFilter, metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByFilter_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getWebClient(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByFilterWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getWebClient(record -> record.getName().equals(SERVICE_NAME), metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getWebClient(jsonFilter, context.asyncAssertSuccess(Assert::assertNotNull)); }
|
### Question:
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 configuration, Handler<AsyncResult<Record>> handler); void getConsumer(Function<Record, Boolean> filter, Handler<AsyncResult<MessageConsumer<T>>> handler); void getConsumer(JsonObject jsonFilter, Handler<AsyncResult<MessageConsumer<T>>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsConsumer_thenShouldGetTheConsumer(TestContext context) throws Exception { publishMessageSourceService(messageSourceConfiguration); vertxServiceDiscovery.messageSource().getConsumer(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsConsumerByJson_thenShouldGetTheConsumer(TestContext context) throws Exception { publishMessageSourceService(messageSourceConfiguration); vertxServiceDiscovery.messageSource().getConsumer(new JsonObject().put("name", SERVICE_NAME), context.asyncAssertSuccess()); }
|
### Question:
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<AsyncResult<Record>> handler); void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<RedisClient>> handler); void getClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<RedisClient>> handler); void getClient(JsonObject jsonFilter, Handler<AsyncResult<RedisClient>> handler); void getClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<RedisClient>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishingRedisDataSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.redis().getClient(filter(), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.redis().getClient(filter(), metadata, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.redis().getClient(jsonFilter, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.redis().getClient(jsonFilter, metadata, context.asyncAssertSuccess()); }
|
### Question:
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<Record>> handler); void getProxy(Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(Function<Record, Boolean> filter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(JsonObject jsonFilter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsProxy_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getProxy(TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); }
|
### Question:
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(EventBusServiceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getProxy(Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(Function<Record, Boolean> filter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(JsonObject jsonFilter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsServiceProxy_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getServiceProxy(record -> record.getName().equals(SERVICE_NAME), TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsServiceProxyByJson_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getServiceProxy(jsonFilter, TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); }
|
### Question:
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<AsyncResult<Record>> handler); void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<JDBCClient>> handler); void getClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<JDBCClient>> handler); void getClient(JsonObject jsonFilter, Handler<AsyncResult<JDBCClient>> handler); void getClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<JDBCClient>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.jdbc().getClient(filter(), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClientWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.jdbc().getClient(filter(), metadata, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.jdbc().getClient(jsonFilter, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.jdbc().getClient(jsonFilter, metadata, context.asyncAssertSuccess()); }
|
### Question:
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<AsyncResult<Record>> handler); void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<MongoClient>> handler); void getClient(JsonObject jsonFilter, Handler<AsyncResult<MongoClient>> handler); void getClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<MongoClient>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishingRedisDataSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.mongo().getClient(filter(), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.mongo().getClient(jsonFilter, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.mongo().getClient(jsonFilter, metadata, context.asyncAssertSuccess()); }
|
### Question:
VertxServiceDiscovery { public void publishRecord(Record record, Handler<AsyncResult<Record>> handler) { serviceDiscovery.publish(record, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test public void givenServiceDiscovery_whenPublishingRecord_thenTheRecordShouldBePublished(TestContext context) throws Exception { vertxServiceDiscovery.publishRecord(record, context.asyncAssertSuccess()); }
|
### Question:
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 messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForARecordWithNullFilter_thenShouldThrowException() throws Exception { lookup(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForARecordUnmatchingPredicate_thenShouldGetNullRecord(TestContext context) throws Exception { publishTestRecord(record); lookup(r -> r.getName().equals(NOT_EXISTED_NAME), context.asyncAssertSuccess(context::assertNull)); }
@Test public void givenServiceDiscovery_whenLookupForARecordMatchingPredicate_thenShouldGetTheRecord(TestContext context) throws Exception { publishTestRecord(record); lookup(r -> r.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(record -> { context.assertEquals(SERVICE_NAME, record.getName()); })); }
|
### Question:
JksServerConfigurator implements HttpServerConfigurator { private String getPath(ServerConfiguration configuration) { return configuration.getString(ConfigKies.SSL_JKS_PATH); } @Override void configureHttpServer(VertxContext context, HttpServerOptions options); }### Answer:
@Test public void givenSslEnabledInConfigurationWithJksPathAndPassword_whenConfiguringServer_thenHttpOptionSslShouldBeEnabledAndConfiguredWithThePathAndPassword() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configureServer(); assertThat(options.isSsl()).isTrue(); assertThat(options.getKeyStoreOptions() instanceof JksOptions).isTrue(); assertThat(options.getKeyStoreOptions().getPath()).isEqualTo(TEST_JKS_PATH); assertThat(options.getKeyStoreOptions().getPassword()).isEqualTo(TEST_JKS_SECRET); }
|
### Question:
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(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForARecordIncludingOutOfServicePassingNullFilter_thenShouldThrowException(TestContext context) throws Exception { lookupIncludeOutOfService(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForARecordIncludingOutOfService_thenShouldGetTheRecord(TestContext context) throws Exception { publishTestRecord(record.setStatus(Status.OUT_OF_SERVICE)); lookupIncludeOutOfService(r -> r.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(record -> { context.assertEquals(Status.OUT_OF_SERVICE, record.getStatus()); })); }
|
### Question:
VertxServiceDiscovery { public void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler) { serviceDiscovery.getRecord(jsonFilter, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@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 givenServiceDiscovery_whenLookupByJsonForARecordWithAName_thenShouldGetARecordWithThatName(TestContext context) throws Exception { publishTestRecord(record); lookupByJson(jsonFilter, context.asyncAssertSuccess(record -> { context.assertEquals(SERVICE_NAME, record.getName()); })); }
|
### Question:
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(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForAllRecordsPassingNullFilter_thenShouldThrowException() throws Exception { lookupAll(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsWithUnmatchingPredicate_thenShouldNotGetAnyRecord(TestContext context) throws Exception { publishTestRecord(record); publishTestRecord(otherRecord); lookupAll(record -> record.getName().equals(NOT_EXISTED_NAME), context.asyncAssertSuccess(records -> { context.assertTrue(records.isEmpty()); })); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsWithMatchingPredicate_thenShouldGetAllRecordsMatching(TestContext context) throws Exception { publishTestRecord(record); publishTestRecord(otherRecord); lookupAll(record -> record.getName().contains(SERVICE_NAME), context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); }
|
### Question:
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(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForAllRecordsIncludingOutOfServicePassingNullFilter_thenShouldThrowException(TestContext context) throws Exception { lookupAllIncludeOutOfService(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsIncludingOutOfService_thenShouldGetAllRecordsIncludingOutOfService(TestContext context) throws Exception { publishTestRecord(record.setStatus(Status.OUT_OF_SERVICE)); publishTestRecord(otherRecord); lookupAllIncludeOutOfService(record -> record.getName().contains(SERVICE_NAME), context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); }
|
### Question:
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<Record>> handler); void getHttpClient(Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler); void getWebClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); }### Answer:
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByFilter_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getHttpClient(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByFilterWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getHttpClient(record -> record.getName().equals(SERVICE_NAME), metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getHttpClient(jsonFilter, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getHttpClient(jsonFilter, metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
|
### Question:
VertxServiceDiscovery { public void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler) { serviceDiscovery.getRecords(jsonFilter, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@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 public void givenServiceDiscovery_whenLookupForAllRecordsWithNameByJson_thenShouldGetAllRecordsMatching(TestContext context) throws Exception { publishTestRecord(record.setMetadata(metadata)); publishTestRecord(otherRecord.setMetadata(metadata)); lookupAllByJson(metadata, context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); }
|
### Question:
VertxServiceDiscovery { public ServiceReference lookupForAReference(Record record) { return serviceDiscovery.getReference(record); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test public void givenServiceDiscovery_whenPublishServiceAndLookupForItsServiceReference_thenShouldGetTheReference(TestContext context) throws Exception { publishTestRecord(record, context.asyncAssertSuccess(record -> { assertNotNull(vertxServiceDiscovery.lookupForAReference(record)); })); }
|
### Question:
VertxServiceDiscovery { public ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration) { return serviceDiscovery.getReferenceWithConfiguration(record, configuration); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); }### Answer:
@Test public void givenServiceDiscovery_whenPublishServiceWithMetadataAndLookupForItsServiceReferencePassingConfiguration_thenShouldGetTheReferenceUponTheseConfigurations(TestContext context) throws Exception { publishTestRecord(record, context.asyncAssertSuccess(record -> { ServiceReference reference = vertxServiceDiscovery.lookupForAReferenceWithConfiguration(record, metadata); assertEquals(VALUE, reference.record().getMetadata().getString(KEY)); })); }
|
### Question:
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 newValue); }### Answer:
@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, ValueHolder.class, "value"); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent( new PropertyChangeEvent(unique, "value", true, false))); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent( new PropertyChangeEvent(unique, "value", false, true))); EasyMock.replay(listener); unique.addPropertyChangeListener(listener); v1.setValue("B"); v1.setValue("Bar"); EasyMock.verify(listener); }
|
### Question:
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); static int getIndexOfElement(Collection<E> set, Object child); static boolean containsAllAndOnly(List<?> c1, List<?> c2); static boolean nextLexicographicElement(int x[], int c[]); }### Answer:
@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(expected=IndexOutOfBoundsException.class) public void testGetElementAtIndexNegative() { CollectionUtil.getElementAtIndex(d_set, -1); }
|
### Question:
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 containsAllAndOnly(List<?> c1, List<?> c2); static boolean nextLexicographicElement(int x[], int c[]); }### Answer:
@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")); }
|
### Question:
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<E> set, int idx); static int getIndexOfElement(Collection<E> set, Object child); static boolean containsAllAndOnly(List<?> c1, List<?> c2); static boolean nextLexicographicElement(int x[], int c[]); }### Answer:
@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, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 1, 0, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 1, 1, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 1, 2, 0}, x); assertFalse(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 0, 0, 0}, x); assertFalse(CollectionUtil.nextLexicographicElement(new int[] { 0 }, new int[] { 1 })); assertTrue(CollectionUtil.nextLexicographicElement(new int[] { 0 }, new int[] { 2 })); }
|
### Question:
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 element); @Override E set(int index, E element); @Override E remove(int index); }### Answer:
@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.0; } }); }
@Test(expected=IllegalArgumentException.class) public void testAddBadValue() { d_list.add(-1); }
|
### Question:
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, E element); @Override E set(int index, E element); @Override E remove(int index); }### Answer:
@Test(expected=IllegalArgumentException.class) public void testSetBadValue() { d_list.set(1, -1); }
|
### Question:
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(index), element); } else { d_inner.add(d_inner.size(), element); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); }### Answer:
@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> list = new SortedSetModel<String>(Arrays.asList("Aa", "Ab", "Ba", "Bb")); ObservableList<String> aList = new FilteredObservableList<String>(list, new Predicate<String>(){ public boolean evaluate(String obj) { return obj.charAt(0) == 'A'; }}); ObservableList<String> bList = new FilteredObservableList<String>(list, new Predicate<String>(){ public boolean evaluate(String obj) { return obj.charAt(0) == 'B'; }}); assertEquals(Arrays.asList("Aa", "Ab"), aList); assertEquals(Arrays.asList("Ba", "Bb"), bList); list.add("Ac"); assertEquals(Arrays.asList("Aa", "Ab", "Ac"), aList); assertEquals(Arrays.asList("Ba", "Bb"), bList); }
@Test(expected=IllegalArgumentException.class) public void testAddNonAcceptable() { d_outer.add("Maarten"); }
|
### Question:
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.evaluate(d_inner.get(i))) { d_indices.add(first, i); } } final int inserted = d_indices.size() - oldSize; if (inserted > 0) { fireIntervalAdded(first, first + inserted - 1); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); }### Answer:
@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("Henk", "Bart")); assertEquals(Arrays.asList("Gert", "Henk", "Bart", "Jan"), d_outer); verify(mock); }
@Test public void testContentsUpdateAddAllEnd() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalAdded(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_ADDED, 2, 3))); replay(mock); d_outer.addListDataListener(mock); d_inner.addAll(Arrays.asList("Henk", "Bart")); assertEquals(Arrays.asList("Gert", "Jan", "Henk", "Bart"), d_outer); verify(mock); }
|
### Question:
ListMinimumSizeModel extends AbstractValueModel { public Boolean getValue() { return d_val; } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); }### Answer:
@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).getValue()); assertTrue(new ListMinimumSizeModel(new ArrayListModel<String>(Arrays.asList("Test", "Test")), 2).getValue()); }
|
### Question:
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); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); }### Answer:
@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); }
|
### Question:
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))); final int delta = upper - lower + 1; updateIndices(first, -delta); if (last > first) { fireIntervalRemoved(first, last - 1); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); }### Answer:
@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(Collections.emptyList(), d_outer); verify(mock); }
|
### Question:
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); } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); }### Answer:
@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", "Klees"), d_outer); }
@Test public void testContentsUpdateSetNoChangeExcl() { ListDataListener mock = createStrictMock(ListDataListener.class); replay(mock); d_outer.addListDataListener(mock); d_inner.set(3, "Paard"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); verify(mock); }
@Test(expected=IllegalArgumentException.class) public void testSetNonAcceptable() { d_outer.set(1, "Maarten"); }
|
### Question:
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); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); }### Answer:
@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, ListDataEvent.INTERVAL_ADDED, 0, 2))); replay(mock); d_outer.addListDataListener(mock); d_outer.setFilter(new Predicate<String>() { public boolean evaluate(String str) { return !str.equals("Gert"); } }); assertEquals(Arrays.asList("Daan", "Jan", "Klaas"), d_outer); verify(mock); }
|
### Question:
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); }### Answer:
@Test(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new ListMinimumSizeModel(new ArrayListModel<String>(), 2).setValue(true); }
|
### Question:
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(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }### Answer:
@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_filledList); resetFilledList(); ListIterator<String> it = d_filledList.listIterator(); int i = 0; while (it.hasNext()) { it.next(); if (i % 2 == 0) { it.remove(); } ++i; } assertEquals(Collections.singletonList("Gert"), d_filledList); }
|
### Question:
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); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }### Answer:
@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); }
|
### Question:
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 index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }### Answer:
@Test public void testGetSet() { assertEquals(new TreeSet<String>(d_filledList), d_filledList.getSet()); }
|
### Question:
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 Object subjectValue); void setExpected(Object expectedValue); }### Answer:
@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.propertyChange(JUnitUtil.eqPropertyChangeEvent(new PropertyChangeEvent(equalsModel, "value", true, false))); EasyMock.replay(listener); equalsModel.addPropertyChangeListener(listener); valueModel.setValue("naem"); EasyMock.verify(listener); }
|
### Question:
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 convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); }### Answer:
@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.propertyChange(JUnitUtil.eqPropertyChangeEvent(new PropertyChangeEvent(equalsModel, "value", true, false))); EasyMock.replay(listener); equalsModel.addPropertyChangeListener(listener); equalsModel.setExpected(15); EasyMock.verify(listener); }
|
### Question:
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 getCurrentDateWithoutTime(); }### Answer:
@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, woTime.getHours()); assertEquals(0, woTime.getMinutes()); assertEquals(0, woTime.getSeconds()); }
|
### Question:
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 double ilogit(double x); static EstimateWithPrecision logOddsRatio(
int a, int n, int c, int m, boolean corrected); static EstimateWithPrecision meanDifference(
double m0, double s0, double n0,
double m1, double s1, double n1); }### Answer:
@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); }
|
### Question:
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 addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); }### Answer:
@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); }
|
### Question:
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 addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); }### Answer:
@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); }
|
### Question:
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 ifTask, Task elTask, Condition condition); List<Task> getSources(); List<Task> getTargets(); boolean isReady(); List<Task> transition(); }### Answer:
@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, condition); source.start(); source.finish(); assertEquals(Collections.singletonList(ifTask), trans.transition()); verify(condition); }
@Test public void testFalseCondition() { MockTask source = new MockTask(); Task ifTask = new MockTask(); Task elTask = new MockTask(); Condition condition = createStrictMock(Condition.class); expect(condition.evaluate()).andReturn(false); replay(condition); Transition trans = new DecisionTransition(source, ifTask, elTask, condition); source.start(); source.finish(); assertEquals(Collections.singletonList(elTask), trans.transition()); verify(condition); }
|
### Question:
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }### Answer:
@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")).getValue()); }
|
### Question:
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(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }### Answer:
@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()); }
@Test public void testSimpleTransition() { 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(); assertEquals(Collections.singleton(end), model.getNextStates()); }
|
### Question:
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> getTransitions(); }### Answer:
@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.isFinished()); assertEquals(Collections.<Task>emptySet(), model.getNextStates()); }
|
### Question:
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); @Override String toString(); }### Answer:
@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 TaskProgressEvent(task, 0, 10)); listener.taskEvent(new TaskProgressEvent(task, 3, 10)); listener.taskEvent(new TaskProgressEvent(task, 6, 10)); listener.taskEvent(new TaskProgressEvent(task, 9, 10)); listener.taskEvent(new TaskProgressEvent(task, 10, 10)); listener.taskEvent(new TaskFinishedEvent(task)); replay(listener); task.addTaskListener(listener); task.run(); verify(listener); }
@Test public void testNotifyProgress2() { IterativeComputation comp = new ShortComputation(9); IterativeTask task = new IterativeTask(comp); task.setReportingInterval(3); TaskListener listener = createStrictMock(TaskListener.class); listener.taskEvent(new TaskStartedEvent(task)); listener.taskEvent(new TaskProgressEvent(task, 0, 9)); listener.taskEvent(new TaskProgressEvent(task, 3, 9)); listener.taskEvent(new TaskProgressEvent(task, 6, 9)); listener.taskEvent(new TaskProgressEvent(task, 9, 9)); listener.taskEvent(new TaskFinishedEvent(task)); replay(listener); task.addTaskListener(listener); task.run(); verify(listener); }
|
### Question:
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }### Answer:
@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); PropertyChangeListener mock = JUnitUtil.mockStrictListener(model, "value", false, true); model.addValueChangeListener(mock); holder.setValue("test"); holder.setValue("test2"); verify(mock); model.removeValueChangeListener(mock); mock = JUnitUtil.mockStrictListener(model, "value", true, false); model.addValueChangeListener(mock); holder.setValue(""); verify(mock); }
|
### Question:
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); }### Answer:
@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, StudentTTable.getT(150), 0.01); assertEquals(3 * StudentTTable.getT(160) / 4 + StudentTTable.getT(140) / 4, StudentTTable.getT(155), 0.01); }
|
### Question:
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(); }### Answer:
@Test public void testGetLength() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals(5.0, in.getLength(), 0.00001); }
|
### Question:
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.getUpperBound()))); } } } return false; } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@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, 6.0); Interval<Integer> in4 = new Interval<Integer>(1, 6); assertEquals(in, in3); assertEquals(in.hashCode(), in3.hashCode()); assertEquals(in2, in4); assertEquals(in2.hashCode(), in4.hashCode()); Interval<Double> in5 = new Interval<Double>(2.0, 5.0); assertNotEquals(in, in5); }
|
### Question:
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(); }### Answer:
@Test public void testToString() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals("1.0-6.0", in.toString()); }
|
### Question:
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(LogEvent event, ByteBufferDestination destination); @Override byte[] getFooter(); @Override byte[] getHeader(); @Override String getContentType(); @Override Map<String, String> getContentFormat(); @PluginBuilderFactory @SuppressWarnings("WeakerAccess") static Builder newBuilder(); }### Answer:
@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_lineSeparator_suffix(logEvent, false); }
|
### Question:
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_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); } }### Answer:
@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 = spy(new MainActivity()); when(activity.findViewById(R.id.text_weight)).thenReturn(weightText); when(activity.findViewById(R.id.text_height)).thenReturn(heightText); when(activity.findViewById(R.id.text_result)).thenReturn(resultText); when(activity.findViewById(R.id.button_calculate)).thenReturn(resultButton); when(activity.createButtonListener(weightText, heightText, resultText)).thenReturn(buttonListener); activity.initViews(); verify(activity, times(1)).createButtonListener(weightText, heightText, resultText); verify(resultButton, times(1)).setOnClickListener(buttonListener); }
|
### Question:
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, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }### Answer:
@Test public void static인start메소드를호출하면startService된다() { Context context = mock(Context.class); SaveBmiService.start(context, mock(BmiValue.class)); verify(context, times(1)).startService((Intent) any()); }
|
### Question:
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 = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }### Answer:
@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를전달하면아무것도하지않는다() { SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(mock(Intent.class)); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue)any()); }
@Test public void onHandleIntent에BmiValue형이외의데이터가들어간Intent를전달하면아무것도하지않는다() { Intent intent = mock(Intent.class); when(intent.getSerializableExtra(SaveBmiService.PARAM_KEY_BMI_VALUE)).thenReturn("hoge"); SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(intent); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue)any()); }
@Test public void onHandleIntent에바르게데이터가들어간Intent를전달하면데이터저장과Broadcast가이루어진다() { BmiValue bmiValue = mock(BmiValue.class); Intent intent = mock(Intent.class); when(intent.getSerializableExtra(SaveBmiService.PARAM_KEY_BMI_VALUE)).thenReturn(bmiValue); SaveBmiService service = spy(new SaveBmiService()); doReturn(false).when(service).saveToRemoteServer((BmiValue)any()); doNothing().when(service).sendLocalBroadcast(anyBoolean()); service.onHandleIntent(intent); verify(service, times(1)).sendLocalBroadcast(anyBoolean()); verify(service, times(1)).saveToRemoteServer((BmiValue)any()); }
|
### Question:
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, float weightInKg); }### Answer:
@Test(expected = RuntimeException.class) public void 신장에음수값을넘기면예외가발생한다() { calculator.calculate(-1f, 60.0f);
|
### Question:
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); }### Answer:
@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()); }
|
### Question:
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 path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@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); }
|
### Question:
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 eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; }### Answer:
@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); assertTrue(result.toString().matches("(0[1-9]|1[012]) (0[1-9]|[12][0-9]|3[01]) \\d{4}"), "date " + result); s = "Date(0,\"MM:dd:yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012]):(0[1-9]|[12][0-9]|3[01]):\\d{4}"), "date " + result); s = "Date(0,\"dd/MM/yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/\\d{4}"), "date " + result); }
@Test(invocationCount = 10) public void testEval() { System.out.println("Eval"); String s = "Concat(=Round(=Random(4)),[email protected])"; Object result = FParser.eval(s); assertTrue(result.toString().matches("[0-9]{4}[email protected]"), "random email " + result); }
|
### Question:
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 script); static List<String> FUNCTIONS; }### Answer:
@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)+'[email protected]'"; result = (String) JSONValue.parse(FParser.evaljs(script)); assertTrue(result.matches("test[0-9]{3}[email protected]"), "Test random email "); }
|
### Question:
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, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }### Answer:
@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); assertEquals(expResult, result); }
|
### Question:
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 passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }### Answer:
@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); }
|
### Question:
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; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } 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 passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }### Answer:
@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 = KeyMap.replaceKeys(in, KeyMap.USER_VARS, preserveKeys, 1, vMap); assertEquals(expResult, result); expResult = "this is a myscn/ts -> ts/rel for pro.tc/L2. "; result = KeyMap.replaceKeys(in, KeyMap.USER_VARS, preserveKeys, 2, vMap); assertEquals(expResult, result); }
@Test public void testReplaceKeys_String_Pattern() { System.out.println("replaceKeys"); 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.replaceKeys(in, KeyMap.ENV_VARS); assertEquals(expResult, result); }
|
### Question:
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/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }### Answer:
@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(File::getAbsolutePath).forEach(System.out::println); fail("Unable to fine preference file"); } }
|
### Question:
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("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }### Answer:
@Test(enabled = false) public void testSync() { System.out.println("sync"); ChromeEmulators.sync(); assertTrue(!ChromeEmulators.getEmulatorsList().isEmpty(), "EmulatorsList is Empty"); }
|
### Question:
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }### Answer:
@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 EmulatorsList" ); }
|
### Question:
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); final URL url; }### Answer:
@Test(enabled = false,description = "http-get of remote address") public void testGetHttp() throws Exception { System.out.println("Get-http"); URL targetUrl = new URL("http: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, getArgs.toJSONString()); assertEquals(result.get("args"), getArgs); }
@Test(enabled = false,description = "https-get of remote address") public void testGetHttps() throws Exception { System.out.println("Get-https"); URL targetUrl = new URL("https: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, getArgs.toJSONString()); assertEquals(result.get("args"), getArgs); }
@Test(enabled = false,description = "http-get of local address") public void testGetHttpLocal() throws Exception { System.out.println("Get-http-local"); URL targetUrl = new URL("http: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, "data", "vola"); assertEquals(result.toString(), "{\"data\":\"vola\"}"); }
|
### Question:
DriverSettings extends AbstractPropSettings { public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testGetChromeDriverPath() { String expResult; if (isWin) { expResult = "./lib/Drivers/chromedriver.exe"; } else { expResult = "./lib/Drivers/chromedriver"; } String result = ds.getChromeDriverPath(); assertEquals(result, expResult); }
|
### Question:
JIRAClient { public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, String tc, String ts, String rc,
String proj); void updateResult(int status, int eid); String addAttachment(int eid, File attachment); @SuppressWarnings("unchecked") JSONObject createIssue(JSONObject issue, List<File> attachments); @SuppressWarnings("unchecked") static JSONObject getJsonified(LinkedHashMap<String, String> dataMap); boolean containsProject(String project); boolean isConnected(); static final String ISSUE; }### Answer:
@Test(enabled = false) public void testConnection() throws MalformedURLException { JIRASync sync = new JIRASync(Data.server, Data.uname, Data.pass, Data.project); Assert.assertTrue(sync.isConnected()); }
|
### Question:
JIRAClient { @SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null && !attachments.isEmpty()) { List<JSONObject> attchRes = new ArrayList<>(); res.put("Attachments", attchRes); for (File f : attachments) { attchRes.add(client.post(new URL(client.url + restAttach), f)); } } else { LOG.log(Level.INFO, "no attachments to upload"); } LOG.log(Level.INFO, "issue response {0}", res.toString()); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return res; } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, String tc, String ts, String rc,
String proj); void updateResult(int status, int eid); String addAttachment(int eid, File attachment); @SuppressWarnings("unchecked") JSONObject createIssue(JSONObject issue, List<File> attachments); @SuppressWarnings("unchecked") static JSONObject getJsonified(LinkedHashMap<String, String> dataMap); boolean containsProject(String project); boolean isConnected(); static final String ISSUE; }### Answer:
@Test(enabled = false) public void testCreateIssue_JSONObject_List() throws MalformedURLException { JSONObject res = null; JIRAClient jc = new JIRAClient(Data.server, Data.uname, Data.pass, null); Map issue = getIssue(Data.project); List<File> attach = null; res = jc.createIssue((JSONObject) issue, attach); }
|
### Question:
DriverSettings extends AbstractPropSettings { public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testGetIEDriverPath() { String expResult = "./lib/Drivers/IEDriverServer.exe"; String result = ds.getIEDriverPath(); assertEquals(result, expResult); }
|
### Question:
DriverSettings extends AbstractPropSettings { public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testGetEdgeDriverPath() { String expResult = "./lib/Drivers/MicrosoftWebDriver.exe"; String result = ds.getEdgeDriverPath(); assertEquals(result, expResult); }
|
### Question:
DriverSettings extends AbstractPropSettings { public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testSetGeckcoDriverPath() { String path = "./lib/gk"; ds.setGeckcoDriverPath(path); assertEquals(ds.getGeckcoDriverPath(), path); }
|
### Question:
DriverSettings extends AbstractPropSettings { public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testSetChromeDriverPath() { String path = "./lib/chrome"; ds.setChromeDriverPath(path); assertEquals(ds.getChromeDriverPath(), path); }
|
### Question:
DriverSettings extends AbstractPropSettings { public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testSetIEDriverPath() { String path = "./lib/ie"; ds.setIEDriverPath(path); assertEquals(ds.getIEDriverPath(), path); }
|
### Question:
DriverSettings extends AbstractPropSettings { public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }### Answer:
@Test public void testSetEdgeDriverPath() { String path = "./lib/edge"; ds.setEdgeDriverPath(path); assertEquals(ds.getEdgeDriverPath(), path); }
|
### Question:
FParser { public static List<String> getFuncList() { return FUNCTIONS; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; }### Answer:
@Test public void testGetFuncList() { System.out.println("getFuncList"); String[] vals = {"Concat", "Random", "Round", "Pow", "Min", "Max", "Date"}; List<String> expResult = Arrays.asList(vals); Collections.sort(expResult); List<String> result = FParser.getFuncList(); Collections.sort(result); assertEquals(expResult.toString(), result.toString()); }
|
### Question:
RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } private RedisAppender(Builder builder); Configuration getConfig(); @Override String getName(); @Override Layout<? extends Serializable> getLayout(); @Override boolean ignoreExceptions(); @Override ErrorHandler getHandler(); @Override void setHandler(ErrorHandler errorHandler); @Override State getState(); RedisThrottlerJmxBean getJmxBean(); @Override void append(LogEvent event); @Override void initialize(); @Override void start(); @Override synchronized void stop(); @Override boolean isStarted(); @Override boolean isStopped(); @Override String toString(); @PluginBuilderFactory static Builder newBuilder(); }### Answer:
@Test public void test_messages_are_enqueued_to_redis() throws InterruptedException { LOGGER.debug("creating the logger"); Logger logger = LOGGER_CONTEXT_RESOURCE .getLoggerContext() .getLogger(RedisAppenderTest.class.getCanonicalName()); int expectedMessageCount = MIN_MESSAGE_COUNT + RANDOM.nextInt(MAX_MESSAGE_COUNT - MIN_MESSAGE_COUNT); LOGGER.debug("logging %d messages", expectedMessageCount); LogMessage[] expectedLogMessages = LogMessage.createRandomArray(expectedMessageCount); for (LogMessage expectedLogMessage : expectedLogMessages) { logger.log(expectedLogMessage.level, expectedLogMessage.message); } LOGGER.debug("waiting for throttler to kick in"); Thread.sleep(1_000); LOGGER.debug("checking logged messages"); Jedis redisClient = REDIS_CLIENT_RESOURCE.getClient(); for (int messageIndex = 0; messageIndex < expectedMessageCount; messageIndex++) { LogMessage expectedLogMessage = expectedLogMessages[messageIndex]; String expectedSerializedMessage = String.format( "%s %s", expectedLogMessage.level, expectedLogMessage.message); String actualSerializedMessage = redisClient.lpop(RedisAppenderTestConfig.REDIS_KEY); try { assertThat(actualSerializedMessage).isEqualTo(expectedSerializedMessage); } catch (ComparisonFailure comparisonFailure) { String message = String.format( "comparison failure (messageIndex=%d, messageCount=%d)", messageIndex, expectedMessageCount); throw new RuntimeException(message, comparisonFailure); } } Appender appender = LOGGER_CONTEXT_RESOURCE .getLoggerContext() .getConfiguration() .getAppender(RedisAppenderTestConfig.LOG4J2_APPENDER_NAME); assertThat(appender).isInstanceOf(RedisAppender.class); RedisThrottlerJmxBean jmxBean = ((RedisAppender) appender).getJmxBean(); assertThat(jmxBean.getTotalEventCount()).isEqualTo(expectedMessageCount); assertThat(jmxBean.getIgnoredEventCount()).isEqualTo(0); assertThat(jmxBean.getEventRateLimitFailureCount()).isEqualTo(0); assertThat(jmxBean.getByteRateLimitFailureCount()).isEqualTo(0); assertThat(jmxBean.getUnavailableBufferSpaceFailureCount()).isEqualTo(0); assertThat(jmxBean.getRedisPushSuccessCount()).isEqualTo(expectedMessageCount); assertThat(jmxBean.getRedisPushFailureCount()).isEqualTo(0); }
|
### Question:
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); static int KEY_LOCK_EXPIRE_TIME; static int KEY_LOCK_CYCLE_SLEEP_TIME; static Map<String, KeyLock> keyLockMap; }### Answer:
@Test public void testGetKeyLock() { KeyLock keylock = KeyLockManager.getKeyLock(TEST1); assertEquals(true, keylock != null); }
@Test public void testLockPartOneKey() { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(TEST1); String lockKey = "111"; boolean result = false; try { keyLock.lock(lockKey); result = true; } catch (KeyLockException e) { isKeyLockException = true; } catch (Exception e) { } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } assertEquals(true, result); }
@Test public void testLockPartTwoKey() { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(TEST1); String lockKey1 = "11"; String lockKey2 = "22"; boolean result = false; try { keyLock.lock(lockKey1, lockKey2); result = true; } catch (KeyLockException e) { isKeyLockException = true; } catch (Exception e) { } finally { if (!isKeyLockException) { keyLock.unlock(lockKey1, lockKey2); } else { } } assertEquals(true, result); }
|
### Question:
MsgManager { public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method = msgListener.getClass().getMethod(msgs.get(msg), new Class[] { MsgPacket.class }); if (msg == null || msg.equals("")) { if (MsgManager.log != null) { MsgManager.log.warn("消息类型为空,无法注册"); } continue; } ArrayList<Method> methodList = msgListenerMap.get(msg); if (methodList == null) { methodList = new ArrayList<Method>(); msgListenerMap.put(msg, methodList); } if (!methodList.contains(method)) { methodList.add(method); } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + method.getClass().getName() + "注册多遍,请及时处理"); } } if (!msgInstanceMap.containsKey(method)) { msgInstanceMap.put(method, msgListener); } else { if (MsgManager.log != null) { MsgManager.log.warn(method.getName() + "已经被实例化注册过,请及时处理"); } } msgClassInstanceMap.put(msgListener.getClass(), msgListener); } return true; } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + msgListener.getClass().getName() + "监控数据为空"); } return false; } } static void init(boolean useMsgMonitor, ILog log); static boolean addMsgListener(IMsgListener msgListener); static boolean dispatchMsg(String msgOpCode, Object data, Object otherData); static boolean handleMsg(MsgPacket msgPacket); static Map<String, ArrayList<Method>> msgListenerMap; static Map<Class<?>, Object> msgClassInstanceMap; static boolean USE_MSG_MONITOR; static ILog log; static Method method; }### Answer:
@Test public void testAddMsgListener() throws Exception { TestMsgListener testMsgListener = new TestMsgListener(); boolean result = MsgManager.addMsgListener(testMsgListener); MsgManager.dispatchMsg("createuser", 111, 222); assertEquals(true, result); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.