focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean doNotLoadBalance() { return _doNotLoadBalance; }
@Test public void testDoNotLoadBalance() { boolean doNotLoadBalance = true; _trackerClient = new TrackerClientImpl(URI.create("uri"), new HashMap<>(), null, SystemClock.instance(), 1000, (test) -> false, false, false, doNotLoadBalance); Assert.assertEquals(_trackerClient.doNotLoadBalance(), doNotLoadBa...
@Override public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) { if (!shouldHandle(instances)) { return instances; } List<Object> result = getTargetInstancesByRules(targetName, instances); return super.handle(targetName, result, ...
@Test public void testGetTargetInstancesByGlobalRules() { RuleInitializationUtils.initGlobalTagMatchRules(); List<Object> instances = new ArrayList<>(); ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0"); instances.add(instance1); Se...
@Override public void deleteDictType(Long id) { // 校验是否存在 DictTypeDO dictType = validateDictTypeExists(id); // 校验是否有字典数据 if (dictDataService.getDictDataCountByDictType(dictType.getType()) > 0) { throw exception(DICT_TYPE_HAS_CHILDREN); } // 删除字典类型 ...
@Test public void testDeleteDictType_success() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbDictType.getId(); // 调用 dictTypeService.deleteDictType(id); // 校验数据不存在了 ...
static <T> T getWildcardMappedObject(final Map<String, T> mapping, final String query) { T value = mapping.get(query); if (value == null) { for (String key : mapping.keySet()) { // Turn the search key into a regex, using all characters but the * as a literal. ...
@Test public void testSubdirWildcardExtension() throws Exception { // Setup test fixture. final Map<String, Object> haystack = Map.of("myplugin/baz/*.jsp", new Object()); // Execute system under test. final Object result = PluginServlet.getWildcardMappedObject(haystack, "myplugi...
public ModeConfiguration getModeConfiguration() { return null == modeConfig ? new ModeConfiguration("Standalone", null) : modeConfig; }
@Test void assertGetModeConfiguration() { ModeConfiguration modeConfig = new ModeConfiguration("Cluster", mock(PersistRepositoryConfiguration.class)); ContextManagerBuilderParameter param = new ContextManagerBuilderParameter(modeConfig, Collections.emptyMap(), Collections.emptyMap(),...
@Override public String getSqlSelect(Table table) { List<Column> columns = table.getColumns(); StringBuilder sb = new StringBuilder("SELECT\n"); for (int i = 0; i < columns.size(); i++) { sb.append(" "); if (i > 0) { sb.append(","); } ...
@Test void getSqlSelect() { SubAbstractDriver ad = new SubAbstractDriver(); String result = ad.getSqlSelect(table); assertThat( result, equalTo("SELECT\n `column1` -- comment abc \n" + " ,`column2` -- comment abc \n" ...
@Override public double cost(Link link, ResourceContext context) { // explicitly call a method not depending on LinkResourceService return cost(link); }
@Test public void testCost() { sut = new LatencyConstraint(Duration.of(10, ChronoUnit.NANOS)); assertThat(sut.cost(link1, resourceContext), is(closeTo(Double.parseDouble(LATENCY1), 1.0e-6))); assertThat(sut.cost(link2, resourceContext), is(closeTo(Double.parseDouble(LATENCY2), 1.0e-6))); ...
@Override public String getBucketId(IN element, BucketAssigner.Context context) { if (dateTimeFormatter == null) { dateTimeFormatter = DateTimeFormatter.ofPattern(formatString).withZone(zoneId); } return dateTimeFormatter.format(Instant.ofEpochMilli(context.currentProcessingTime(...
@Test void testGetBucketPathWithSpecifiedFormatString() { DateTimeBucketAssigner bucketAssigner = new DateTimeBucketAssigner("yyyy-MM-dd-HH", ZoneId.of("America/Los_Angeles")); assertThat(bucketAssigner.getBucketId(null, mockedContext)).isEqualTo("2018-08-03-23"); }
@Override public <T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess( KeyedPartitionStream<K, T_OTHER> other, TwoInputNonBroadcastStreamProcessFunction<V, T_OTHER, OUT> processFunction) { validateStates( processFunction.usesStates(), ...
@Test void testStateErrorWithConnectKeyedStream() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); KeyedPartitionStream<Integer, Integer> stream = createKeyedStream(env); assertThatThrownBy( () -> stream.conn...
@Override public Set<String> toStrings(Set<SystemScope> scope) { if (scope == null) { return null; } else { return new LinkedHashSet<>(Collections2.filter(Collections2.transform(scope, systemScopeToString), Predicates.notNull())); } }
@Test public void toStrings() { // check null condition assertThat(service.toStrings(null), is(nullValue())); assertThat(service.toStrings(allScopes), equalTo(allScopeStrings)); assertThat(service.toStrings(allScopesWithValue), equalTo(allScopeStringsWithValue)); }
public static String processingLogStreamCreateStatement( final ProcessingLogConfig config, final KsqlConfig ksqlConfig ) { return processingLogStreamCreateStatement( config.getString(ProcessingLogConfig.STREAM_NAME), getTopicName(config, ksqlConfig) ); }
@Test public void shouldBuildCorrectStreamCreateDDLWithDefaultTopicName() { // Given: serviceContext.getTopicClient().createTopic(DEFAULT_TOPIC, 1, (short) 1); // When: final String statement = ProcessingLogServerUtils.processingLogStreamCreateStatement( new ProcessingLogConfig( ...
@Override public void upgrade() { // Only run this migration once. if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } final IndexSetConfig indexSetConfig = findDefaultIndexSet(); fina...
@Test public void upgradeWhenAlreadyCompleted() throws Exception { final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class); when(indexSetService.findAll()).thenReturn(Collections.singletonList(indexSetConfig)); when(indexSetConfig.id()).thenReturn("abc123"); when(clusterCon...
public static <T> PrefetchableIterable<T> fromArray(T... values) { if (values.length == 0) { return emptyIterable(); } return new Default<T>() { @Override public PrefetchableIterator<T> createIterator() { return PrefetchableIterators.fromArray(values); } }; }
@Test public void testDefaultPrefetch() { PrefetchableIterable<String> iterable = new Default<String>() { @Override protected PrefetchableIterator<String> createIterator() { return new ReadyAfterPrefetchUntilNext<>( PrefetchableIterators.fromArray("A", "B", ...
public StreamDestinationFilterRuleDTO createForStream(String streamId, StreamDestinationFilterRuleDTO dto) { if (!isBlank(dto.id())) { throw new IllegalArgumentException("id must be blank"); } // We don't want to allow the creation of a filter rule for a different stream, so we enfo...
@Test void createForStream() { final var result = service.createForStream("stream-1", StreamDestinationFilterRuleDTO.builder() .title("Test") .description("A Test") .streamId("stream-1") .destinationType("indexer") .status(Strea...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testEqInt96() throws Exception { BinaryColumn b = binaryColumn("int96_field"); // INT96 ordering is undefined => no filtering shall be done assertFalse("Should not drop block for -2", canDrop(eq(b, toBinary("-2", 12)), ccmd, dictionaries)); assertFalse("Should not drop block for -1...
@Override public Mono<ServerResponse> handle(ServerRequest request) { String name = request.pathVariable("name"); return request.bodyToMono(Unstructured.class) .filter(unstructured -> unstructured.getMetadata() != null && StringUtils.hasText(unstructured.getMetadata().get...
@Test void shouldHandleCorrectly() { final var fake = new FakeExtension(); var metadata = new Metadata(); metadata.setName("my-fake"); fake.setMetadata(metadata); var unstructured = new Unstructured(); unstructured.setMetadata(metadata); unstructured.setApiVe...
@Override public void start(long checkpointId, CheckpointOptions checkpointOptions) { LOG.debug("{} starting checkpoint {} ({})", taskName, checkpointId, checkpointOptions); ChannelStateWriteResult result = new ChannelStateWriteResult(); ChannelStateWriteResult put = results....
@Test void testLimit() throws IOException { int maxCheckpoints = 3; try (ChannelStateWriterImpl writer = new ChannelStateWriterImpl( JOB_VERTEX_ID, TASK_NAME, SUBTASK_INDEX, () -> CHECKPOI...
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testCleanupOptionalEmptyNestedMap() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'map': {'type': 'MAP','value': {'nested': {'type': 'MAP','value': {}, 'internal_mode': 'OPTIONAL'}}, 'internal_mode': 'OPTIONAL'}}"); Map<Stri...
public V remove(final K key) { V oldValue = cacheMap.remove(key); if (oldValue != null) { LOG.debug("Removed cache entry for '{}'", key); } return oldValue; }
@Test public void testRemove() { LruCache<String, SimpleValue> cache = new LruCache<String, SimpleValue>(1); SimpleValue value = new SimpleValue(true, true); cache.put(DEFAULT_KEY, value); assertEquals(1, cache.size()); assertEquals(value, cache.getCurrentValue(DEFAULT_KEY)); // remove the o...
@Deprecated public static MessageType convert(StructType struct, FieldProjectionFilter filter) { return convert(struct, filter, true, new Configuration()); }
@Test public void testConvertLogicalBinaryType() { LogicalTypeAnnotation jsonLogicalType = LogicalTypeAnnotation.jsonType(); String fieldName = "logicalBinaryType"; Short fieldId = 0; ThriftType.StringType jsonBinaryType = new ThriftType.StringType(); jsonBinaryType.setBinary(true); jsonBinar...
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void retryOnResultFailAfterMaxAttemptsUsingFlowable() throws InterruptedException { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of(...
public EndpointResponse isValidProperty(final String property) { try { final Map<String, Object> properties = new HashMap<>(); properties.put(property, ""); denyListPropertyValidator.validateAll(properties); final KsqlConfigResolver resolver = new KsqlConfigResolver(); final Optional<C...
@Test public void shouldReturnBadRequestWhenIsValidatorIsCalledWithNonQueryLevelProps() { final Map<String, Object> properties = new HashMap<>(); properties.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, ""); givenKsqlConfigWith(ImmutableMap.of( KsqlConfig.KSQL_SHARED_RUNTIME_ENABLED, true )); ...
static void copy(InputStream is, OutputStream os) throws IOException { byte[] buf = new byte[4096]; int b; while ((b = is.read(buf)) != -1) os.write(buf, 0, b); }
@Test public void testCopyError() throws IOException { InputStream mockedIn = mock(InputStream.class); OutputStream out = new ByteArrayOutputStream(); when(mockedIn.read(any(byte[].class))).thenThrow(new IOException()); assertThrows(IOException.class, () -> HttpAccessTokenRetriever.c...
@Override public Comparison compare(final Path.Type type, final PathAttributes local, final PathAttributes remote) { if(Checksum.NONE == remote.getChecksum()) { log.warn(String.format("No remote checksum available for comparison %s", remote)); return Comparison.unknown; } ...
@Test public void testCompare() { ComparisonService s = new ChecksumComparisonService(); assertEquals(Comparison.equal, s.compare(Path.Type.file, new PathAttributes() { @Override public Checksum getChecksum() { return new Checksum(HashA...
public static ColumnDataType convertToColumnDataType(RelDataType relDataType) { SqlTypeName sqlTypeName = relDataType.getSqlTypeName(); if (sqlTypeName == SqlTypeName.NULL) { return ColumnDataType.UNKNOWN; } boolean isArray = (sqlTypeName == SqlTypeName.ARRAY); if (isArray) { assert relD...
@Test public void testBigDecimal() { Assert.assertEquals(RelToPlanNodeConverter.convertToColumnDataType( new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.DECIMAL, 10)), DataSchema.ColumnDataType.INT); Assert.assertEquals(RelToPlanNodeConverter.convertToColumnDataType( ne...
public Optional<Violation> validate(IndexSetConfig newConfig) { // Don't validate prefix conflicts in case of an update if (Strings.isNullOrEmpty(newConfig.id())) { final Violation prefixViolation = validatePrefix(newConfig); if (prefixViolation != null) { return...
@Test public void validateWithInvalidFieldTypeRefreshInterval() { final Duration fieldTypeRefreshInterval = Duration.millis(999); final IndexSetConfig newConfig = mock(IndexSetConfig.class); final IndexSet indexSet = mock(IndexSet.class); when(indexSetRegistry.iterator()).thenReturn...
@Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { ensureWritable(length); setBytes(writerIndex, src, srcIndex, length); writerIndex += length; return this; }
@Test public void testSliceReadGatheringByteChannelMultipleThreads() throws Exception { final byte[] bytes = new byte[8]; random.nextBytes(bytes); final ByteBuf buffer = newBuffer(8); buffer.writeBytes(bytes); try { testReadGatheringByteChannelMultipleThreads(buf...
public static double toFixed(double value, int precision) { return BigDecimal.valueOf(value).setScale(precision, RoundingMode.HALF_UP).doubleValue(); }
@Test public void toFixedFloat() { float actualF = TbUtils.toFixed(floatVal, 3); Assertions.assertEquals(1, Float.compare(floatVal, actualF)); Assertions.assertEquals(0, Float.compare(29.298f, actualF)); }
public static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures) { class Combiner { final Object monitor = new Object(); final CompletableFuture<T> combined = new CompletableFuture<>(); final int futuresCount; Throwable error = null; ...
@Test public void firstof_completes_if_any_futures_completes() { CompletableFuture<String> f1 = new CompletableFuture<>(); CompletableFuture<String> f2 = new CompletableFuture<>(); CompletableFuture<String> f3 = new CompletableFuture<>(); CompletableFuture<String> result = Completabl...
public String toStringNormal() { return String.format("%04d-%02d-%02d", this.year, isLeapMonth() ? this.month - 1 : this.month, this.day); }
@Test public void toStringNormalTest(){ ChineseDate date = new ChineseDate(DateUtil.parseDate("2020-03-1")); assertEquals("2020-02-08", date.toStringNormal()); }
@Override public void stop() throws Exception { factory.close(); dataSource.stop(); }
@Test void stopsTheDataSourceOnStopping() throws Exception { manager.stop(); verify(dataSource).stop(); }
@Override public WebSocketClientExtension handshakeExtension(WebSocketExtensionData extensionData) { if (!PERMESSAGE_DEFLATE_EXTENSION.equals(extensionData.name())) { return null; } boolean succeed = true; int clientWindowSize = MAX_WINDOW_SIZE; int serverWindowS...
@Test public void testDecoderNoClientContext() { PerMessageDeflateClientExtensionHandshaker handshaker = new PerMessageDeflateClientExtensionHandshaker(6, true, MAX_WINDOW_SIZE, true, false); byte[] firstPayload = new byte[] { 76, -50, -53, 10, -62, 48, 20, 4, -48, 9...
@Override public void setRootResources(final Map<String, ResourceModel> rootResources) { log.debug("Setting root resources"); _rootResources = rootResources; Collection<Class<?>> allResourceClasses = new HashSet<>(); for (ResourceModel resourceModel : _rootResources.values()) { processCh...
@Test public void testMissingNamedDependency() { Map<String, ResourceModel> pathRootResourceMap = buildResourceModels(SomeResource1.class); BeanProvider ctx = EasyMock.createMock(BeanProvider.class); EasyMock.expect(ctx.getBean(EasyMock.eq("dep1"))).andReturn(null).anyTimes(); EasyMock.expe...
@Override public GetDataStream getDataStream() { return windmillStreamFactory.createGetDataStream( dispatcherClient.getWindmillServiceStub(), throttleTimers.getDataThrottleTimer()); }
@Test @SuppressWarnings("FutureReturnValueIgnored") public void testStreamingGetData() throws Exception { // This server responds to GetDataRequests with responses that mirror the requests. serviceRegistry.addService( new CloudWindmillServiceV1Alpha1ImplBase() { @Override public ...
static String currentTimestamp(Clock clock) { SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"); df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(Instant.now(clock).toEpochMilli()); }
@Test public void currentTimestamp() { // given Clock clock = Clock.fixed(Instant.ofEpochMilli(1585909518929L), ZoneId.systemDefault()); // when String currentTimestamp = AwsRequestUtils.currentTimestamp(clock); // then assertEquals("20200403T102518Z", currentTimest...
public String nextString() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED) { result = nextUnquotedValue(); } else if (p == PEEKED_SINGLE_QUOTED) { result = nextQuotedValue('\''); } else if (p == PEEKED_DO...
@Test public void testNonStrictModeParsesUnescapedControlCharacter() throws IOException { String json = "\"\t\""; JsonReader reader = new JsonReader(reader(json)); assertThat(reader.nextString()).isEqualTo("\t"); }
static String computeDetailsAsString(SearchRequest searchRequest) { StringBuilder message = new StringBuilder(); message.append(String.format("ES search request '%s'", searchRequest)); if (searchRequest.indices().length > 0) { message.append(String.format(ON_INDICES_MESSAGE, Arrays.toString(searchRequ...
@Test public void should_format_PutMappingRequest() { PutMappingRequest request = new PutMappingRequest("index-1"); assertThat(EsRequestDetails.computeDetailsAsString(request)) .isEqualTo("ES put mapping request on indices 'index-1'"); }
@Override public String service() { return DubboParser.service(invoker); }
@Test void service() { when(invocation.getInvoker()).thenReturn(invoker); when(invoker.getUrl()).thenReturn(url); assertThat(request.service()) .isEqualTo("brave.dubbo.GreeterService"); }
public final Operation setReplicaIndex(int replicaIndex) { if (replicaIndex < 0 || replicaIndex >= InternalPartition.MAX_REPLICA_COUNT) { throw new IllegalArgumentException("Replica index is out of range [0-" + (InternalPartition.MAX_REPLICA_COUNT - 1) + "]: " + replicaIndex); ...
@Test(expected = IllegalArgumentException.class) public void shouldThrowException_whenReplicaIndexInvalid() { Operation op = new DummyOperation(); op.setReplicaIndex(-1); }
public CompiledPipeline.CompiledExecution buildExecution() { return buildExecution(false); }
@Test @SuppressWarnings({"unchecked"}) public void testCacheCompiledClassesWithDifferentId() throws IOException, InvalidIRException { final FixedPluginFactory pluginFactory = new FixedPluginFactory( () -> null, () -> IDENTITY_FILTER, mockOutputSupplier() ...
public void run(String[] args) { if (!parseArguments(args)) { showOptions(); return; } if (command == null) { System.out.println("Error: Command is empty"); System.out.println(); showOptions(); return; } if ...
@Test public void testMainDecrypt() { Main main = new Main(); assertDoesNotThrow(() -> main.run("-c decrypt -p secret -i bsW9uV37gQ0QHFu7KO03Ww==".split(" "))); }
@Override public void click() { isSuspended = !isSuspended; if (isSuspended) { twin.suspendMe(); } else { twin.resumeMe(); } }
@Test void testClick() { final var ballThread = mock(BallThread.class); final var ballItem = new BallItem(); ballItem.setTwin(ballThread); final var inOrder = inOrder(ballThread); IntStream.range(0, 10).forEach(i -> { ballItem.click(); inOrder.verify(ballThread).suspendMe(); ba...
public static Read readResources() { return new Read(); }
@Test public void test_FhirIO_failedReads() { List<String> badMessageIDs = Arrays.asList("foo", "bar"); FhirIO.Read.Result readResult = pipeline.apply(Create.of(badMessageIDs)).apply(FhirIO.readResources()); PCollection<HealthcareIOError<String>> failed = readResult.getFailedReads(); PCollec...
@Override public Integer doCall() throws Exception { CommandLineHelper.createPropertyFile(); if (configuration.split("=").length == 1) { printer().println("Configuration parameter not in key=value format"); return 1; } CommandLineHelper.loadProperties(proper...
@Test public void shouldSetConfig() throws Exception { UserConfigHelper.createUserConfig(""); ConfigSet command = new ConfigSet(new CamelJBangMain().withPrinter(printer)); command.configuration = "foo=bar"; command.doCall(); Assertions.assertEquals("", printer.getOutput());...
public DownlinkMsg convertTelemetryEventToDownlink(Edge edge, EdgeEvent edgeEvent) { if (edgeEvent.getBody() != null) { String bodyStr = edgeEvent.getBody().toString(); if (maxTelemetryMessageSize > 0 && bodyStr.length() > maxTelemetryMessageSize) { String error = "Conver...
@Test public void testConvert_maxSizeLimit() { Edge edge = new Edge(); EdgeEvent edgeEvent = new EdgeEvent(); ObjectNode body = JacksonUtil.newObjectNode(); body.put("value", StringUtils.randomAlphanumeric(1000)); edgeEvent.setBody(body); DownlinkMsg downlinkMsg = te...
public void isEqualTo(@Nullable Object expected) { standardIsEqualTo(expected); }
@Test public void isEqualToWithNulls() { Object o = null; assertThat(o).isEqualTo(null); }
public synchronized OutputStream open() { try { close(); fileOutputStream = new FileOutputStream(file, true); } catch (FileNotFoundException e) { throw new RuntimeException("Unable to open output stream", e); } return fileOutputStream; }
@Test(expected = RuntimeException.class) public void requireThatExceptionIsThrowIfFileNotFound() throws IOException { File file = new File("mydir1"); file.delete(); assertTrue(file.mkdir()); new FileLogTarget(file).open(); }
public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException { if ((defaultManagedBean == null && customManagedBean == null) || objectName == null) return null; // skip proxy classes if (defaultManagedBean != null && P...
@Test(expected = IllegalArgumentException.class) public void testAttributeSetterHavingResult() throws JMException { mbeanInfoAssembler.getMBeanInfo(new BadAttributeSetterHavinReturn(), null, "someName"); }
@Override public boolean isValid(ParameterValue value) { return choices.contains(((StringParameterValue) value).getValue()); }
@Test @Issue("JENKINS-62889") public void checkValue_WrongValueType() { String stringValue = "single"; String[] choices = new String[]{stringValue}; ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition("name", choices, "description"); BooleanParameterValu...
@Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); }
@Test void testGetReader() throws IOException { BufferedReader reader = reuseHttpServletRequest.getReader(); assertNotNull(reader); }
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testSimpleAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList(ResourceRequest.newInstance(PRIORITY_NORMAL, "*", ...
public static BrokerRequest compileToBrokerRequest(String query) { return convertToBrokerRequest(CalciteSqlParser.compileToPinotQuery(query)); }
@Test public void testSqlNumericalLiteralIntegerNPE() { CalciteSqlCompiler.compileToBrokerRequest("SELECT * FROM testTable WHERE floatColumn > " + Double.MAX_VALUE); }
@SuppressWarnings("unchecked") public static void processPartitionKey(byte[] partitionKey, byte[] offsetValue, Converter keyConverter, Map<String, Set<Map<String, Object>>> connectorPartitions) { // The key is expected to always be of the form [connectorName, part...
@Test public void testProcessPartitionKeyNullPartition() { try (LogCaptureAppender logCaptureAppender = LogCaptureAppender.createAndRegister(OffsetUtils.class)) { Map<String, Set<Map<String, Object>>> connectorPartitions = new HashMap<>(); OffsetUtils.processPartitionKey(serializePar...
@Override public MutablePathKeys getPathKeys() { return _pathKeys; }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testUnmodifiablePathKeysMap() throws RestLiSyntaxException { final ResourceContextImpl context = new ResourceContextImpl(); context.getPathKeys().getKeyMap().put("should", "puke"); }
@Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { super.pre(span, exchange, endpoint); span.setTag(TagConstants.MESSAGE_BUS_DESTINATION, getDestination(exchange, endpoint)); String messageId = getMessageId(exchange); if (messageId != null) { ...
@Test public void testPreMessageId() { String messageId = "abcd"; Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("test"); SpanDecorator decorator = new AbstractMessagingS...
public static String[] getSignalKillCommand(int code, String pid) { // Code == 0 means check alive if (Shell.WINDOWS) { if (0 == code) { return new String[] {Shell.getWinUtilsPath(), "task", "isAlive", pid }; } else { return new String[] {Shell.getWinUtilsPath(), "task", "kill", pid ...
@Test public void testGetSignalKillCommand() throws Exception { String anyPid = "9999"; int anySignal = 9; String[] checkProcessAliveCommand = getSignalKillCommand(anySignal, anyPid); String[] expectedCommand; if (Shell.WINDOWS) { expectedCommand = new String[]{getWinUtil...
public static DataflowRunner fromOptions(PipelineOptions options) { DataflowPipelineOptions dataflowOptions = PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options); ArrayList<String> missing = new ArrayList<>(); if (dataflowOptions.getAppName() == null) { missing.add("appN...
@Test public void testProjectPrefix() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setProject("google.com:some-project-12345"); DataflowRunner.fromOptions(options); }
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null)...
@Test public void testAlterOffsetsIncorrectOffsetKey() { MirrorSourceConnector connector = new MirrorSourceConnector(); Map<Map<String, ?>, Map<String, ?>> offsets = Collections.singletonMap( sourcePartition("t1", 2, "backup"), Collections.singletonMap("unused_offset...
@Override public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionOffset, final int connectionSize, final ConnectionMode connectionMode) throws SQLException { return getConnections0(databaseName, dataSource...
@Test void assertGetConnectionWithConnectionOffset() throws SQLException { assertThat(databaseConnectionManager.getConnections(DefaultDatabase.LOGIC_NAME, "ds", 0, 1, ConnectionMode.MEMORY_STRICTLY), is(databaseConnectionManager.getConnections(DefaultDatabase.LOGIC_NAME, "ds", 0, 1, Connecti...
public abstract List<Consumer<T>> getInputConsumers();
@Test public void testDanglingSubscriptions() throws Exception { MultiConsumerPulsarSourceConfig pulsarConfig = getMultiConsumerPulsarConfigs(true); MultiConsumerPulsarSource<?> pulsarSource = new MultiConsumerPulsarSource<>(getPulsarClient(), pulsarConfig, new HashMap<>(), ...
public void setNodes(String clusterName, String group, List<Node> nodes) { this.clusterNodes.computeIfAbsent(clusterName, k -> new ConcurrentHashMap<>()).put(group, nodes); }
@Test public void testSetNodes() { Assertions.assertDoesNotThrow(() -> metadata.setNodes("cluster", "group", new ArrayList<>())); }
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 shouldMaskIfNotExistSourceConnector() { // Given: final String query = "CREATE SOURCE CONNECTOR IF NOT EXISTS testconnector WITH (" + " \"connector.class\" = 'PostgresSource', \n" + " 'connection.url' = 'jdbc:postgresql://localhost:5432/my.db',\n" + " `mode`=...
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldLoadConfigWithConfigRepoAndConfiguration() throws Exception { CruiseConfig cruiseConfig = xmlLoader.loadConfigHolder(configWithConfigRepos( """ <config-repos> <config-repo id="id1" pluginId="gocd-xml"> ...
public static String executeDockerCommand(DockerCommand dockerCommand, String containerId, Map<String, String> env, PrivilegedOperationExecutor privilegedOperationExecutor, boolean disableFailureLogging, Context nmContext) throws ContainerExecutionException { PrivilegedOperation dockerOp = d...
@Test public void testExecuteDockerKillSIGKILL() throws Exception { DockerKillCommand dockerKillCommand = new DockerKillCommand(MOCK_CONTAINER_ID) .setSignal(ContainerExecutor.Signal.KILL.name()); DockerCommandExecutor.executeDockerCommand(dockerKillCommand, MOCK_CONTAINER_ID, env,...
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) { final CookieOrigin cookieOrigin = cookieOriginFromUri(requestSpec.getURI()); for (Cookie cookie : cookieStore.getCookies()) { if (cookieSpec.match(cookie, co...
@Test public void addDuplicateNameCookiesLikeInBrowser() { FilterableRequestSpecification reqOriginDomainDuplicate = (FilterableRequestSpecification) given().with().baseUri("https://foo.com/bar"); DuplicateTestFilterContext duplicateTestFilterContext = new DuplicateTestFilterContext(...
@Override public void killProcess(final String processId) { Collection<String> triggerPaths = getKillProcessTriggerPaths(processId); boolean isCompleted = false; try { triggerPaths.forEach(each -> repository.persist(each, "")); isCompleted = ProcessOperationLockRegist...
@Test void assertKillProcess() { when(repository.getChildrenKeys(ComputeNode.getOnlineNodePath(InstanceType.JDBC))).thenReturn(Collections.emptyList()); when(repository.getChildrenKeys(ComputeNode.getOnlineNodePath(InstanceType.PROXY))).thenReturn(Collections.singletonList("abc")); processPe...
public void run() throws Exception { final Terminal terminal = TerminalBuilder.builder() .nativeSignals(true) .signalHandler(signal -> { if (signal == Terminal.Signal.INT || signal == Terminal.Signal.QUIT) { if (execState == ExecState.R...
@Test public void testFileModeExitOnError() throws Exception { Terminal terminal = TerminalBuilder.builder().build(); final MockLineReader linereader = new MockLineReader(terminal); final Properties props = new Properties(); props.setProperty("webServiceUrl", "http://localhost:8080")...
public static FileSystem write(final FileSystem fs, final Path path, final byte[] bytes) throws IOException { Objects.requireNonNull(path); Objects.requireNonNull(bytes); try (FSDataOutputStream out = fs.createFile(path).overwrite(true).build()) { out.write(bytes); } return fs; }
@Test public void testWriteStringsFileContext() throws IOException { URI uri = tmp.toURI(); Configuration conf = new Configuration(); FileContext fc = FileContext.getFileContext(uri, conf); Path testPath = new Path(new Path(uri), "writestrings.out"); Collection<String> write = Arrays.asList("over...
@Override public QueryHeader build(final QueryResultMetaData queryResultMetaData, final ShardingSphereDatabase database, final String columnName, final String columnLabel, final int columnIndex) throws SQLException { String schemaName = null == database ? "" : database.getName()...
@Test void assertBuildWithNullSchema() throws SQLException { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getSchemas()).thenReturn(Collections.emptyMap()); DataNodeRuleAttribute ruleAttribute = mock(DataNodeRuleAttribute.class); ...
@Override public Application install(InputStream appDescStream) { checkNotNull(appDescStream, "Application archive stream cannot be null"); Application app = store.create(appDescStream); SecurityUtil.register(app.id()); return app; }
@Test public void install() { InputStream stream = ApplicationArchive.class.getResourceAsStream("app.zip"); Application app = mgr.install(stream); validate(app); assertEquals("incorrect features URI used", app.featuresRepo().get(), ((TestFeaturesService) mgr.feat...
@Override public void to(final String topic) { to(topic, Produced.with(keySerde, valueSerde, null)); }
@Test public void shouldNotAllowNullTopicChooserOnToWithProduced() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.to((TopicNameExtractor<String, String>) null, Produced.as("to"))); assertThat(exception.getMessage(), equalTo...
public static void insert( final UnsafeBuffer termBuffer, final int termOffset, final UnsafeBuffer packet, final int length) { if (0 == termBuffer.getInt(termOffset)) { termBuffer.putBytes(termOffset + HEADER_LENGTH, packet, HEADER_LENGTH, length - HEADER_LENGTH); te...
@Test void shouldFillAfterAGap() { final int frameLength = 50; final int alignedFrameLength = BitUtil.align(frameLength, FRAME_ALIGNMENT); final int srcOffset = 0; final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocate(alignedFrameLength)); final int termOffset ...
@Override public void clearChanged() { changedEntries = false; changedHops = false; for ( int i = 0; i < nrJobEntries(); i++ ) { JobEntryCopy entry = getJobEntry( i ); entry.setChanged( false ); } for ( JobHopMeta hi : jobhops ) { // Look at all the hops hi.setChanged( fal...
@Test public void testContentChangeListener() throws Exception { jobMeta.setChanged(); jobMeta.setChanged( true ); verify( listener, times( 2 ) ).contentChanged( same( jobMeta ) ); jobMeta.clearChanged(); jobMeta.setChanged( false ); verify( listener, times( 2 ) ).contentSafe( same( jobMeta...
@Override public void start() { // we request a split only if we did not get splits during the checkpoint restore if (getNumberOfCurrentlyAssignedSplits() == 0) { context.sendSplitRequest(); } }
@Test void testNoSplitRequestWhenSplitRestored() throws Exception { final TestingReaderContext context = new TestingReaderContext(); final FileSourceReader<String, FileSourceSplit> reader = createReader(context); reader.addSplits(Collections.singletonList(createTestFileSplit())); re...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertInt() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.INT_TYPE).build(); BasicTypeDefine typeDefine = XuguTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.a...
public boolean isNewerThan(JavaSpecVersion otherVersion) { return this.compareTo(otherVersion) > 0; }
@Test public void test8notNewerThan11() throws Exception { // Setup fixture. final JavaSpecVersion eight = new JavaSpecVersion( "1.8" ); final JavaSpecVersion eleven = new JavaSpecVersion( "11" ); // Execute system under test. final boolean result = eight.isNewerThan( el...
@Udf(description = "Returns a masked version of the input string. The last n characters" + " will be replaced according to the default masking rules.") @SuppressWarnings("MethodMayBeStatic") // Invoked via reflection public String mask( @UdfParameter("input STRING to be masked") final String input, ...
@Test public void shouldMaskAllCharsIfLengthTooLong() { final String result = udf.mask("AbCd#$123xy Z", 999); assertThat(result, is("XxXx--nnnxx-X")); }
@Override public Consumer createConsumer(Processor processor) throws Exception { // we need to have database and container set to consume events if (ObjectHelper.isEmpty(configuration.getDatabaseName()) || ObjectHelper.isEmpty(configuration.getContainerName())) { throw new IllegalArgumen...
@Test void testCreateConsumerWithInvalidConfig() throws Exception { final String uri = "azure-cosmosdb://mydb/myContainer"; String remaining = "mydb"; final Map<String, Object> params = new HashMap<>(); params.put("databaseEndpoint", "https://test.com:443"); params.put("creat...
public String getValue(String key) { String currentValue = configOverrides.getProperty(key); return StringUtils.isEmpty(currentValue) ? getInitialValue(key) : currentValue; }
@Test void testLoadPropertiesFromInitFile() throws IOException { String propBackUp = System.getProperty("spark.kubernetes.operator.basePropertyFileName"); try { String propsFilePath = SparkOperatorConfManagerTest.class .getClassLoader() .getResource("spark-operator....
@GetMapping(params = "search=blur") @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.READ) public Page<User> fuzzySearchUser(@RequestParam int pageNo, @RequestParam int pageSize, @RequestParam(name = "username", required = false, defaultValue = "") Strin...
@Test void testFuzzySearchUser() { Page<User> userPage = new Page<>(); when(userDetailsService.findUsersLike4Page(anyString(), anyInt(), anyInt())).thenReturn(userPage); Page<User> nacos = userController.fuzzySearchUser(1, 10, "nacos"); assertEquals(userPage, nacos)...
public static boolean acceptEndpoint(String endpointUrl) { return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING); }
@Test public void testAcceptEndpointFailures() { AsyncTestSpecification specification = new AsyncTestSpecification(); NATSMessageConsumptionTask task = new NATSMessageConsumptionTask(specification); assertFalse(NATSMessageConsumptionTask.acceptEndpoint("ssl://localhost:1883/testTopic")); as...
static boolean isNewDatabase(String uppercaseProductName) { if (SUPPORTED_DATABASE_NAMES.contains(uppercaseProductName)) { return false; } return DETECTED_DATABASE_NAMES.add(uppercaseProductName); }
@Test public void testMySQL() { String dbName = "MYSQL"; boolean newDB1 = SupportedDatabases.isNewDatabase(dbName); assertThat(newDB1).isFalse(); }
public static List<String> splitPlainTextParagraphs( List<String> lines, int maxTokensPerParagraph) { return internalSplitTextParagraphs( lines, maxTokensPerParagraph, (text) -> internalSplitLines( text, maxTokensPerParagraph, false, s_plaintextSplitOp...
@Test public void canSplitTextParagraphsOnNewlines() { List<String> input = Arrays.asList( "This is a test of the emergency broadcast system\r\nThis is only a test", "We repeat this is only a test\nA unit test", "A small note\n" + "And another\r\n" ...
@Override public Long createRewardActivity(RewardActivityCreateReqVO createReqVO) { // 校验商品是否冲突 validateRewardActivitySpuConflicts(null, createReqVO.getProductSpuIds()); // 插入 RewardActivityDO rewardActivity = RewardActivityConvert.INSTANCE.convert(createReqVO) .setS...
@Test public void testCreateRewardActivity_success() { // 准备参数 RewardActivityCreateReqVO reqVO = randomPojo(RewardActivityCreateReqVO.class, o -> { o.setConditionType(randomEle(PromotionConditionTypeEnum.values()).getType()); o.setProductScope(randomEle(PromotionProductScopeE...
int getMinLatForTile(double lat) { return (int) (Math.floor((90 + lat) / LAT_DEGREE) * LAT_DEGREE) - 90; }
@Test public void testMinLat() { assertEquals(50, instance.getMinLatForTile(52.5)); assertEquals(10, instance.getMinLatForTile(29.9)); assertEquals(-70, instance.getMinLatForTile(-59.9)); }
public Integer value() { return value; }
@Test void testSetValue() { IntegerNode n = new IntegerNode(); assertFalse(n.setValue("invalid")); assertTrue(n.setValue("10")); assertEquals(10, n.value().intValue()); }
void error() { if (state <= k * (n - 1)) { state += k; } else { state = k * n; } }
@Test public void lotsOfErrors() { assertOutput(500); degrader.error(); assertOutput(400); degrader.error(); assertOutput(300); degrader.error(); assertOutput(200); for (int i = 0; i < OUTPUTS.length; i++) { degrader.error(); ...
@SuppressWarnings("ParameterNumber") PersistentQueryMetadata buildPersistentQueryInDedicatedRuntime( final KsqlConfig ksqlConfig, final KsqlConstants.PersistentQueryType persistentQueryType, final String statementText, final QueryId queryId, final Optional<DataSource> sinkDataSource, ...
@Test public void shouldBuildDedicatedCreateAsPersistentQueryWithSharedRuntimeCorrectly() { // Given: when(ksqlConfig.getBoolean(KsqlConfig.KSQL_SHARED_RUNTIME_ENABLED)).thenReturn(true); final ProcessingLogger uncaughtProcessingLogger = mock(ProcessingLogger.class); when(processingLoggerFactory.getLo...
public Optional<PluginMatchingResult<ServiceFingerprinter>> getServiceFingerprinter( NetworkService networkService) { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.SERVICE_FINGERPRINT)) .filter(entry -> hasMatchingServiceName(networkService,...
@Test public void getServiceFingerprinter_whenForWebServiceAnnotationAndNonWebService_returnsEmpty() { NetworkService sshService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtocol.TCP) ...
public static int compareLong(long o1, long o2) { return Long.compare(o1, o2); }
@Test public void testCompareLong() { Assert.assertEquals(0, NumberUtils.compareLong(0L, 0L)); Assert.assertEquals(1, NumberUtils.compareLong(9L, 0L)); Assert.assertEquals(-1, NumberUtils.compareLong(0L, 9L)); Assert.assertEquals(-1, NumberUtils.compareLong(-9L, 0L)); Assert.assertEquals(1, NumberUtils.compa...
@SuppressWarnings("checkstyle:NestedIfDepth") @Nullable public PartitioningStrategy getPartitioningStrategy( String mapName, PartitioningStrategyConfig config, final List<PartitioningAttributeConfig> attributeConfigs ) { if (attributeConfigs != null && !attributeC...
@Test public void whenConfigNull_getPartitioningStrategy_returnsNull() { PartitioningStrategy partitioningStrategy = partitioningStrategyFactory.getPartitioningStrategy(mapName, null, null); assertNull(partitioningStrategy); }
public static boolean isIPInRange(String ip, String cidr) { try { String[] parts = cidr.split(SLASH); if (parts.length == 1) { return StringUtils.equals(ip, cidr); } if (parts.length != 2) { return false; } I...
@Test public void isIPInRange() { // IPv4 test String ipv4Address = "192.168.1.10"; String ipv4Cidr = "192.168.1.0/24"; assert IPAddressUtils.isIPInRange(ipv4Address, ipv4Cidr); ipv4Address = "192.168.2.10"; assert !IPAddressUtils.isIPInRange(ipv4Address, ipv4Cidr);...
@Override protected int rsv(WebSocketFrame msg) { return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame? msg.rsv() | WebSocketExtension.RSV1 : msg.rsv(); }
@Test public void testAlreadyCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false)); // initialize byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(...
public void refreshStarted(long currentVersion, long requestedVersion) { updatePlanDetails = new ConsumerRefreshMetrics.UpdatePlanDetails(); refreshStartTimeNano = System.nanoTime(); refreshMetricsBuilder = new ConsumerRefreshMetrics.Builder(); refreshMetricsBuilder.setIsInitialLoad(curr...
@Test public void testRefreshStartedWithInitialLoad() { concreteRefreshMetricsListener.refreshStarted(VERSION_NONE, TEST_VERSION_HIGH); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); assertEquals(true, refreshMetrics.getIsInitialLoad());...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path f : files.keySet()) { if(f.isPlaceholder()) { log.warn(String.format("Ignore placeholder %s", f)); con...
@Test(expected = NotfoundException.class) public void testDeleteNotFound() throws Exception { final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new DriveTrashFeature(session, new DriveFileIdProvider(session)).delete(Collectio...
public List<Flow> convertFlows(String componentName, @Nullable DbIssues.Locations issueLocations) { if (issueLocations == null) { return Collections.emptyList(); } return issueLocations.getFlowList().stream() .map(sourceFlow -> toFlow(componentName, sourceFlow)) .collect(Collectors.toColle...
@Test public void convertFlows_with2DbLocations_returns() { DbIssues.Location location1 = createDbLocation("comp_id_1"); DbIssues.Location location2 = createDbLocation("comp_id_2"); DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder() .addFlow(createFlow(location1, location2)) ....
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset( RequestContext context, OffsetCommitRequestData request ) throws ApiException { Group group = validateOffsetCommit(context, request); // In the old consumer group protocol, the offset commits maintai...
@Test public void testGenericGroupOffsetCommitWhileInCompletingRebalanceState() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); // Create an empty group. ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup( ...
@Operation(summary = "prepare PCA for nik") @PostMapping(value = Constants.URL_NIK_PREPARE_PCA, consumes = "application/json", produces = "application/json") public PreparePcaResponse preparePcaRequestRestService(@Valid @RequestBody NikApduResponsesRequest request) { return nikService.preparePcaRequestR...
@Test public void preparePcaRequestRestServiceTest() { PreparePcaResponse expectedResponse = new PreparePcaResponse(); when(nikServiceMock.preparePcaRequestRestService(any(NikApduResponsesRequest.class))).thenReturn(expectedResponse); PreparePcaResponse actualResponse = nikController.prepar...
@Deprecated public static <T extends Collection<String>> T readLines(InputStream in, String charsetName, T collection) throws IORuntimeException { return readLines(in, CharsetUtil.charset(charsetName), collection); }
@Test public void readLinesTest() { try (BufferedReader reader = ResourceUtil.getUtf8Reader("test_lines.csv");) { IoUtil.readLines(reader, (LineHandler) Assertions::assertNotNull); } catch (IOException e) { throw new IORuntimeException(e); } }
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void returnOnErrorUsingObservable() throws InterruptedException { RetryConfig config = retryConfig(); Retry retry = Retry.of("testName", config); RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry); given(helloWorldService.returnHelloWorld()) ...