focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public CompletableFuture<Void> awaitAsync() { phaser.arriveAndDeregister(); return terminationFuture; }
@Test void testAwaitAsyncIsIdempotent() { final CompletableFuture<Void> awaitFuture = inFlightRequestTracker.awaitAsync(); assertThat(awaitFuture).isDone(); assertThat(awaitFuture) .as("The reference to the future must not change") .isSameAs(inFlightRequestTr...
@JsonIgnore public void configIgnoreFailureMode(StepAction action, WorkflowSummary summary) { ignoreFailureMode = action.getAction() == Actions.StepInstanceAction.KILL && (action.isWorkflowAction() || !(action.getWorkflowId().equals(summary.getWorkflowId()) ...
@Test public void testShouldIgnoreFailureMode() throws Exception { StepRuntimeSummary summary = loadObject( "fixtures/execution/sample-step-runtime-summary-1.json", StepRuntimeSummary.class); assertFalse(summary.isIgnoreFailureMode()); StepAction stepAction = mock(StepAction.class); ...
@Description("escape a string for use in URL query parameter names and values") @ScalarFunction @LiteralParameters({"x", "y"}) @Constraint(variable = "y", expression = "min(2147483647, x * 12)") @SqlType("varchar(y)") public static Slice urlEncode(@SqlType("varchar(x)") Slice value) { Es...
@Test public void testUrlEncode() { final String[][] outputInputPairs = { {"http%3A%2F%2Ftest", "http://test"}, {"http%3A%2F%2Ftest%3Fa%3Db%26c%3Dd", "http://test?a=b&c=d"}, {"http%3A%2F%2F%E3%83%86%E3%82%B9%E3%83%88", "http://\u30c6\u30b9\u30c8"}, ...
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()); if (handshakeReceived) { MySQLPacket responsePacket = dec...
@Test void assertDecodeUnsupportedProtocolVersion() { MySQLNegotiatePackageDecoder commandPacketDecoder = new MySQLNegotiatePackageDecoder(); assertThrows(IllegalArgumentException.class, () -> commandPacketDecoder.decode(channelHandlerContext, byteBuf, null)); }
@Override public String toString() { return toStringHelper(getClass()) .add("nextHeader", Byte.toString(nextHeader)) .add("fragmentOffset", Short.toString(fragmentOffset)) .add("moreFragment", Byte.toString(moreFragment)) .add("identification",...
@Test public void testToStringFragment() throws Exception { Fragment frag = deserializer.deserialize(bytePacket, 0, bytePacket.length); String str = frag.toString(); assertTrue(StringUtils.contains(str, "nextHeader=" + (byte) 0x11)); assertTrue(StringUtils.contains(str, "fragmentOff...
public boolean isValid() { return (mPrimaryColor != mPrimaryTextColor) && (mPrimaryDarkColor != mPrimaryTextColor); }
@Test public void isNotValidIfTextIsSame() { Assert.assertFalse(overlay(Color.GRAY, Color.GRAY, Color.GRAY).isValid()); Assert.assertFalse(overlay(Color.BLACK, Color.BLUE, Color.BLACK).isValid()); Assert.assertFalse(overlay(Color.MAGENTA, Color.WHITE, Color.WHITE).isValid()); }
public double bearingTo(final IGeoPoint other) { final double lat1 = Math.toRadians(this.mLatitude); final double long1 = Math.toRadians(this.mLongitude); final double lat2 = Math.toRadians(other.getLatitude()); final double long2 = Math.toRadians(other.getLongitude()); final dou...
@Test public void test_bearingTo_north() { final GeoPoint target = new GeoPoint(0.0, 0.0); final GeoPoint other = new GeoPoint(10.0, 0.0); assertEquals("directly north", 0, Math.round(target.bearingTo(other))); }
public static HealthStateScope forMaterial(Material material) { return new HealthStateScope(ScopeType.MATERIAL, material.getAttributesForScope().toString()); }
@Test public void shouldHaveAUniqueScopeForEachMaterial() { HealthStateScope scope1 = HealthStateScope.forMaterial(MATERIAL1); HealthStateScope scope2 = HealthStateScope.forMaterial(MATERIAL1); assertThat(scope1, is(scope2)); }
protected abstract void confuseTarget(String target);
@Test void testConfuseTarget() { assertEquals(0, appender.getLogSize()); this.method.confuseTarget(this.expectedTarget); assertEquals(this.expectedConfuseMethod, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); }
@Override // Camel calls this method if the endpoint isSynchronous(), as the // KafkaEndpoint creates a SynchronousDelegateProducer for it public void process(Exchange exchange) throws Exception { // is the message body a list or something that contains multiple values Message message = exch...
@Test public void processSendsMessageWithMessageKeyHeader() throws Exception { endpoint.getConfiguration().setTopic("someTopic"); Mockito.when(exchange.getIn()).thenReturn(in); Mockito.when(exchange.getMessage()).thenReturn(in); in.setHeader(KafkaConstants.KEY, "someKey"); p...
public static MacAddress valueOf(final String address) { if (!isValid(address)) { throw new IllegalArgumentException( "Specified MAC Address must contain 12 hex digits" + " separated pairwise by :'s."); } final String[] elements = addre...
@Test(expected = IllegalArgumentException.class) public void testValueOfInvalidStringWithTooShortOctet() throws Exception { MacAddress.valueOf(INVALID_MAC_OCTET_TOO_SHORT); }
public static Domain singleValue(Type type, Object value) { return new Domain(ValueSet.of(type, value), false); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testUncomparableSingleValue() { Domain.singleValue(HYPER_LOG_LOG, Slices.EMPTY_SLICE); }
@Override public Object parse(Object input) { return input; }
@Test public void passThrough_correctArgument() { // WHEN Object arguments = parser.parse("123"); // THEN assertThat((String) arguments).isEqualTo("123"); }
void flush() throws IOException { requireOpened(); stream.flush(); }
@Test void flushAfterCloseShouldThrowException() { assertThatExceptionOfType(IOException.class) .isThrownBy( () -> { final RefCountedFileWithStream fileUnderTest = getClosedRefCountedFileWithContent( ...
public List<String> build(TablePath tablePath) { List<String> sqls = new ArrayList<>(); StringBuilder createTableSql = new StringBuilder(); createTableSql .append("CREATE TABLE ") .append(tablePath.getSchemaAndTableName("\"")) .append(" (\n"); ...
@Test public void testBuild() { String dataBaseName = "test_database"; String tableName = "test_table"; TablePath tablePath = TablePath.of(dataBaseName, tableName); TableSchema tableSchema = TableSchema.builder() .column(PhysicalColumn.of("id",...
public Token generateToken(final Map<String, Object> claims) { final long currentTimeMillis = System.currentTimeMillis(); final Date tokenIssuedAt = new Date(currentTimeMillis); final Date accessTokenExpiresAt = DateUtils.addMinutes( new Date(currentTimeMillis), ...
@Test void givenClaims_whenGenerateToken_thenReturnValidToken() { // Given Map<String, Object> claims = Map.of("user_id", "12345"); when(tokenConfigurationParameter.getAccessTokenExpireMinute()).thenReturn(15); when(tokenConfigurationParameter.getRefreshTokenExpireDay()).thenReturn(...
public static Map<String, Object> map(String metricName, Metric metric) { final Map<String, Object> metricMap = Maps.newHashMap(); metricMap.put("full_name", metricName); metricMap.put("name", metricName.substring(metricName.lastIndexOf(".") + 1)); if (metric instanceof Timer) { ...
@Test public void mapSupportsHistogram() { final Histogram histogram = new Histogram(new UniformReservoir()); histogram.update(23); final Map<String, Object> map = MetricUtils.map("metric", histogram); assertThat(map) .containsEntry("type", "histogram") ...
public static boolean verify(@Nonnull UserModel currentUser, @Nonnull CertificateMetadata edsMetadata) { logger.info("Trying to match via user attributes and bin & taxCode..."); Map<String, List<String>> attrs = currentUser.getAttributes(); String bin = edsMetadata.getBin(), taxCode = edsMetadat...
@Test public void testVerifyEmptyData() { CertificateMetadata metadata = new CertificateMetadata(); metadata.withBin("BIN_VALUE"); metadata.withTaxCode("TAX_CODE_VALUE"); UserModel user = Mockito.mock(UserModel.class); HashMap<String, List<String>> attributes = new HashMap<>...
private MultiStepCombine( CombineFn<InputT, AccumT, OutputT> combineFn, Coder<KV<K, OutputT>> outputCoder) { this.combineFn = combineFn; this.outputCoder = outputCoder; }
@Test public void testMultiStepCombine() { PCollection<KV<String, Long>> combined = pipeline .apply( Create.of( KV.of("foo", 1L), KV.of("bar", 2L), KV.of("bizzle", 3L), KV.of("bar", 4L), ...
@VisibleForTesting static void initAddrUseFqdn(List<InetAddress> addrs) { useFqdn = true; analyzePriorityCidrs(); String fqdn = null; if (PRIORITY_CIDRS.isEmpty()) { // Get FQDN from local host by default. try { InetAddress localHost = InetAdd...
@Test(expected = IllegalAccessException.class) public void testGetStartWithFQDNNotFindAddr() { new MockUp<System>() { @Mock public void exit(int status) throws IllegalAccessException { throw new IllegalAccessException(); } }; new MockUp<Net...
@Override public String buildAuthRequestUrl(ServerConfiguration serverConfig, RegisteredClient clientConfig, String redirectUri, String nonce, String state, Map<String, String> options, String loginHint) { try { URIBuilder uriBuilder = new URIBuilder(serverConfig.getAuthorizationEndpointUri()); uriBuilder.add...
@Test(expected = AuthenticationServiceException.class) public void buildAuthRequestUrl_badUri() { Mockito.when(serverConfig.getAuthorizationEndpointUri()).thenReturn("e=mc^2"); Map<String, String> options = ImmutableMap.of("foo", "bar"); urlBuilder.buildAuthRequestUrl(serverConfig, clientConfig, "example.com"...
@Override @Nullable public String errorCode() { if (status.isOk()) return null; return status.getCode().name(); }
@Test void errorCode() { assertThat(response.errorCode()).isEqualTo("CANCELLED"); }
@Around(CLIENT_INTERFACE_PUBLISH_CONFIG_RPC) Object publishConfigAroundRpc(ProceedingJoinPoint pjp, ConfigPublishRequest request, RequestMeta meta) throws Throwable { final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_RPC; final List<ConfigCha...
@Test void testPublishConfigAroundRpcException() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); ConfigPublishRequest request ...
@Nullable public static <T extends KeyedStateHandle> T chooseTheBestStateHandleForInitial( @Nonnull List<T> restoreStateHandles, @Nonnull KeyGroupRange targetKeyGroupRange, double overlapFractionThreshold) { int pos = findTheBestStateHandleForInitial( ...
@Test public void testChooseTheBestStateHandleForInitial() { List<KeyedStateHandle> keyedStateHandles = new ArrayList<>(3); KeyedStateHandle keyedStateHandle1 = mock(KeyedStateHandle.class); when(keyedStateHandle1.getKeyGroupRange()).thenReturn(new KeyGroupRange(0, 3)); keyedStateH...
public void submitIndexingErrors(Collection<IndexingError> indexingErrors) { try { final FailureBatch fb = FailureBatch.indexingFailureBatch( indexingErrors.stream() .filter(ie -> { if (!ie.message().supportsFailureHandl...
@Test public void submitIndexingErrors_messageNotSupportingFailureHandlingNotSubmittedToQueue() throws Exception { // given final Message msg1 = Mockito.mock(Message.class); when(msg1.getMessageId()).thenReturn("msg-1"); when(msg1.supportsFailureHandling()).thenReturn(false); ...
public Stream<Hit> stream() { if (nPostingLists == 0) { return Stream.empty(); } return StreamSupport.stream(new PredicateSpliterator(), false); }
@Test void requireThatThereCanBeManyIntervals() { PredicateSearch search = createPredicateSearch( new byte[]{1}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010001, 0x00020002, 0x00030003, 0x000100ff, 0x00040004, 0x00050005, 0x00060006))); ...
@Override public boolean sendLeaderMessage(int currentId, int leaderId) { var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); instanceMap.keySet() .stream() .filter((i) -> i != currentId) .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); retur...
@Test void testSendLeaderMessage() { try { var instance1 = new BullyInstance(null, 1, 1); var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); Map<Integer, Instance> instanceMap = Map.of(1, instan...
public static void requestDeferredDeepLink(Context context, JSONObject params, String androidId, String oaid, JSONObject presetProperties, String url, boolean isSaveDeepLinkInfo) { if (mIsDeepLink) return; try { JSONObject jsonObject = new JSONObject(); String ids; St...
@Test public void requestDeferredDeepLink() { SAStoreManager.getInstance().remove(DbParams.PersistentName.REQUEST_DEFERRER_DEEPLINK); Assert.assertFalse(ChannelUtils.isExistRequestDeferredDeeplink()); Assert.assertTrue(ChannelUtils.isRequestDeferredDeeplink()); SensorsDataAPI.sharedI...
public static String getMaskedStatement(final String query) { try { final ParseTree tree = DefaultKsqlParser.getParseTree(query); return new Visitor().visit(tree); } catch (final Exception | StackOverflowError e) { return fallbackMasking(query); } }
@Test public void shouldNotMaskInvalidCreateStreamWithoutQuote() { // Given: // Typo in "WITH" => "WIT" final String query = "CREATE STREAM `stream` WIT (" + " format = 'avro', \n" + " kafka_topic = 'test_topic'," + "\"partitions\"= 3,\n" + ");"; // When fi...
public static List<HollowSchema> dependencyOrderedSchemaList(HollowDataset dataset) { return dependencyOrderedSchemaList(dataset.getSchemas()); }
@Test public void schemasAreSortedBasedOnDependencies() throws IOException { String schemasText = "TypeB {" + " ListOfString str;" + "}" + "" + "String {" + " string v...
public static String getHostName () { return getDefaults().vespaHostname(); }
@Test public void testSimple () { String name = LogUtils.getHostName(); assertNotNull(name); assertFalse(name.equals("")); }
public String getDiscriminatingValue(ILoggingEvent event) { // http://jira.qos.ch/browse/LBCLASSIC-213 Map<String, String> mdcMap = event.getMDCPropertyMap(); if (mdcMap == null) { return defaultValue; } String mdcValue = mdcMap.get(key); if (mdcValue == null)...
@Test public void nullMDC() { event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null); assertEquals(new HashMap<String, String>(), event.getMDCPropertyMap()); String discriminatorValue = discriminator.getDiscriminatingValue(event); assertEquals(DEFAULT_VAL, discriminatorVa...
static public void addOnConsoleListenerInstance(Context context, OnConsoleStatusListener onConsoleStatusListener) { onConsoleStatusListener.setContext(context); boolean effectivelyAdded = context.getStatusManager().add(onConsoleStatusListener); if (effectivelyAdded) { onConsoleStatusListener.start(); ...
@Test public void addOnConsoleListenerInstanceShouldNotStartSecondListener() { OnConsoleStatusListener ocl0 = new OnConsoleStatusListener(); OnConsoleStatusListener ocl1 = new OnConsoleStatusListener(); StatusListenerConfigHelper.addOnConsoleListenerInstance(context, ocl0); { ...
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) { final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps()); map.put( MetricCollectors.RESOURCE_LABEL_PREFIX + StreamsConfig.APPLICATION_ID_CONFIG, applicationId ); // Streams cli...
@Test public void shouldNotSetAutoOffsetResetByDefault() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.emptyMap()); final Object result = ksqlConfig.getKsqlStreamConfigProps().get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG); assertThat(result, is(nullValue())); }
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final List<Path> containers = new ArrayList<>(); for(Path file : files.keySet()) { if(containerService.isContainer(file)) { container...
@Test public void testDeleteFileBackslash() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Path test = new Path(container, String.format("%s\\%s", new AlphanumericRandomStringService().random(), ...
@Override public String toString() { return "EntryTaskScheduler{" + "numberOfEntries=" + size() + ", numberOfKeys=" + keys.size() + ", numberOfGroups=" + groups.size() + '}'; }
@Test public void test_toString() { scheduler = new SecondsBasedEntryTaskScheduler<>(taskScheduler, entryProcessor, FOR_EACH); assertNotNull(scheduler.toString()); }
@Override public ExecuteContext after(ExecuteContext context) { configService.init(RouterConstant.SPRING_CACHE_NAME, AppCache.INSTANCE.getAppName()); return context; }
@Test public void testAfter() { AppCache.INSTANCE.setAppName("foo"); interceptor.after(context); Assert.assertEquals(RouterConstant.SPRING_CACHE_NAME, configService.getCacheName()); Assert.assertEquals("foo", configService.getServiceName()); }
@Override protected void decode(ChannelHandlerContext ctx, Object object, List out) throws Exception { try { if (object instanceof XMLEvent) { final XMLEvent event = (XMLEvent) object; if (event.isStartDocument() || event.isEndDocument()) { r...
@Test public void testMergePublishMsg() throws Exception { List<Object> list = Lists.newArrayList(); xmlMerger.depth = 1; publishMsgEventList.forEach(xmlEvent -> { try { xmlMerger.decode(new ChannelHandlerContextAdapter(), xmlEvent, list); } catch (Exc...
@Override public ValidationResult validate(Object value) { ValidationResult result = super.validate(value); if (result instanceof ValidationResult.ValidationPassed) { final String sValue = (String)value; if (sValue.length() < minLength || sValue.length() > maxLength) { ...
@Test public void testValidateShortString() { assertThat(new LimitedStringValidator(2, 2).validate("1")) .isInstanceOf(ValidationResult.ValidationFailed.class); }
static String formatAuthorizationHeader(String clientId, String clientSecret, boolean urlencode) throws UnsupportedEncodingException { clientId = sanitizeString("the token endpoint request client ID parameter", clientId); clientSecret = sanitizeString("the token endpoint request client secret pa...
@Test public void testFormatAuthorizationHeaderMissingValues() { assertThrows(IllegalArgumentException.class, () -> HttpAccessTokenRetriever.formatAuthorizationHeader(null, "secret", false)); assertThrows(IllegalArgumentException.class, () -> HttpAccessTokenRetriever.formatAuthorizationHeader("id", ...
@Deprecated public static EnvironmentSettings fromConfiguration(ReadableConfig configuration) { return new EnvironmentSettings( (Configuration) configuration, Thread.currentThread().getContextClassLoader()); }
@Test void testFromConfiguration() { Configuration configuration = new Configuration(); configuration.setString("execution.runtime-mode", "batch"); EnvironmentSettings settings = EnvironmentSettings.newInstance().withConfiguration(configuration).build(); assertThat(s...
private void fail(long frameLength) { if (frameLength > 0) { throw new TooLongFrameException( "frame length exceeds " + maxFrameLength + ": " + frameLength + " - discarded"); } else { throw new TooLongFrameException( ...
@Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LenientDelimiterBasedFrameDecoder(1, true, false, false, Delimiters.nulDelimiter())); for (int i = 0; i < 2; i++) { ch.writeInbound(Unpooled.wrappedBuffe...
public MessageDescription shallowParseMessage(ByteBuf packet) { final ByteBuf buffer = packet.readSlice(MessageHeader.LENGTH); LOG.debug("Shallow parse header\n{}", ByteBufUtil.prettyHexDump(buffer)); final MessageHeader header = parseMessageHeader(buffer); final MessageDescription messa...
@Test public void onlyDataSets() throws IOException { final ByteBuf packet = Utils.readPacket("dataset-only.ipfix"); final IpfixParser.MessageDescription description = new IpfixParser(definitions).shallowParseMessage(packet); assertThat(description.templateRecords()).isEmpty(); ass...
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) { if ( from == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));...
@Test void invokeNumberWithGroupCharComma() { FunctionTestUtil.assertResult(numberFunction.invoke("9,876", ",", null), BigDecimal.valueOf(9876)); FunctionTestUtil.assertResult(numberFunction.invoke("9,876,000", ",", null), BigDecimal.valueOf(9876000)); }
@Override public void addAt(long offset, T value) { // we consider -1 a legal offset to account for loading values from the 0-0.checkpoint if (offset < -1) { throw new IllegalArgumentException( String.format("Next offset %d must be greater than or equal to -1", offset) ...
@Test void testAddAt() { TreeMapLogHistory<String> history = new TreeMapLogHistory<>(); assertThrows(IllegalArgumentException.class, () -> history.addAt(-2, "")); assertEquals(Optional.empty(), history.lastEntry()); history.addAt(-1, "-1"); assertEquals(Optional.of("-1"), hi...
public void serialize(Node node, JsonGenerator generator) { requireNonNull(node); Log.info("Serializing Node to JSON."); try { serialize(null, node, generator); } finally { generator.close(); } }
@Test void test() { CompilationUnit cu = parse("class X{java.util.Y y;}"); String serialized = serialize(cu, false); assertEquals( "{\"!\":\"com.github.javaparser.ast.CompilationUnit\",\"range\":{\"beginLine\":1,\"beginColumn\":1,\"endLine\":1,\"endColumn\":23},\"tokenRange...
@Override public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId, final ProcessorContext context, final long streamTime) { final TimestampedSegment segment = super.getOrCreateSegmentIfLiv...
@Test public void shouldGetCorrectSegmentString() { final TimestampedSegment segment = segments.getOrCreateSegmentIfLive(0, context, -1L); assertEquals("TimestampedSegment(id=0, name=test.0)", segment.toString()); }
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldBeAbleToAddSingleSubscription() { final long id = driverProxy.addSubscription(CHANNEL_4000, STREAM_ID_1); driverConductor.doWork(); final ArgumentCaptor<ReceiveChannelEndpoint> captor = ArgumentCaptor.forClass(ReceiveChannelEndpoint.class); verify(receiverProxy...
@Override public List<ServiceDTO> getServiceInstances(String serviceId) { String configName = SERVICE_ID_TO_CONFIG_NAME.get(serviceId); if (configName == null) { return Collections.emptyList(); } return assembleServiceDTO(serviceId, bizConfig.getValue(configName)); }
@Test public void testGetAdminServiceInstances() { String someUrl = "http://some-host/some-path"; String anotherUrl = "http://another-host/another-path"; when(bizConfig.getValue(adminServiceConfigName)) .thenReturn(String.format("%s,%s", someUrl, anotherUrl)); List<ServiceDTO> serviceDTOList ...
@Override public SparseVector getColumn(int i) { if (i < 0 || i > dim2) { throw new IllegalArgumentException("Invalid column index, must be [0,"+dim2+"), received " + i); } List<Integer> indexList = new ArrayList<>(); List<Double> valueList = new ArrayList<>(); fo...
@Test public void testGetColumn() { DenseSparseMatrix diagonal = DenseSparseMatrix.createDiagonal(new DenseVector(new double[] {1.618033988749894, Math.E, Math.PI})); SparseVector column = diagonal.getColumn(1); assertEquals(3, column.size()); assertEquals(0, column.get(0)); ...
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { var triggers = annotations.stream() .filter(te -> { for (var trigger : KoraSchedulingAnnotationProcessor.triggers) { if (te.getQualifiedName().contentEquals(t...
@Test void testScheduledJdkAtFixedRateTest() throws Exception { process(ScheduledJdkAtFixedRateTest.class); }
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Histogram histogram = registry.histogram(metricsName); Long value = endpoint.getValue(); Long fin...
@Test public void testProcessOverrideValue() throws Exception { when(endpoint.getValue()).thenReturn(VALUE); when(in.getHeader(HEADER_HISTOGRAM_VALUE, VALUE, Long.class)).thenReturn(VALUE + 3); producer.doProcess(exchange, endpoint, registry, METRICS_NAME); inOrder.verify(exchange, t...
@Override public void writeShort(final int v) throws IOException { ensureAvailable(SHORT_SIZE_IN_BYTES); MEM.putShort(buffer, ARRAY_BYTE_BASE_OFFSET + pos, (short) v); pos += SHORT_SIZE_IN_BYTES; }
@Test public void testWriteShortForPositionVByteOrder() throws Exception { short expected = 100; out.writeShort(1, expected, ByteOrder.LITTLE_ENDIAN); out.writeShort(3, expected, ByteOrder.BIG_ENDIAN); short actual1 = Bits.readShort(out.buffer, 1, false); short actual2 = Bits...
@Override public Long getTenantCountByPackageId(Long packageId) { return tenantMapper.selectCountByPackageId(packageId); }
@Test public void testGetTenantCountByPackageId() { // mock 数据 TenantDO dbTenant1 = randomPojo(TenantDO.class, o -> o.setPackageId(1L)); tenantMapper.insert(dbTenant1);// @Sql: 先插入出一条存在的数据 TenantDO dbTenant2 = randomPojo(TenantDO.class, o -> o.setPackageId(2L)); tenantMapper....
static void checkValidIndexName(String indexName) { if (indexName.length() > MAX_INDEX_NAME_LENGTH) { throw new IllegalArgumentException( "Index name " + indexName + " cannot be longer than " + MAX_INDEX_NAME_LENGTH + " characters."); } ...
@Test public void testCheckValidIndexNameThrowsErrorWhenNameBeginsWithUnderscore() { assertThrows(IllegalArgumentException.class, () -> checkValidIndexName("_test-index")); }
@SuppressWarnings("MethodLength") public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { messageHeaderDecoder.wrap(buffer, offset); final int templateId = messageHeaderDecoder.templateId(); final int schemaId = messageHeaderDecoder.s...
@Test void onFragmentIsANoOpIfSessionIdDoesNotMatchOnSessionMessage() { final int offset = 18; final long sessionId = 21; final long timestamp = 1000; sessionMessageHeaderEncoder .wrapAndApplyHeader(buffer, offset, messageHeaderEncoder) .clusterSessionId(s...
public static AtomicInteger getFailedPushMonitor() { return INSTANCE.failedPush; }
@Test void testGetFailedPush() { assertEquals(0, MetricsMonitor.getFailedPushMonitor().get()); assertEquals(1, MetricsMonitor.getFailedPushMonitor().incrementAndGet()); }
public Optional<PushEventDto> raiseEventOnIssue(String projectUuid, DefaultIssue currentIssue) { var currentIssueComponentUuid = currentIssue.componentUuid(); if (currentIssueComponentUuid == null) { return Optional.empty(); } var component = treeRootHolder.getComponentByUuid(currentIssueComponen...
@Test public void raiseEventOnIssue_whenClosedHotspot_shouldCreateClosedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setNew(false) .setCopied(false) .setBeingClosed(true) .setStatus(Issue.STATUS_CLOSED) .setResolution(Issue.RES...
public static void main(String[] args) { final var logger = LoggerFactory.getLogger(App.class); Function<Integer, Integer> timesTwo = x -> x * 2; Function<Integer, Integer> square = x -> x * x; Function<Integer, Integer> composedFunction = FunctionComposer.composeFunctions(timesTwo, square); int r...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public String formatSmsTemplateContent(String content, Map<String, Object> params) { return StrUtil.format(content, params); }
@Test public void testFormatSmsTemplateContent() { // 准备参数 String content = "正在进行登录操作{operation},您的验证码是{code}"; Map<String, Object> params = MapUtil.<String, Object>builder("operation", "登录") .put("code", "1234").build(); // 调用 String result = smsTemplateServ...
@Override public void remove(NamedNode master) { connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName()); }
@Test public void testRemove() { Collection<RedisServer> masters = connection.masters(); connection.remove(masters.iterator().next()); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test public void testMove() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path test = new BoxTouchFeature(session, fileid).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.fi...
public DoubleArrayAsIterable usingExactEquality() { return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_successWithInfinity() { assertThat(array(1.1, POSITIVE_INFINITY, 3.3)).usingExactEquality().contains(POSITIVE_INFINITY); }
@Override public Iterable<ConnectorFactory> getConnectorFactories() { return ImmutableList.of(new ClickHouseConnectorFactory("clickhouse", getClassLoader())); }
@Test public void testCreateConnector() { Plugin plugin = new ClickHousePlugin(); ConnectorFactory factory = getOnlyElement(plugin.getConnectorFactories()); factory.create("test", ImmutableMap.of("clickhouse.connection-url", "jdbc:clickhouse://test"), new TestingConnectorContext()); ...
public MemorySize divide(long by) { if (by < 0) { throw new IllegalArgumentException("divisor must be != 0"); } return new MemorySize(bytes / by); }
@Test void testDivideByNegativeLong() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy( () -> { final MemorySize memory = new MemorySize(100L); memory.divide(-23L); ...
public static int toSignedInt(long x) { return (int) x; }
@Test public void testUnsignedConversions() { long l = Integer.toUnsignedLong(-1); assertEquals(4294967295L, l); assertEquals(-1, BitUtil.toSignedInt(l)); int intVal = Integer.MAX_VALUE; long maxInt = intVal; assertEquals(intVal, BitUtil.toSignedInt(maxInt)); ...
public void setProperty(String name, String value) { if (value == null) { return; } name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); if (prop == null) { addWarn("No such property [" + name + "] in " + objClass.getName() + "."); } else ...
@Test public void testDuration() { setter.setProperty("duration", "1.4 seconds"); assertEquals(1400, house.getDuration().getMilliseconds()); }
@Override public DefaultBasicAuthRuleHandle parseHandleJson(final String handleJson) { try { return GsonUtils.getInstance().fromJson(handleJson, DefaultBasicAuthRuleHandle.class); } catch (Exception exception) { LOG.error("Failed to parse json , please check json format", exc...
@Test public void testParseHandleJson() { String handleJson = "{\"authorization\":\"test:test123\"}"; MatcherAssert.assertThat(defaultBasicAuthAuthenticationStrategy.parseHandleJson(handleJson), notNullValue(DefaultBasicAuthRuleHandle.class)); MatcherAssert.assertThat(defaultBasicAuthAuthent...
@VisibleForTesting protected void setInitialFlushTime(Date now) { // Start with the beginning of the current hour nextFlush = Calendar.getInstance(); nextFlush.setTime(now); nextFlush.set(Calendar.MILLISECOND, 0); nextFlush.set(Calendar.SECOND, 0); nextFlush.set(Calendar.MINUTE, 0); // In...
@Test public void testSetInitialFlushTime() { RollingFileSystemSink rfsSink = new RollingFileSystemSink(1000, 0); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR, ...
@NonNull @Override public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException { return Stapler.lookupConverter(target) .convert( target, context.getSecretSourceResolver() ...
@Test public void _string() throws Exception { Configurator c = registry.lookupOrFail(String.class); final Object value = c.configure(new Scalar("abc"), context); assertEquals("abc", value); }
public synchronized void set(float progress) { if (Float.isNaN(progress)) { progress = 0; LOG.debug("Illegal progress value found, progress is Float.NaN. " + "Progress will be changed to 0"); } else if (progress == Float.NEGATIVE_INFINITY) { progress = 0; LOG.debug("Illegal p...
@Test public void testSet(){ Progress progress = new Progress(); progress.set(Float.NaN); Assert.assertEquals(0, progress.getProgress(), 0.0); progress.set(Float.NEGATIVE_INFINITY); Assert.assertEquals(0,progress.getProgress(),0.0); progress.set(-1); Assert.assertEquals(0,progress.getPro...
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testDecodeMultipleDynamicStructStaticDynamicArrays() { String rawInput = "0x0000000000000000000000000000000000000000000000000000000000000140" + "0000000000000000000000000000000000000000000000000000000000000000" + "000000000000...
@Override public List<Long> getAllAvailableNodes() { List<Long> nodeIds = Lists.newArrayList(); if (usedComputeNode || availableID2Backend.isEmpty()) { nodeIds.addAll(availableID2ComputeNode.keySet()); } if (preferComputeNode) { return nodeIds; } ...
@Test public void testSelectBackendAndComputeNode() { new MockUp<SystemInfoService>() { @Mock public ImmutableMap<Long, ComputeNode> getIdToBackend() { return availableId2Backend; } @Mock public ImmutableMap<Long, ComputeNode> getI...
@Override public URL getResource(String name) { ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resource '{}'", name); for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) { URL url = null; ...
@Test void parentFirstGetResourceExistsInParent() throws IOException, URISyntaxException { URL resource = parentFirstPluginClassLoader.getResource("META-INF/file-only-in-parent"); assertFirstLine("parent", resource); }
static Runnable decorateRunnable(Observation observation, Runnable runnable) { return () -> observation.observe(runnable); }
@Test public void shouldDecorateRunnable() throws Throwable { Runnable timedRunnable = Observations.decorateRunnable(observation, helloWorldService::sayHelloWorld); timedRunnable.run(); assertThatObservationWasStartedAndFinishedWithoutErrors(); then(helloWorldService).should(times(...
@Override public void release(String permitId) { get(releaseAsync(permitId)); }
@Test public void testReleaseWithoutPermits() { Assertions.assertThrows(RedisException.class, () -> { RPermitExpirableSemaphore s = redisson.getPermitExpirableSemaphore("test"); s.release("1234"); }); }
public Entry getRoot() { return parent == null ? this : parent.getRoot(); }
@Test public void selfIsRoot() { final Entry entry = new Entry(); assertThat(entry.getRoot(), equalTo(entry)); }
public static Coordinate bd09ToGcj02(double lng, double lat) { double x = lng - 0.0065; double y = lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI); double gg_lng = z * Math.cos(theta); double gg_lat = z * Math.s...
@Test public void bd09toGcj02Test() { final CoordinateUtil.Coordinate coordinate = CoordinateUtil.bd09ToGcj02(116.404, 39.915); assertEquals(116.39762729119315D, coordinate.getLng(), 0); assertEquals(39.90865673957631D, coordinate.getLat(), 0); }
public static List<String> getJavaOpts(Configuration conf) { String adminOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_KEY, YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_DEFAULT); String userOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_KEY, ...
@Test public void testDefaultJavaOptionsWhenExtraJDK17OptionsAreNotConfigured() throws Exception { ContainerLocalizerWrapper wrapper = new ContainerLocalizerWrapper(); ContainerLocalizer localizer = wrapper.setupContainerLocalizerForTest(); Configuration conf = new Configuration(); conf.setBoolean(Ya...
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String appId = accessKeyUtil.extractAppIdFromRequest(r...
@Test public void testRequestTimeTooSkewed() throws Exception { String appId = "someAppId"; List<String> secrets = Lists.newArrayList("someSecret"); String oneMinAgoTimestamp = Long.toString(System.currentTimeMillis() - 61 * 1000); when(accessKeyUtil.extractAppIdFromRequest(any())).thenReturn(appId);...
public List<String> getAddresses() { if (args.length < 3) { return Collections.singletonList(DEFAULT_BIND_ADDRESS); } List<String> addresses = Arrays.asList(args[2].split(",")); return addresses.stream().filter(InetAddresses::isInetAddress).collect(Collectors.toList()); }
@Test void assertGetAddressesWithThreeArguments() { assertThat(new BootstrapArguments(new String[]{"3306", "test_conf", "127.0.0.1"}).getAddresses(), is(Collections.singletonList("127.0.0.1"))); assertThat(new BootstrapArguments(new String[]{"3306", "test_conf", "1.1.1.1,127.0.0.1"}).getAddresses(),...
public HCatRecord getWritable() throws HCatException { DefaultHCatRecord d = new DefaultHCatRecord(); d.copy(this); return d; }
@Test public void testGetWritable() throws Exception { HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector()).getWritable(); Assert.assertEquals(INT_CONST, ((Integer) r.get(0)).intValue()); Assert.assertEquals(LONG_CONST, ((Long) r.get(1)).longValue()); Assert.assertEquals(DOUBLE_CON...
@Override public HashSlotCursor12byteKey cursor() { return new CursorIntKey2(); }
@Test(expected = AssertionError.class) public void testCursor_key2_whenDisposed() { HashSlotCursor12byteKey cursor = hsa.cursor(); hsa.dispose(); cursor.key2(); }
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void workerAddrUpdateWithIdUnchanged() throws Exception { JumpHashPolicy policy = new JumpHashPolicy(mConf); List<WorkerInfo> workers = new ArrayList<>(); workers.add(new WorkerInfo().setIdentity(WorkerIdentityTestUtils.ofLegacyId(1L)) .setAddress(new WorkerNetAddress().setHost("host1...
public T get(K key) { T metric = metrics.get(key); if (metric == null) { metric = factory.createInstance(key); metric = MoreObjects.firstNonNull(metrics.putIfAbsent(key, metric), metric); } return metric; }
@Test public void testGet() { assertThat(metricsMap.tryGet("foo"), nullValue(AtomicLong.class)); AtomicLong foo = metricsMap.get("foo"); assertThat(metricsMap.tryGet("foo"), sameInstance(foo)); }
@VisibleForTesting public void validateSmsTemplateCodeDuplicate(Long id, String code) { SmsTemplateDO template = smsTemplateMapper.selectByCode(code); if (template == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if (id == null) { throw exception(...
@Test public void testValidateDictDataValueUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String code = randomString(); // mock 数据 smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); // 调用,校验异常 assertServiceException(() ...
@Override public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) { if (segments.isEmpty()) { return segments; } // For LIMIT 0 case, keep one segment to create the schema int limit = query.getLimit(); if (limit == 0) { return Collections.singletonList(segment...
@Test public void testUpsertTable() { List<IndexSegment> indexSegments = Arrays .asList(getIndexSegment(0L, 10L, 10, true), getIndexSegment(20L, 30L, 10, true), getIndexSegment(40L, 50L, 10, true)); // Should not prune any segment for upsert table QueryContext queryContext = QueryCont...
public RuntimeProfile buildTopLevelProfile(boolean isFinished) { RuntimeProfile profile = new RuntimeProfile("Load"); RuntimeProfile summaryProfile = new RuntimeProfile("Summary"); summaryProfile.addInfoString(ProfileManager.QUERY_ID, DebugUtil.printId(getLoadId())); summaryProfile.addIn...
@Test public void testBuildTopLevelProfile(@Mocked GlobalStateMgr globalStateMgr, @Mocked GlobalTransactionMgr globalTransactionMgr, @Mocked TransactionState transactionState) { new Expectations() { { ...
@UdafFactory(description = "Compute sample standard deviation of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint, M2 double>") public static TableUdaf<Integer, Struct, Double> stdDevInt() { return getStdDevImplementation( 0, STRUCT_INT, (agg, newValue)...
@Test public void shouldAverageEmpty() { final TableUdaf<Integer, Struct, Double> udaf = stdDevInt(); final Struct agg = udaf.initialize(); final double standardDev = udaf.map(agg); assertThat(standardDev, equalTo(0.0)); }
static SelType callJavaMethod(Object javaObj, SelType[] args, MethodHandle m, String methodName) { try { if (args.length == 0) { return callJavaMethod0(javaObj, m); } else if (args.length == 1) { return callJavaMethod1(javaObj, args[0], m); } else if (args.length == 2) { re...
@Test public void testCallJavaMethodWithoutArg() throws Throwable { m1 = MethodHandles.lookup() .findStatic(MockType.class, "staticNoArg", MethodType.methodType(void.class)); m2 = MethodHandles.lookup() .findVirtual(MockType.class, "noArg", MethodType.methodType(String....
public static Map<String, String> alterCurrentAttributes(boolean create, Map<String, Attribute> all, ImmutableMap<String, String> currentAttributes, ImmutableMap<String, String> newAttributes) { Map<String, String> init = new HashMap<>(); Map<String, String> add = new HashMap<>(); Map<S...
@Test(expected = RuntimeException.class) public void alterCurrentAttributes_UpdateMode_DeleteNonExistentAttribute_ShouldThrowException() { ImmutableMap<String, String> newAttributes = ImmutableMap.of("-attr4", "value4"); AttributeUtil.alterCurrentAttributes(false, allAttributes, currentAttributes, n...
static long initNotifyWarnTimeout() { String notifyTimeouts = System.getProperty("nacos.listener.notify.warn.timeout"); if (StringUtils.isNotBlank(notifyTimeouts) && NumberUtils.isDigits(notifyTimeouts)) { notifyWarnTimeout = Long.valueOf(notifyTimeouts); LOGGER.info("config list...
@Test void testNotifyWarnTimeout() { System.setProperty("nacos.listener.notify.warn.timeout", "5000"); long notifyWarnTimeout = CacheData.initNotifyWarnTimeout(); assertEquals(5000, notifyWarnTimeout); System.setProperty("nacos.listener.notify.warn.timeout", "1bf000abc"); lon...
@Override public float floatValue() { return value; }
@Test void testDoubleNegative() throws IOException { // PDFBOX-4289 COSFloat cosFloat = new COSFloat("--16.33"); assertEquals(-16.33f, cosFloat.floatValue()); }
public void generate() throws IOException { packageNameByTypes.clear(); generatePackageInfo(); generateTypeStubs(); generateMessageHeaderStub(); for (final List<Token> tokens : ir.messages()) { final Token msgToken = tokens.get(0); final List<...
@Test void shouldGeneratePrecedenceChecksWhenEnabled() throws Exception { final PrecedenceChecks.Context context = new PrecedenceChecks.Context() .shouldGeneratePrecedenceChecks(true); final PrecedenceChecks precedenceChecks = PrecedenceChecks.newInstance(context); generator(...
@Override public YamlUserConfiguration swapToYamlConfiguration(final ShardingSphereUser data) { if (null == data) { return null; } YamlUserConfiguration result = new YamlUserConfiguration(); result.setUser(data.getGrantee().toString()); result.setPassword(data.get...
@Test void assertSwapToYamlConfiguration() { YamlUserConfiguration actual = new YamlUserSwapper().swapToYamlConfiguration(new ShardingSphereUser("foo_user", "foo_pwd", "127.0.0.1")); assertNotNull(actual); assertThat(actual.getUser(), is("foo_user@127.0.0.1")); assertThat(actual.getP...
public static String asRomanNumeralsLower(int i) { return asRomanNumerals(i).toLowerCase(Locale.ROOT); }
@Test public void testRomanLower() { assertEquals("i", AutoPageNumberUtils.asRomanNumeralsLower(1)); assertEquals("xxvi", AutoPageNumberUtils.asRomanNumeralsLower(26)); assertEquals("xxvii", AutoPageNumberUtils.asRomanNumeralsLower(27)); }
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testCallSelf() { run("call-self.feature"); matchContains(fr.result.getVariables(), "{ result: 'second' }"); }
String getEstimatedRunTimeRemaining(boolean inSeconds) { // Calculate the amount of energy lost every tick. // Negative weight has the same depletion effect as 0 kg. >64kg counts as 64kg. final int effectiveWeight = Math.min(Math.max(client.getWeight(), 0), 64); // 100% energy is 10000 energy units int ener...
@Test public void testEstimatedRuntimeRemaining() { ItemContainer equipment = mock(ItemContainer.class); when(client.getItemContainer(InventoryID.EQUIPMENT)).thenReturn(equipment); when(equipment.count(RING_OF_ENDURANCE)).thenReturn(1); when(client.getVarbitValue(Varbits.RUN_SLOWED_DEPLETION_ACTIVE)).thenRetu...
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldAnonymizeAlterOptionCorrectly() { final String output = anon.anonymize( "ALTER STREAM my_stream ADD COLUMN c3 INT, ADD COLUMN c4 INT;"); Approvals.verify(output); }
public static <E> List<E> filterToList(Iterator<E> iter, Filter<E> filter) { return toList(filtered(iter, filter)); }
@Test public void filterToListTest(){ final List<String> obj2 = ListUtil.toList("3"); final List<String> obj = ListUtil.toList("1", "3"); final List<String> filtered = IterUtil.filterToList(obj.iterator(), obj2::contains); assertEquals(1, filtered.size()); assertEquals("3", filtered.get(0)); }