focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public AccessResource parse(RemotingCommand request, String remoteAddr) {
return PlainAccessResource.parse(request, remoteAddr);
} | @Test
public void validateForAdminCommandWithOutAclRPCHook() {
RemotingCommand consumerOffsetAdminRequest = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_CONSUMER_OFFSET, null);
plainAccessValidator.parse(consumerOffsetAdminRequest, "192.168.0.1:9876");
RemotingCommand subscripti... |
@Bean
public ShenyuContextDecorator motanShenyuContextDecorator() {
return new MotanShenyuContextDecorator();
} | @Test
public void testMotanShenyuContextDecorator() {
applicationContextRunner.run(context -> {
ShenyuContextDecorator subscriber = context.getBean("motanShenyuContextDecorator", ShenyuContextDecorator.class);
assertNotNull(subscriber);
}
);
} |
@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
String accessToken = (String) request.get("accessToken");
if(accessToken == null){
throw new ServiceException.BadRequestException("accessToken is required");
}
accessToken = accessToken.trim(... | @Test
public void validateAndCreatePaddedToken() throws Exception {
validateAndCreate(" 12345 ");
} |
public int computeThreshold(StreamConfig streamConfig, CommittingSegmentDescriptor committingSegmentDescriptor,
@Nullable SegmentZKMetadata committingSegmentZKMetadata, String newSegmentName) {
long desiredSegmentSizeBytes = streamConfig.getFlushThresholdSegmentSizeBytes();
if (desiredSegmentSizeBytes <= ... | @Test
public void testUseLastSegmentSizeTimesRatioIfFirstSegmentInPartitionAndNewPartitionGroupMinimumSize10000Rows() {
double segmentRowsToSizeRatio = 1.5;
long segmentSizeBytes = 2000L;
SegmentFlushThresholdComputer computer =
new SegmentFlushThresholdComputer(Clock.systemUTC(), segmentRowsToSiz... |
@Override
public Optional<P> authenticate(C credentials) throws AuthenticationException {
try (Timer.Context context = gets.time()) {
return cache.get(credentials);
} catch (CompletionException e) {
final Throwable cause = e.getCause();
if (cause instanceof Invali... | @Test
void cachesTheFirstReturnedPrincipal() throws Exception {
assertThat(cached.authenticate("credentials")).isEqualTo(Optional.<Principal>of(new PrincipalImpl("principal")));
assertThat(cached.authenticate("credentials")).isEqualTo(Optional.<Principal>of(new PrincipalImpl("principal")));
... |
public FluentBackoff withMaxBackoff(Duration maxBackoff) {
checkArgument(
maxBackoff.getMillis() > 0, "maxBackoff %s must be at least 1 millisecond", maxBackoff);
return new FluentBackoff(
exponent,
initialBackoff,
maxBackoff,
maxCumulativeBackoff,
maxRetries,
... | @Test
public void testInvalidMaxBackoff() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("maxBackoff PT0S must be at least 1 millisecond");
defaultBackoff.withMaxBackoff(Duration.ZERO);
} |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateFieldWithInvalidValueMismatchTimestamp() {
long longValue = 1000L;
String fieldName = "field";
ConnectSchema.validateValue(fieldName, Schema.INT64_SCHEMA, longValue);
assertInvalidValueForSchema(fieldName, Timestamp.SCHEMA, longValue,
"... |
@Override
public void beginShutdown(String source) {
lock.lock();
try {
if (shuttingDown) {
log.debug("{}: Event queue is already shutting down.", source);
return;
}
log.info("{}: shutting down event queue.", source);
sh... | @Test
public void testShutdownBeforeDeferred() throws Exception {
try (KafkaEventQueue queue = new KafkaEventQueue(Time.SYSTEM, logContext, "testShutdownBeforeDeferred")) {
final AtomicInteger count = new AtomicInteger(0);
CompletableFuture<Integer> future = new CompletableFuture<>()... |
@Transactional
public void deleteUsedMemberCoupons(final Long buyerId, final List<Long> usedCoupons) {
memberCouponRepository.deleteByMemberIdAndCouponIdIn(buyerId, usedCoupons);
} | @Test
void 멤버가_사용한_쿠폰을_모두_제거한다() {
// given
Coupon coupon = couponRepository.save(쿠픈_생성_독자_사용_할인율_10_퍼센트());
MemberCoupon memberCoupon = memberCouponRepository.save(멤버_쿠폰_생성());
// when
couponService.deleteUsedMemberCoupons(memberCoupon.getMemberId(), List.of(coupon.getId())... |
public int getHeaderLen() {
return header_len;
} | @Test
public void getHeaderLen() {
assertEquals(TestParameters.VP_ITSF_HEADER_LENGTH, chmItsfHeader.getHeaderLen());
} |
@Deprecated
public static DockerCmdExecFactory getDefaultDockerCmdExecFactory() {
return new JerseyDockerCmdExecFactory();
} | @Test
public void testConcurrentClientBuilding() throws Exception {
// we use it to check instance uniqueness
final Set<DockerCmdExecFactory> instances = Collections.synchronizedSet(new HashSet<>());
Runnable runnable = () -> {
DockerCmdExecFactory factory = DockerClientBuilder.... |
@Override
public void write(final MySQLPacketPayload payload, final Object value) {
payload.getByteBuf().writeFloatLE(Float.parseFloat(value.toString()));
} | @Test
void assertWrite() {
new MySQLFloatBinaryProtocolValue().write(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8), 1.0F);
verify(byteBuf).writeFloatLE(1.0F);
} |
@Override
public DataSink createDataSink(Context context) {
FactoryHelper.createFactoryHelper(this, context)
.validateExcept(PREFIX_TABLE_PROPERTIES, PREFIX_CATALOG_PROPERTIES);
Map<String, String> allOptions = context.getFactoryConfiguration().toMap();
Map<String, String> c... | @Test
void testCreateDataSink() {
DataSinkFactory sinkFactory =
FactoryDiscoveryUtils.getFactoryByIdentifier("paimon", DataSinkFactory.class);
Assertions.assertThat(sinkFactory).isInstanceOf(PaimonDataSinkFactory.class);
Configuration conf =
Configuration.fro... |
public CatCommand(Logger console, long defaultNumRecords) {
super(console);
this.numRecords = defaultNumRecords;
} | @Test
public void testCatCommand() throws IOException {
File file = parquetFile();
CatCommand command = new CatCommand(createLogger(), 0);
command.sourceFiles = Arrays.asList(file.getAbsolutePath());
command.setConf(new Configuration());
Assert.assertEquals(0, command.run());
} |
public synchronized Collection<StreamsMetadata> getAllMetadataForStore(final String storeName) {
Objects.requireNonNull(storeName, "storeName cannot be null");
if (topologyMetadata.hasNamedTopologies()) {
throw new IllegalArgumentException("Cannot invoke the getAllMetadataForStore(storeName)... | @Test
public void shouldThrowIfStoreNameIsNullOnGetAllInstancesWithStore() {
assertThrows(NullPointerException.class, () -> metadataState.getAllMetadataForStore(null));
} |
public static String getRuleName(final String ruleRow) {
String testVal = ruleRow.toLowerCase();
final int left = testVal.indexOf( DefaultRuleSheetListener.RULE_TABLE_TAG );
return ruleRow.substring( left + DefaultRuleSheetListener.RULE_TABLE_TAG.length() ).trim();
} | @Ignore
@Test
public void testInvalidRuleName() {
final String row = "RuleTable This is my rule name (type class)";
assertThatIllegalArgumentException().isThrownBy(() -> getRuleName(row));
} |
public static String toStr(Object value, String defaultValue) {
return convertQuietly(String.class, value, defaultValue);
} | @Test
public void toStrTest() {
final int a = 1;
final long[] b = {1, 2, 3, 4, 5};
assertEquals("[1, 2, 3, 4, 5]", Convert.convert(String.class, b));
final String aStr = Convert.toStr(a);
assertEquals("1", aStr);
final String bStr = Convert.toStr(b);
assertEquals("[1, 2, 3, 4, 5]", Convert.toStr(bStr))... |
@Override
public boolean isWrapperFor(final Class<?> iface) {
return false;
} | @Test
void assertIsWrapperFor() {
assertFalse(metaData.isWrapperFor(null));
} |
public void processScheduledTask(String name) throws SharedServiceClientException {
if(RE_CHECK_DOCUMENTS.equals(name)) {
var daysAgo = sharedServiceClient.getSSConfigInt("interval_lost_stolen_check");
for (IdCheckDocument document : idCheckDocumentRepository.findAllWithCreationDateTimeB... | @Test
void processesScheduledTaskStolenDocument() throws SharedServiceClientException {
when(dwsClient.checkBvBsn("document_type", "document_number")).thenReturn(Map.of("status", "NOK"));
when(sharedServiceClient.getSSConfigInt("interval_lost_stolen_check")).thenReturn(7);
service.processSc... |
public static void e(String tag, String message, Object... args) {
sLogger.e(tag, message, args);
} | @Test
public void error() {
String tag = "TestTag";
String message = "Test message";
LogManager.e(tag, message);
verify(logger).e(tag, message);
} |
@Udf(description = "Converts a TIMESTAMP value into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'"
+ " The system default time zone is used when no time zone is explicitly ... | @Test
public void testPSTTimeZone() {
// When:
final String result = udf.formatTimestamp(new Timestamp(1534353043000L),
"yyyy-MM-dd HH:mm:ss", "America/Los_Angeles");
// Then:
assertThat(result, is("2018-08-15 10:10:43"));
} |
public BigDecimal getAmount() {
return BigDecimal.valueOf(cent, currency.getDefaultFractionDigits());
} | @Test
public void centToYuanTest() {
final Money money = new Money(1234, 56);
assertEquals(1234.56D, money.getAmount().doubleValue(), 0);
assertEquals(1234.56D, MathUtil.centToYuan(123456), 0);
} |
RequestQueue<ReadRequest> getReadRequestQueue(FileIOChannel.ID channelID) {
return this.readers[channelID.getThreadNum()].requestQueue;
} | @Test
void testExceptionInCallbackRead() throws Exception {
final AtomicBoolean handlerCalled = new AtomicBoolean();
ReadRequest regularRequest =
new ReadRequest() {
@Override
public void requestDone(IOException ioex) {
... |
@Override
public void createApiAccessLog(ApiAccessLogCreateReqDTO createDTO) {
ApiAccessLogDO apiAccessLog = BeanUtils.toBean(createDTO, ApiAccessLogDO.class);
apiAccessLog.setRequestParams(StrUtil.maxLength(apiAccessLog.getRequestParams(), REQUEST_PARAMS_MAX_LENGTH));
apiAccessLog.setResult... | @Test
public void testCreateApiAccessLog() {
// 准备参数
ApiAccessLogCreateReqDTO createDTO = randomPojo(ApiAccessLogCreateReqDTO.class);
// 调用
apiAccessLogService.createApiAccessLog(createDTO);
// 断言
ApiAccessLogDO apiAccessLogDO = apiAccessLogMapper.selectOne(null);
... |
public static String toUnicodeHex(int value) {
final StringBuilder builder = new StringBuilder(6);
builder.append("\\u");
String hex = toHex(value);
int len = hex.length();
if (len < 4) {
builder.append("0000", 0, 4 - len);// 不足4位补0
}
builder.append(hex);
return builder.toString();
} | @Test
public void toUnicodeHexTest() {
String unicodeHex = HexUtil.toUnicodeHex('\u2001');
assertEquals("\\u2001", unicodeHex);
unicodeHex = HexUtil.toUnicodeHex('你');
assertEquals("\\u4f60", unicodeHex);
} |
void startup(@Observes StartupEvent event) {
if (storageProviderMetricsBinderInstance.isResolvable()) {
storageProviderMetricsBinderInstance.get();
LOGGER.debug("JobRunr StorageProvider MicroMeter Metrics enabled");
}
if (backgroundJobServerMetricsBinderInstance.isResolva... | @Test
void metricsStarterStartsBackgroundJobServerMetricsBinderIfAvailable() {
when(backgroundJobServerMetricsBinderInstance.isResolvable()).thenReturn(true);
jobRunrMetricsStarter.startup(new StartupEvent());
verify(backgroundJobServerMetricsBinderInstance).get();
} |
public static long readUint32(ByteBuffer buf) throws BufferUnderflowException {
return Integer.toUnsignedLong(buf.order(ByteOrder.LITTLE_ENDIAN).getInt());
} | @Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32ThrowsException2() {
ByteUtils.readUint32(new byte[]{1, 2, 3, 4, 5}, 2);
} |
public static String normalizeUri(String uri) throws URISyntaxException {
// try to parse using the simpler and faster Camel URI parser
String[] parts = CamelURIParser.fastParseUri(uri);
if (parts != null) {
// we optimized specially if an empty array is returned
if (part... | @Test
public void testNormalizeUriWhereParameterIsFaulty() throws Exception {
String out = URISupport.normalizeUri("stream:uri?file:///d:/temp/data/log/quickfix.log&scanStream=true");
assertNotNull(out);
} |
@Override
@SuppressWarnings("assignment")
public ComputeMessageStatsResponse computeMessageStats(Offset offset) throws ApiException {
try {
return client
.computeMessageStats(topicPath, partition, offset, Offset.of(Long.MAX_VALUE))
.get(1, MINUTES);
} catch (Throwable t) {
th... | @Test
public void computeMessageStats_validResponseCached() {
Timestamp minEventTime = Timestamp.newBuilder().setSeconds(1000).setNanos(10).build();
Timestamp minPublishTime = Timestamp.newBuilder().setSeconds(1001).setNanos(11).build();
ComputeMessageStatsResponse response =
ComputeMessageStatsRe... |
public static <T> Partition<T> of(
int numPartitions,
PartitionWithSideInputsFn<? super T> partitionFn,
Requirements requirements) {
Contextful ctfFn =
Contextful.fn(
(T element, Contextful.Fn.Context c) ->
partitionFn.partitionFor(element, numPartitions, c),
... | @Test
public void testZeroNumPartitions() {
PCollection<Integer> input = pipeline.apply(Create.of(591));
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("numPartitions must be > 0");
input.apply(Partition.of(0, new IdentityFn()));
} |
@Override
public JdbcRecordIterator
getRecordIterator(Configuration conf, String partitionColumn, String lowerBound, String upperBound, int limit, int
offset) throws
HiveJdbcDatabaseAccessException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
tr... | @Test
public void testGetRecordIterator() throws HiveJdbcDatabaseAccessException {
Configuration conf = buildConfiguration();
DatabaseAccessor accessor = DatabaseAccessorFactory.getAccessor(conf);
JdbcRecordIterator iterator = accessor.getRecordIterator(conf, null, null, null,2, 0);
assertThat(iterat... |
public static String toStepName(ExecutableStage executableStage) {
/*
* Look for the first/input ParDo/DoFn in this executable stage by
* matching ParDo/DoFn's input PCollection with executable stage's
* input PCollection
*/
Set<PipelineNode.PTransformNode> inputs =
executableStage.g... | @Test
public void testExecutableStageWithOutput() {
pipeline
.apply("MyCreateOf", Create.of(KV.of(1L, "1")))
.apply("MyFilterBy", Filter.by(Objects::nonNull))
.apply(GroupByKey.create());
assertEquals("[MyCreateOf-MyFilterBy]", DoFnUtils.toStepName(getOnlyExecutableStage(pipeline)));
... |
@Override
public Long stringSize(String path) {
return get(stringSizeAsync(path));
} | @Test
public void testStringSize() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
Long s3 = al.stringSize("name");
assertThat(s3).isNull();
TestType t = new TestType();
t.setName("name1");
NestedType nt = new NestedTy... |
public void setInitialAttributes(File file, FileAttribute<?>... attrs) {
// default values should already be sanitized by their providers
for (int i = 0; i < defaultValues.size(); i++) {
FileAttribute<?> attribute = defaultValues.get(i);
int separatorIndex = attribute.name().indexOf(':');
Str... | @Test
public void testSetInitialAttributes() {
File file = createFile();
service.setInitialAttributes(file);
assertThat(file.getAttributeNames("test")).containsExactly("bar", "baz");
assertThat(file.getAttributeNames("owner")).containsExactly("owner");
assertThat(service.getAttribute(file, "basi... |
public static File unzip(String zipFilePath) throws UtilException {
return unzip(zipFilePath, DEFAULT_CHARSET);
} | @Test
@Disabled
public void unzipTest() {
final File unzip = ZipUtil.unzip("d:/test/hutool.zip", "d:\\test", CharsetUtil.CHARSET_GBK);
Console.log(unzip);
} |
@Override public synchronized <T>
T register(String name, String desc, T source) {
MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source);
final MetricsSource s = sb.build();
MetricsInfo si = sb.info();
String name2 = name == null ? si.name() : name;
final String finalDesc = desc ==... | @Test(expected=MetricsException.class) public void testRegisterDupError() {
MetricsSystem ms = new MetricsSystemImpl("test");
TestSource ts = new TestSource("ts");
ms.register(ts);
ms.register(ts);
} |
@Override
public ConsumerBuilder<T> topic(String... topicNames) {
checkArgument(topicNames != null && topicNames.length > 0,
"Passed in topicNames should not be null or empty.");
return topics(Arrays.stream(topicNames).collect(Collectors.toList()));
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testConsumerBuilderImplWhenTopicNamesVarargsHasNullTopic() {
consumerBuilderImpl.topic("my-topic", null);
} |
public void mergeUpdateCount() {
updateCount = 0L;
for (int each : updateCounts) {
updateCount += each;
}
} | @Test
void assertGetUpdateCountWhenExecuteResultIsNotEmpty() {
UpdateResponseHeader actual = new UpdateResponseHeader(mock(SQLStatement.class), createExecuteUpdateResults());
assertThat(actual.getUpdateCount(), is(0L));
actual.mergeUpdateCount();
assertThat(actual.getUpdateCount(), i... |
@Override
public String toString() {
return toStringHelper(getClass())
.add("securityParamIndex", Integer.toString(securityParamIndex))
.add("sequence", Integer.toString(sequence))
.toString();
} | @Test
public void testToStringESP() throws Exception {
EncapSecurityPayload esp = deserializer.deserialize(bytePacket, 0, bytePacket.length);
String str = esp.toString();
assertTrue(StringUtils.contains(str, "securityParamIndex=" + 0x13572468));
assertTrue(StringUtils.contains(str, ... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(containerService.isContainer(file)) {
final PathAttributes attributes = new PathAttributes();
... | @Test
public void testFindFileUsEast() throws Exception {
final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(new Path(container, new AlphanumericR... |
List<MappingField> resolveAndValidateFields(List<MappingField> userFields, Map<String, ?> options) {
if (options.get(OPTION_FORMAT) == null) {
throw QueryException.error("Missing '" + OPTION_FORMAT + "' option");
}
if (options.get(OPTION_PATH) == null) {
throw QueryExcept... | @Test
public void when_formatIsNotSupported_then_throws() {
assertThatThrownBy(() -> resolvers.resolveAndValidateFields(
emptyList(),
Map.of(OPTION_FORMAT, "some-other-format", OPTION_PATH, "/path")
)).isInstanceOf(QueryException.class)
.hasMessageContaining... |
CreateConnectorRequest parseConnectorConfigurationFile(String filePath) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
File connectorConfigurationFile = Paths.get(filePath).toFile();
try {
Map<String, String> connectorConfigs = objectMapper.readValue(
... | @Test
public void testParseJsonFileWithConnectorConfiguration() throws Exception {
try (FileWriter writer = new FileWriter(connectorConfigurationFile)) {
writer.write(new ObjectMapper().writeValueAsString(CONNECTOR_CONFIG));
}
CreateConnectorRequest request = connectStandalone.p... |
public static <T> Builder<T> newBuilder(int initialCapacity) {
return new Builder<>(initialCapacity);
} | @Test(expected = IllegalArgumentException.class)
public void whenInitialCapacityNegative_thenThrowIllegalArgumentException() {
InflatableSet.newBuilder(-1);
} |
public static String stripAll(final CharSequence str, final CharSequence prefixOrSuffix) {
if (equals(str, prefixOrSuffix)) {
return EMPTY;
}
return stripAll(str, prefixOrSuffix, prefixOrSuffix);
} | @Test
public void stripAllTest() {
final String SOURCE_STRING = "aaa_STRIPPED_bbb";
// ---------------------------- test stripAll ----------------------------
// Normal test
assertEquals("_STRIPPED_bbb", CharSequenceUtil.stripAll(SOURCE_STRING, "a"));
assertEquals(SOURCE_STRING, CharSequenceUtil.stripAll(S... |
@Override
public boolean add(QueryableEntry obj) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testIterator_addUnsopperted() {
result.add(mock(QueryableEntry.class));
} |
@Override
public LeaderAndIsrResponse getErrorResponse(int throttleTimeMs, Throwable e) {
LeaderAndIsrResponseData responseData = new LeaderAndIsrResponseData();
Errors error = Errors.forException(e);
responseData.setErrorCode(error.code());
if (version() < 5) {
List<Lea... | @Test
public void testGetErrorResponse() {
Uuid topicId = Uuid.randomUuid();
String topicName = "topic";
int partition = 0;
for (short version : LEADER_AND_ISR.allVersions()) {
LeaderAndIsrRequest request = new LeaderAndIsrRequest.Builder(version, 0, 0, 0,
... |
@Override
public InputStream getInputStream() {
return new RedissonInputStream();
} | @Test
public void testSkip() throws IOException {
RBinaryStream t = redisson.getBinaryStream("test");
t.set(new byte[] {1, 2, 3, 4, 5, 6});
InputStream is = t.getInputStream();
is.skip(3);
byte[] b = new byte[6];
is.read(b);
assertThat(b).isEqualTo(ne... |
public WeightedItem<T> addOrVote(T item) {
for (int i = 0; i < list.size(); i++) {
WeightedItem<T> weightedItem = list.get(i);
if (weightedItem.item.equals(item)) {
voteFor(weightedItem);
return weightedItem;
}
}
return organize... | @Test
public void testListReorganizesAfterEnoughVotes() {
WeightedEvictableList<String> list = new WeightedEvictableList<>(3, 3);
list.addOrVote("c");
list.addOrVote("b");
list.addOrVote("b");
list.addOrVote("a");
list.addOrVote("a");
list.addOrVote("a");
... |
public ResourcePattern toKafkaResourcePattern() {
org.apache.kafka.common.resource.ResourceType kafkaType;
String kafkaName;
PatternType kafkaPattern = PatternType.LITERAL;
switch (type) {
case TOPIC:
kafkaType = org.apache.kafka.common.resource.ResourceType.... | @Test
public void testToKafkaResourcePatternForGroupResource() {
// Regular group
SimpleAclRuleResource groupResourceRules = new SimpleAclRuleResource("my-group", SimpleAclRuleResourceType.GROUP, AclResourcePatternType.LITERAL);
ResourcePattern expectedKafkaResourcePattern = new ResourcePat... |
@Override
public void createAgent(OFAgent ofAgent) {
checkNotNull(ofAgent, ERR_NULL_OFAGENT);
if (ofAgent.state() == STARTED) {
log.warn(String.format(MSG_OFAGENT, ofAgent.networkId(), ERR_IN_USE));
return;
}
// TODO check if the virtual network exists
... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateAgent() {
target.createAgent(OFAGENT_1);
target.createAgent(OFAGENT_1);
} |
@Override
public boolean isMarshallable(Object o) {
return o instanceof Serializable;
} | @Test
public void testBoxedPrimitivesAndArray() throws Exception {
JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller();
isMarshallable(marshaller, Byte.MAX_VALUE);
isMarshallable(marshaller, Short.MAX_VALUE);
isMarshallable(marshaller, Integer.MAX_VALUE);
isMarsha... |
public static int byteCount(Slice slice, int offset, int length, int codePointCount)
{
requireNonNull(slice, "slice is null");
if (length < 0) {
throw new IllegalArgumentException("length must be greater than or equal to zero");
}
if (offset < 0 || offset + length > slice... | @Test
public void testByteCount()
{
// Single byte code points
assertByteCount("abc", 0, 0, 1, "");
assertByteCount("abc", 0, 1, 0, "");
assertByteCount("abc", 1, 1, 1, "b");
assertByteCount("abc", 1, 1, 2, "b");
assertByteCount("abc", 1, 2, 1, "b");
asser... |
public static void checkNotNegative(long value, String argName) {
checkArgument(value >= 0, "'%s' must not be negative.", argName);
} | @Test
public void testCheckNotNegative() throws Exception {
int positiveArg = 1;
int zero = 0;
int negativeArg = -1;
// Should not throw.
Validate.checkNotNegative(zero, "zeroArg");
Validate.checkNotNegative(positiveArg, "positiveArg");
// Verify it throws.
intercept(IllegalArgument... |
public void expand(String key, long value, RangeHandler rangeHandler, EdgeHandler edgeHandler) {
if (value < lowerBound || value > upperBound) {
// Value outside bounds -> expand to nothing.
return;
}
int maxLevels = value > 0 ? maxPositiveLevels : maxNegativeLevels;
... | @Test
void requireThatSmallRangeIsExpandedInArity2() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2);
Iterator<String> expectedLabels = List.of(
"key=42-43",
"key=40-43",
"key=40-47",
"key=32-47",
... |
@Description("pads a string on the left")
@ScalarFunction("lpad")
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.VARCHAR)
public static Slice leftPad(@SqlType("varchar(x)") Slice text, @SqlType(StandardTypes.BIGINT) long targetLength, @SqlType("varchar(y)") Slice padString)
{
return p... | @Test
public void testLeftPad()
{
assertFunction("LPAD('text', 5, 'x')", VARCHAR, "xtext");
assertFunction("LPAD('text', 4, 'x')", VARCHAR, "text");
assertFunction("LPAD('text', 6, 'xy')", VARCHAR, "xytext");
assertFunction("LPAD('text', 7, 'xy')", VARCHAR, "xyxtext");
a... |
@Override
public String named() {
return PluginEnum.MODIFY_RESPONSE.getName();
} | @Test
public void testNamed() {
assertEquals(modifyResponsePlugin.named(), PluginEnum.MODIFY_RESPONSE.getName());
} |
public static Document readDocument(@Nonnull final InputStream stream) throws ExecutionException, InterruptedException {
return readDocumentAsync(stream).get();
} | @Test
public void testString() throws Exception
{
// Setup test fixture.
final String input = "<foo><bar>test</bar></foo>";
// Execute system under test.
final Document output = SAXReaderUtil.readDocument(input);
// Verify result.
assertNotNull(output);
... |
@Override
public List<String> listPartitionNames(Connection connection, String databaseName, String tableName) {
String partitionNamesQuery =
"SELECT PARTITION_DESCRIPTION as NAME FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = ? " +
"AND TABLE_NAME = ? AND PARTITION_... | @Test
public void testListPartitionNames() {
try {
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
List<String> partitionNames = jdbcMetadata.listPartitionNames("test", "tbl1", TableVersionRange.empty());
Assert.assertFalse(partitionNames.... |
@Override
public boolean process(NacosTask task) {
MergeDataTask mergeTask = (MergeDataTask) task;
final String dataId = mergeTask.dataId;
final String group = mergeTask.groupId;
final String tenant = mergeTask.tenant;
final String tag = mergeTask.tag;
final String cl... | @Test
void testMergerExistAggrConfig() throws InterruptedException {
String dataId = "dataId12345";
String group = "group123";
String tenant = "tenant1234";
when(configInfoAggrPersistService.aggrConfigInfoCount(eq(dataId), eq(group), eq(tenant))).thenReturn(2);
Page<ConfigInf... |
public static void deleteDirectory(File file) {
Path pathToBeDeleted = file.toPath();
try {
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (Exception e) {
... | @Test
void testDeleteDirectory() throws Exception {
new File("target/foo/bar").mkdirs();
FileUtils.writeToFile(new File("target/foo/hello.txt"), "hello world");
FileUtils.writeToFile(new File("target/foo/bar/world.txt"), "hello again");
assertTrue(new File("target/foo/hello.txt").exi... |
@Override
public List<DatabaseTableRespVO> getDatabaseTableList(Long dataSourceConfigId, String name, String comment) {
List<TableInfo> tables = databaseTableService.getTableList(dataSourceConfigId, name, comment);
// 移除在 Codegen 中,已经存在的
Set<String> existsTables = convertSet(
... | @Test
public void testGetDatabaseTableList() {
// 准备参数
Long dataSourceConfigId = randomLongId();
String name = randomString();
String comment = randomString();
// mock 方法
TableInfo tableInfo01 = mock(TableInfo.class);
when(tableInfo01.getName()).thenReturn("t_... |
@Override public void onEvent(ApplicationEvent event) {
// only onRequest is used
} | @Test void onEvent_setsErrorWhenNotAlreadySet() {
setEventType(RequestEvent.Type.FINISHED);
setBaseUri("/");
when(request.getProperty(SpanCustomizer.class.getName())).thenReturn(span);
Exception error = new Exception();
when(requestEvent.getException()).thenReturn(error);
when(request.getPrope... |
@Override
public void removePod(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_POD_UID);
synchronized (this) {
if (isPodInUse(uid)) {
final String error = String.format(MSG_POD, uid, ERR_IN_USE);
throw new IllegalStateException(error);
... | @Test(expected = IllegalArgumentException.class)
public void testRemovePodWithNull() {
target.removePod(null);
} |
synchronized boolean groupSubscribe(Collection<String> topics) {
if (!hasAutoAssignedPartitions())
throw new IllegalStateException(SUBSCRIPTION_EXCEPTION_MESSAGE);
groupSubscription = new HashSet<>(topics);
return !subscription.containsAll(groupSubscription);
} | @Test
public void testGroupSubscribe() {
state.subscribe(singleton(topic1), Optional.of(rebalanceListener));
assertEquals(singleton(topic1), state.metadataTopics());
assertFalse(state.groupSubscribe(singleton(topic1)));
assertEquals(singleton(topic1), state.metadataTopics());
... |
static void registerMethod(MetricsRegistry metricsRegistry, Object osBean, String methodName, String name) {
if (OperatingSystemMXBeanSupport.GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED
&& methodName.equals("getFreePhysicalMemorySize")) {
metricsRegistry.registerStaticProbe(osBean, name, ... | @Test
public void registerMethod_whenDouble() {
FakeOperatingSystemBean fakeOperatingSystemBean = new FakeOperatingSystemBean();
registerMethod(metricsRegistry, fakeOperatingSystemBean, "doubleMethod", "doubleMethod");
DoubleGauge gauge = metricsRegistry.newDoubleGauge("doubleMethod");
... |
public static <T extends Comparable<? super T>> T max(Collection<T> coll) {
return isEmpty(coll) ? null : Collections.max(coll);
} | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void maxEmptyTest() {
final List<? extends Comparable> emptyList = Collections.emptyList();
assertNull(CollUtil.max(emptyList));
} |
public static void destroyServer(ServerConfig serverConfig) {
try {
Server server = serverConfig.getServer();
if (server != null) {
serverConfig.setServer(null);
SERVER_MAP.remove(Integer.toString(serverConfig.getPort()));
server.destroy();... | @Test
public void destroyServer() {
ServerConfig serverConfig = new ServerConfig().setProtocol("test").setPort(1234);
Server server = serverConfig.buildIfAbsent();
Assert.assertNotNull(server);
Assert.assertEquals(1, ServerFactory.getServers().size());
serverConfig.destroy();... |
@GET
@Path("/apps/{appid}/containers/{containerid}")
@Produces(MediaType.APPLICATION_JSON)
public TimelineEntity getContainer(@Context HttpServletRequest req,
@Context HttpServletResponse res, @PathParam("appid") String appId,
@PathParam("containerid") String containerId,
@QueryParam("userid") S... | @Test
void testGetContainer() throws Exception {
Client client = createClient();
try {
URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/"
+ "timeline/clusters/cluster1/apps/app1/"
+ "entities/YARN_CONTAINER/container_2_2");
ClientResponse resp = getResponse(clien... |
public static String unmangleXmlString(String str, boolean decodeEntityRefs)
throws UnmanglingError {
int slashPosition = -1;
String escapedCp = "";
StringBuilder bld = new StringBuilder();
StringBuilder entityRef = null;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i)... | @Test
public void testInvalidSequence() throws Exception {
try {
XMLUtils.unmangleXmlString("\\000g;foo", false);
Assert.fail("expected an unmangling error");
} catch (UnmanglingError e) {
// pass through
}
try {
XMLUtils.unmangleXmlString("\\0", false);
Assert.fail("expe... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForShowColumnsWithTableRule() {
DALStatement dalStatement = mock(MySQLShowColumnsStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(dalStatement);
tableNames.add("table_1");
when(shardingRule.getShardingRuleTableNames(tableNames)).the... |
public void resetTo(int position) {
ensureCapacity(position);
size = position;
} | @Test
public void testResetTo() throws Exception {
RandomAccessData stream = new RandomAccessData();
stream.asOutputStream().write(TEST_DATA_A);
stream.resetTo(1);
assertEquals(1, stream.size());
stream.asOutputStream().write(TEST_DATA_A);
assertArrayEquals(
new byte[] {0x01, 0x01, 0x0... |
public static void validate(WindowConfig windowConfig) {
if (windowConfig.getWindowLengthDurationMs() == null && windowConfig.getWindowLengthCount() == null) {
throw new IllegalArgumentException("Window length is not specified");
}
if (windowConfig.getWindowLengthDurationMs() != nul... | @Test
public void testSettingTumblingTimeWindow() throws Exception {
final Object[] args = new Object[]{-1L, 0L, 1L, 2L, 5L, 10L, null};
for (Object arg : args) {
Object arg0 = arg;
try {
Long windowLengthDuration = null;
if (arg0 != null) {
... |
@Override
public Map<Integer, List<Permission>> getPrintableSpecifiedPermissions(ApplicationId appId) {
return null;
} | @Test
public void testGetPrintableSpecifiedPermissions() {
Map<Integer, List<Permission>> result = getPrintablePermissionMap(getMaximumPermissions(appId));
assertNotNull(result.get(1).get(0));
assertTrue(result.get(1).size() > 0);
assertEquals("testNameAdmin", result.get(1).get(0).ge... |
public void clear() {
final int arrayOffset = getHeadElementIndex();
Arrays.fill(queue, arrayOffset, arrayOffset + size, null);
size = 0;
} | @Test
void testClear() {
HeapPriorityQueue<TestElement> priorityQueueSet = newPriorityQueue(1);
int count = 10;
HashSet<TestElement> checkSet = new HashSet<>(count);
insertRandomElements(priorityQueueSet, checkSet, count);
assertThat(priorityQueueSet.size()).isEqualTo(count)... |
public ReducingStateDescriptor(
String name, ReduceFunction<T> reduceFunction, Class<T> typeClass) {
super(name, typeClass, null);
this.reduceFunction = checkNotNull(reduceFunction);
if (reduceFunction instanceof RichFunction) {
throw new UnsupportedOperationException(
... | @Test
void testReducingStateDescriptor() throws Exception {
ReduceFunction<String> reducer = (a, b) -> a;
TypeSerializer<String> serializer =
new KryoSerializer<>(String.class, new SerializerConfigImpl());
ReducingStateDescriptor<String> descr =
new Reducin... |
public static void setCallId(Operation op, long callId) {
op.setCallId(callId);
} | @Test
public void testSetCallId() {
Operation operation = new DummyOperation();
setCallId(operation, 10);
assertEquals(10, operation.getCallId());
} |
@Override
public void warmUpEncryptedKeys(String... keyNames) throws IOException {
Preconditions.checkArgument(providers.length > 0,
"No providers are configured");
boolean success = false;
IOException e = null;
for (KMSClientProvider provider : providers) {
try {
provider.warmUp... | @Test
public void testWarmUpEncryptedKeysWhenAllProvidersFail() throws Exception {
Configuration conf = new Configuration();
KMSClientProvider p1 = mock(KMSClientProvider.class);
String keyName = "key1";
Mockito.doThrow(new IOException(new AuthorizationException("p1"))).when(p1)
.warmUpEncrypt... |
public Collection<SQLException> closeConnections(final boolean forceRollback) {
Collection<SQLException> result = new LinkedList<>();
synchronized (cachedConnections) {
resetSessionVariablesIfNecessary(cachedConnections.values(), result);
for (Connection each : cachedConnections.... | @Test
void assertCloseConnectionsAndFailedToResetVariables() throws SQLException {
connectionSession.getRequiredSessionVariableRecorder().setVariable("key", "default");
Connection connection = mock(Connection.class, RETURNS_DEEP_STUBS);
when(connection.getMetaData().getDatabaseProductName())... |
public Icon getIcon(final Entry entry) {
if (entry.getAttribute(ICON_INSTANCE) != null)
return entry.getAttribute(ICON_INSTANCE);
String key = (String) entry.getAttribute(ICON);
if (key == null) {
String name = entry.getName();
key = name + ".icon";
}
final Icon icon ... | @Test
public void getsIconFromEntryAttributeIcon() throws Exception {
final Icon icon = new ImageIcon();
entry.setAttribute(EntryAccessor.ICON_INSTANCE, icon);
final Icon entryIcon = entryAccessor.getIcon(entry);
assertThat(entryIcon, equalTo(icon));
} |
@Override
public void upgrade() {
try {
streamService.load(Stream.DEFAULT_STREAM_ID);
} catch (NotFoundException ignored) {
createDefaultStream();
}
} | @Test
public void upgrade() throws Exception {
final ArgumentCaptor<Stream> streamArgumentCaptor = ArgumentCaptor.forClass(Stream.class);
when(streamService.load("000000000000000000000001")).thenThrow(NotFoundException.class);
when(indexSetRegistry.getDefault()).thenReturn(indexSet);
... |
protected String toString(final Map<String, String> configuration) {
return String.join(", ", configuration.entrySet().stream().map(entry -> String.format("%s%s",
entry.getKey(), StringUtils.isNotBlank(entry.getValue()) ? String.format("=%s", entry.getValue()) : StringUtils.EMPTY)).collect(Collector... | @Test
public void testToString() {
final Map<String, String> properties = new LinkedHashMap<>();
properties.put("fs.sync.mode", "online");
properties.put("fs.sync.indexer.enable", "");
properties.put("fs.lock.enable", "");
properties.put("fs.buffer.enable", "");
asser... |
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception {
Http2HeadersSink sink = new Http2HeadersSink(
streamId, headers, maxHeaderListSize, validateHeaders);
// Check for dynamic table size updates, which must occur at the beginning:
... | @Test
public void testLiteralWithIncrementalIndexingWithLargeValue() throws Http2Exception {
// Ignore header that exceeds max header size
final StringBuilder sb = new StringBuilder();
sb.append("4004");
sb.append(hex("name"));
sb.append("7F813F");
for (int i = 0; i <... |
@Override
public CloudConfiguration getCloudConfiguration() {
return hdfsEnvironment.getCloudConfiguration();
} | @Test
public void testGetCloudConfiguration() {
CloudConfiguration cc = hudiMetadata.getCloudConfiguration();
Assert.assertEquals(cc.getCloudType(), CloudType.DEFAULT);
} |
@Override
protected Result[] run(String value) {
final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly);
// the extractor instance is rebuilt every second anyway
final Match match = grok.match(value);
final Map<String, Object> matches = matc... | @Test
public void testDatatypeExtraction() {
final GrokExtractor extractor = makeExtractor("%{NUMBER:number;int}");
final Extractor.Result[] results = extractor.run("199999");
assertEquals("NUMBER is marked as UNWANTED and does not generate a field", 1, results.length);
assertEquals... |
@Override
public void unbindSocialUser(Long userId, Integer userType, Integer socialType, String openid) {
// 获得 openid 对应的 SocialUserDO 社交用户
SocialUserDO socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, openid);
if (socialUser == null) {
throw exception(SOCIAL_USE... | @Test
public void testUnbindSocialUser_success() {
// 准备参数
Long userId = 1L;
Integer userType = UserTypeEnum.ADMIN.getValue();
Integer type = SocialTypeEnum.GITEE.getType();
String openid = "test_openid";
// mock 数据:社交用户
SocialUserDO socialUser = randomPojo(So... |
@Override
public boolean isAllowable(URL url, Invocation invocation) {
int rate = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY, -1);
long interval = url.getMethodParameter(
RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_... | @Test
void testTPSLimiterForMethodLevelConfig() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
in... |
@Override
protected Result[] run(String value) {
final Map<String, Object> extractedJson;
try {
extractedJson = extractJson(value);
} catch (IOException e) {
throw new ExtractorException(e);
}
final List<Result> results = new ArrayList<>(extractedJson.... | @Test
public void testRunWithObjectAndDifferentKeySeparator() throws Exception {
final JsonExtractor jsonExtractor = new JsonExtractor(new MetricRegistry(), "json", "title", 0L, Extractor.CursorStrategy.COPY,
"source", "target", ImmutableMap.<String, Object>of("key_separator", ":"), "user", ... |
public Future<Void> maybeRollingUpdate(Reconciliation reconciliation, int replicas, Labels selectorLabels, Function<Pod, List<String>> podRestart, TlsPemIdentity coTlsPemIdentity) {
String namespace = reconciliation.namespace();
// We prepare the list of expected Pods. This is needed as we need to acco... | @Test
public void testNonReadinessOfLeaderCanPreventAllPodRestarts(VertxTestContext context) {
final String followerPod1NeedsRestart = "name-zookeeper-1";
final String leaderPodNeedsRestartNonReady = "name-zookeeper-2";
final String followerPod2NeedsRestart = "name-zookeeper-0";
fin... |
public void setSignatureKeyFileName(String signatureKeyFileName) {
this.signatureKeyFileName = signatureKeyFileName;
} | @Test
void testSignatureVerificationOptionIgnore() throws Exception {
// encryptor is sending a PGP message with signature! Decryptor is ignoreing the signature
decryptor.setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_IGNORE);
decryptor.setSignatureKeyUs... |
public boolean isTaskDeployedAsFinished() {
if (jobManagerTaskRestore == null) {
return false;
}
return jobManagerTaskRestore.getTaskStateSnapshot().isTaskDeployedAsFinished();
} | @Test
void testStateRetrievingWithFinishedOperator() {
TaskStateSnapshot taskStateSnapshot = TaskStateSnapshot.FINISHED_ON_RESTORE;
JobManagerTaskRestore jobManagerTaskRestore =
new JobManagerTaskRestore(2, taskStateSnapshot);
TaskStateManagerImpl stateManager =
... |
public void flush() {
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
} | @Test
void flush() {
out.append("Hello");
assertThat(bytes, bytes(equalTo("")));
out.flush();
assertThat(bytes, bytes(equalTo("Hello")));
} |
protected List<String> parse(final int response, final String[] reply) {
final List<String> result = new ArrayList<String>(reply.length);
for(final String line : reply) {
// Some servers include the status code for every line.
if(line.startsWith(String.valueOf(response))) {
... | @Test
public void testParseEgnyte() throws Exception {
final List<String> lines = Arrays.asList(
"200-drwx------ 0 - - 0 Jun 17 07:59 core",
"200 -rw------- 0 David-Kocher - 529 Jun 17 07:59 App.config");
final FTPFileEntryParser parser = new LaxUnixFT... |
public RemotingDesc parserRemotingServiceInfo(Object bean, String beanName, RemotingParser remotingParser) {
if (remotingServiceMap.containsKey(bean)) {
return remotingServiceMap.get(bean);
}
RemotingDesc remotingBeanDesc = remotingParser.getServiceDesc(bean, beanName);
if (r... | @Test
public void testParserRemotingServiceInfo() {
SimpleRemoteBean remoteBean = new SimpleRemoteBean();
SimpleRemotingParser parser = new SimpleRemotingParser();
RemotingDesc desc = remotingParser.parserRemotingServiceInfo(remoteBean, remoteBean.getClass().getName(),
parser... |
@Override
@SuppressWarnings("all")
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain,
final SelectorData selector, final RuleData rule) {
String param = exchange.getAttribute(Constants.PARAM_TRANSFORM);
ShenyuContext... | @Test
public void testDoExecute() {
when(chain.execute(exchange)).thenReturn(Mono.empty());
Mono<Void> result = motanPlugin.doExecute(exchange, chain, selectorData, ruleData);
StepVerifier.create(result).expectSubscription().verifyComplete();
} |
@Override
public BytesInput getBytes() {
// The Page Header should include: blockSizeInValues, numberOfMiniBlocks, totalValueCount
if (deltaValuesToFlush != 0) {
flushBlockBuffer();
}
return BytesInput.concat(
config.toBytesInput(),
BytesInput.fromUnsignedVarInt(totalValueCount),... | @Test
public void shouldSkip() throws IOException {
long[] data = new long[5 * blockSize + 1];
for (int i = 0; i < data.length; i++) {
data[i] = i * 32;
}
writeData(data);
reader = new DeltaBinaryPackingValuesReader();
reader.initFromPage(100, writer.getBytes().toInputStream());
for ... |
public Collection<String> getCandidateEIPs(String myInstanceId, String myZone) {
if (myZone == null) {
myZone = "us-east-1d";
}
Collection<String> eipCandidates = clientConfig.shouldUseDnsForFetchingServiceUrls()
? getEIPsForZoneFromDNS(myZone)
... | @Test
public void shouldFilterNonElasticNames() {
when(config.getRegion()).thenReturn("us-east-1");
List<String> hosts = Lists.newArrayList("example.com", "ec2-1-2-3-4.compute.amazonaws.com", "5.6.7.8",
"ec2-101-202-33-44.compute.amazonaws.com");
when(config.getEurekaServerSe... |
@Override
public DeleteRecordsResult deleteRecords(final Map<TopicPartition, RecordsToDelete> recordsToDelete,
final DeleteRecordsOptions options) {
SimpleAdminApiFuture<TopicPartition, DeletedRecords> future = DeleteRecordsHandler.newFuture(recordsToDelete.keySe... | @Test
public void testDeleteRecordsMultipleSends() throws Exception {
String topic = "foo";
TopicPartition tp0 = new TopicPartition(topic, 0);
TopicPartition tp1 = new TopicPartition(topic, 1);
MockTime time = new MockTime();
try (AdminClientUnitTestEnv env = new AdminClien... |
@Override
public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) {
// unfortunately, this method does not run in the scheduler executor, but in the
// checkpoint coordinator time thread.
// we can remove the delegation once the checkpoint coordinator runs full... | @Test
void completedCheckpointFuture() throws Exception {
final EventReceivingTasks tasks = EventReceivingTasks.createForRunningTasks();
final OperatorCoordinatorHolder holder =
createCoordinatorHolder(tasks, TestingOperatorCoordinator::new);
final byte[] testData = new byte... |
static ProtocolHandlerWithClassLoader load(ProtocolHandlerMetadata metadata,
String narExtractionDirectory) throws IOException {
final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
NarClassLoader ncl = NarClassLoaderBuilder.builder()
... | @Test
public void testLoadProtocolHandlerBlankHandlerClass() throws Exception {
ProtocolHandlerDefinition def = new ProtocolHandlerDefinition();
def.setDescription("test-protocol-handler");
String archivePath = "/path/to/protocol/handler/nar";
ProtocolHandlerMetadata metadata = new... |
public static CoderProvider fromStaticMethods(Class<?> rawType, Class<?> coderClazz) {
checkArgument(
Coder.class.isAssignableFrom(coderClazz),
"%s is not a subtype of %s",
coderClazz.getName(),
Coder.class.getSimpleName());
return new CoderProviderFromStaticMethods(rawType, code... | @Test
public void testKvCoderProvider() throws Exception {
TypeDescriptor<KV<Double, Double>> type =
TypeDescriptors.kvs(TypeDescriptors.doubles(), TypeDescriptors.doubles());
CoderProvider kvCoderProvider = CoderProviders.fromStaticMethods(KV.class, KvCoder.class);
assertEquals(
KvCoder.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.