focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public byte[] serialize(final String topic, final T data) {
try {
return delegate.serialize(topic, data);
} catch (final RuntimeException e) {
processingLogger.error(new SerializationError<>(e, Optional.of(data), topic, isKey));
throw e;
}
} | @Test
public void shouldLogOnException() {
// Given:
when(delegate.serialize(any(), any())).thenThrow(ERROR);
// When:
assertThrows(
RuntimeException.class,
() -> serializer.serialize("t", SOME_ROW)
);
// Then:
verify(processingLogger).error(new SerializationError<>(ERROR... |
public long availableMemory() {
lock.lock();
try {
return this.nonPooledAvailableMemory + freeSize() * (long) this.poolableSize;
} finally {
lock.unlock();
}
} | @Test
public void testStressfulSituation() throws Exception {
int numThreads = 10;
final int iterations = 50000;
final int poolableSize = 1024;
final long totalMemory = numThreads / 2 * poolableSize;
final BufferPool pool = new BufferPool(totalMemory, poolableSize, metrics, t... |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertDecodeUnknownTableType() {
ByteBuffer data = ByteBuffer.wrap("unknown".getBytes());
assertThat(new MppdbDecodingPlugin(null, false, false).decode(data, logSequenceNumber), instanceOf(PlaceholderEvent.class));
} |
public void close() {
close(Long.MAX_VALUE, false);
} | @Test
public void shouldReturnFalseOnCloseWithCloseOptionWithLeaveGroupTrueWhenThreadsHaventTerminated() throws Exception {
prepareStreams();
prepareStreamThread(streamThreadOne, 1);
prepareStreamThread(streamThreadTwo, 2);
prepareTerminableThread(streamThreadOne);
final Moc... |
public static Descriptors.MethodDescriptor findMethodDescriptor(String base64ProtobufDescriptor, String serviceName,
String methodName) throws InvalidProtocolBufferException, Descriptors.DescriptorValidationException {
// Now we may have serviceName as being the FQDN. We have to find short version to la... | @Test
void testFindMethodDescriptor() {
// This is the simple HelloService with no dependencies.
String base64ProtobufDescriptor = "CrICCg5oZWxsby12MS5wcm90bxIgaW8uZ2l0aHViLm1pY3JvY2tzLmdycGMuaGVsbG8udjEiSAoMSGVsbG9SZXF1ZXN0EhwKCWZpcnN0bmFtZRgBIAEoCVIJZmlyc3RuYW1lEhoKCGxhc3RuYW1lGAIgASgJUghsYXN0bmFtZSIrC... |
public static Range<Comparable<?>> safeClosed(final Comparable<?> lowerEndpoint, final Comparable<?> upperEndpoint) {
try {
return Range.closed(lowerEndpoint, upperEndpoint);
} catch (final ClassCastException ex) {
Optional<Class<?>> clazz = getTargetNumericType(Arrays.asList(low... | @Test
void assertSafeClosedForLong() {
Range<Comparable<?>> range = SafeNumberOperationUtils.safeClosed(12, 5001L);
assertThat(range.lowerEndpoint(), is(12L));
assertThat(range.upperEndpoint(), is(5001L));
} |
public int minValue()
{
final int initialValue = this.initialValue;
int min = 0 == size ? initialValue : Integer.MAX_VALUE;
final int[] entries = this.entries;
@DoNotSub final int length = entries.length;
for (@DoNotSub int i = 1; i < length; i += 2)
{
f... | @Test
void shouldHaveNoMinValueForEmptyCollection()
{
assertEquals(INITIAL_VALUE, map.minValue());
} |
public List<StreamPartitionWithWatermark> readStreamPartitionsWithWatermark()
throws InvalidProtocolBufferException {
LOG.debug(
"Reading stream partitions from metadata table: "
+ getFullStreamPartitionPrefix().toStringUtf8());
Filter filterForWatermark =
FILTERS
.... | @Test
public void testReadStreamPartitionsWithWatermark() throws InvalidProtocolBufferException {
ByteStringRange lockedPartition = ByteStringRange.create("", "a");
PartitionRecord partitionRecord =
new PartitionRecord(
lockedPartition,
Instant.now(),
UniqueIdGenera... |
void deleteObsoleteFiles() {
final long rrdDiskUsage = CounterStorage.deleteObsoleteCounterFiles(getApplication());
final long serGzDiskUsage = JRobin.deleteObsoleteJRobinFiles(getApplication());
diskUsage = rrdDiskUsage + serGzDiskUsage;
// il manque la taille du fichier "last_shutdown.html", mais on n'est pas... | @Test
public void testDeleteObsoleteFiles() {
final Collector collector = createCollectorWithOneCounter();
collector.deleteObsoleteFiles();
} |
@Override
protected String convertFromString(final String value) throws ConversionException {
final Path path = Paths.get(value);
if (path.getParent() != null) {
throw new ConversionException(
String.format("%s must be a filename only (%s)", KEY, path));
}
... | @Test
void testConvertFromString() throws Exception {
final String expectedJarId = "test.jar";
final String jarId = jarIdPathParameter.convertFromString(expectedJarId);
assertThat(jarId).isEqualTo(expectedJarId);
} |
@Override
public Map<String, String> responseHeaders() {
return unmodifiableMap(responseHeaders);
} | @Test
public void shouldReturnUnmodifiableResponseHeaders() throws Exception {
DefaultGoApiResponse response = new DefaultGoApiResponse(0);
Map<String, String> headers = response.responseHeaders();
try {
headers.put("new-key", "new-value");
fail("Should not allow modi... |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = true;
boolean containsNull = false;
// Spec. definitio... | @Test
void invokeArrayParamReturnNull() {
FunctionTestUtil.assertResultNull(allFunction.invoke(new Object[]{Boolean.TRUE, null, Boolean.TRUE}));
} |
@KafkaClientInternalsDependant
@VisibleForTesting
Mono<Map<TopicPartition, Long>> listOffsetsUnsafe(Collection<TopicPartition> partitions, OffsetSpec offsetSpec) {
if (partitions.isEmpty()) {
return Mono.just(Map.of());
}
Function<Collection<TopicPartition>, Mono<Map<TopicPartition, Long>>> call ... | @Test
void testListOffsetsUnsafe() {
String topic = UUID.randomUUID().toString();
createTopics(new NewTopic(topic, 2, (short) 1));
// sending messages to have non-zero offsets for tp
try (var producer = KafkaTestProducer.forKafka(kafka)) {
producer.send(new ProducerRecord<>(topic, 1, "k", "v"))... |
public static URI parse(String featureIdentifier) {
requireNonNull(featureIdentifier, "featureIdentifier may not be null");
if (featureIdentifier.isEmpty()) {
throw new IllegalArgumentException("featureIdentifier may not be empty");
}
// Legacy from the Cucumber Eclipse plug... | @Test
void can_parse_empty_feature_path() {
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> FeaturePath.parse(""));
assertThat(exception.getMessage(), is("featureIdentifier may not be empty"));
} |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testUnpartitionedTruncateString() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
TruncateFunction.TruncateString function = new TruncateFunction.TruncateString();
UserDefinedScalarFunc udf = toUDF(function, expressio... |
Tracer(
Propagation.Factory propagationFactory,
SpanHandler spanHandler,
PendingSpans pendingSpans,
Sampler sampler,
CurrentTraceContext currentTraceContext,
boolean traceId128Bit,
boolean supportsJoin,
boolean alwaysSampleLocal,
AtomicBoolean noop
) {
this.propagationFactory =... | @Test void sampler() {
Sampler sampler = new Sampler() {
@Override public boolean isSampled(long traceId) {
return false;
}
};
tracer = Tracing.newBuilder().sampler(sampler).build().tracer();
assertThat(tracer.sampler)
.isSameAs(sampler);
} |
public void processOnce() throws IOException {
// set status of query to OK.
ctx.getState().reset();
executor = null;
// reset sequence id of MySQL protocol
final MysqlChannel channel = ctx.getMysqlChannel();
channel.setSequenceId(0);
// read packet from channel
... | @Test
public void testUnknownCommand() throws Exception {
MysqlSerializer serializer = MysqlSerializer.newInstance();
serializer.writeInt1(101);
ByteBuffer packet = serializer.toByteBuffer();
ConnectContext ctx = initMockContext(mockChannel(packet), GlobalStateMgr.getCurrentState());... |
public CompletableFuture<Integer> inferSourceParallelismAsync(
int parallelismInferenceUpperBound, long dataVolumePerTask) {
return context.supplyAsync(
() -> {
if (!(source instanceof DynamicParallelismInference)) {
... | @Test
public void testInferSourceParallelismAsync() throws Exception {
final String listeningID = "testListeningID";
class TestDynamicFilteringEvent implements SourceEvent, DynamicFilteringInfo {}
CoordinatorStore store = new CoordinatorStoreImpl();
store.putIfAbsent(listeningID, n... |
@Override
public void run(T configuration, Environment environment) throws Exception {
final Map<String, Map<String, String>> options = getViewConfiguration(configuration);
for (ViewRenderer viewRenderer : viewRenderers) {
final Map<String, String> viewOptions = options.get(viewRenderer.... | @Test
void addsTheViewMessageBodyWriterToTheEnvironment() throws Exception {
new ViewBundle<>().run(new MyConfiguration(), environment);
verify(jerseyEnvironment).register(any(ViewMessageBodyWriter.class));
} |
public static Sensor processLatencySensor(final String threadId,
final String taskId,
final StreamsMetricsImpl streamsMetrics) {
return avgAndMaxSensor(
threadId,
taskId,
PROCESS_LATEN... | @Test
public void shouldGetProcessLatencySensor() {
final String operation = "process-latency";
when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG))
.thenReturn(expectedSensor);
final String avgLatencyDescription = "The average latency of ... |
public static RestServerConfig forPublic(Integer rebalanceTimeoutMs, Map<?, ?> props) {
return new PublicConfig(rebalanceTimeoutMs, props);
} | @Test
public void testAdminListenersNotAllowingBlankStrings() {
Map<String, String> props = new HashMap<>();
props.put(RestServerConfig.ADMIN_LISTENERS_CONFIG, "http://a.b:9999, ,https://a.b:9999");
assertThrows(ConfigException.class, () -> RestServerConfig.forPublic(null, props));
} |
public TopicRouteData getAnExistTopicRouteData(final String topic) {
return this.topicRouteTable.get(topic);
} | @Test
public void testGetAnExistTopicRouteData() {
topicRouteTable.put(topic, createTopicRouteData());
TopicRouteData actual = mqClientInstance.getAnExistTopicRouteData(topic);
assertNotNull(actual);
assertNotNull(actual.getQueueDatas());
assertNotNull(actual.getBrokerDatas()... |
public static boolean getBooleanWithAltKeys(org.apache.flink.configuration.Configuration conf,
ConfigProperty<?> configProperty) {
Option<String> rawValue = getRawValueWithAltKeys(conf, configProperty);
boolean defaultValue = configProperty.hasDefaultValue()
... | @Test
public void testGetBooleanWithAltKeys() {
Configuration flinkConf = new Configuration();
assertEquals(Boolean.parseBoolean(TEST_BOOLEAN_CONFIG_PROPERTY.defaultValue()),
FormatUtils.getBooleanWithAltKeys(flinkConf, TEST_BOOLEAN_CONFIG_PROPERTY));
boolean setValue = !Boolean.parseBoolean(TEST... |
public static String validateColumnName(@Nullable String columnName) {
String name = requireNonNull(columnName, "Column name cannot be null");
checkDbIdentifierCharacters(columnName, "Column name");
return name;
} | @Test
public void fail_when_column_name_is_in_upper_case() {
assertThatThrownBy(() -> validateColumnName("DATE_IN_MS"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'DATE_IN_MS'");
} |
static JavaType constructType(Type type) {
try {
return constructTypeInner(type);
} catch (Exception e) {
throw new InvalidDataTableTypeException(type, e);
}
} | @Test
void optional_is_optional_type() {
JavaType javaType = TypeFactory.constructType(OPTIONAL_NUMBER);
assertThat(javaType.getClass(), equalTo(TypeFactory.OptionalType.class));
assertThat(javaType.getOriginal(), is(OPTIONAL_NUMBER));
} |
@Override
public void updateRouter(Router osRouter) {
checkNotNull(osRouter, ERR_NULL_ROUTER);
checkArgument(!Strings.isNullOrEmpty(osRouter.getId()), ERR_NULL_ROUTER_ID);
osRouterStore.updateRouter(osRouter);
log.info(String.format(MSG_ROUTER, osRouter.getId(), MSG_UPDATED));
} | @Test(expected = IllegalArgumentException.class)
public void testUpdateUnregisteredRouter() {
target.updateRouter(ROUTER);
} |
public static Object newInstance(String name) {
try {
return forName(name).getDeclaredConstructor().newInstance();
} catch (InstantiationException
| IllegalAccessException
| InvocationTargetException
| NoSuchMethodException e) {
thr... | @Test
void testNewInstance() {
HelloServiceImpl0 instance = (HelloServiceImpl0) ClassUtils.newInstance(HelloServiceImpl0.class.getName());
Assertions.assertEquals("Hello world!", instance.sayHello());
} |
@Override public HashSlotCursor8byteKey cursor() {
return new Cursor();
} | @Test
public void testCursor_key() {
final long key = random.nextLong();
insert(key);
HashSlotCursor8byteKey cursor = hsa.cursor();
cursor.advance();
assertEquals(key, cursor.key());
} |
static byte[] generateRandomBytes(int size) {
byte[] bytes = new byte[size];
secureRandom().nextBytes(bytes);
return bytes;
} | @Test
public void testGenerateRandomBytes() {
assertArrayEquals(Wallet.generateRandomBytes(0), (new byte[] {}));
assertEquals(Wallet.generateRandomBytes(10).length, (10));
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
int laneCount = 1;
if (way.hasTag("lanes")) {
String noLanes = way.getTag("lanes");
String[] noLanesTok = noLanes.split(";|\\.");
if (noLanesTok.le... | @Test
void notTagged() {
ReaderWay readerWay = new ReaderWay(1);
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
Assertions.assertEquals(1, lanesEnc.getInt(false, edgeId, edgeIntAccess)... |
@Override
public Long createJobLog(Long jobId, LocalDateTime beginTime,
String jobHandlerName, String jobHandlerParam, Integer executeIndex) {
JobLogDO log = JobLogDO.builder().jobId(jobId).handlerName(jobHandlerName)
.handlerParam(jobHandlerParam).executeIndex(e... | @Test
public void testCreateJobLog() {
// 准备参数
JobLogDO reqVO = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1));
// 调用
Long id = jobLogService.createJobLog(reqVO.getJobId(), reqVO.getBeginTime(),
reqVO.getHandlerName(), reqVO.getHandlerParam(), reqVO.getExecute... |
public static long getSizeOfPhysicalMemory() {
// first try if the JVM can directly tell us what the system memory is
// this works only on Oracle JVMs
try {
Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
Method method = clazz.getMethod("getTo... | @Test
void testPhysicalMemory() {
try {
long physMem = Hardware.getSizeOfPhysicalMemory();
assertThat(physMem).isGreaterThanOrEqualTo(-1);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
} |
public int getIndex_depth() {
return index_depth;
} | @Test
public void testGetIndex_depth() {
assertEquals(TestParameters.VP_INDEX_DEPTH, chmItspHeader.getIndex_depth());
} |
public String getType() {
return type;
} | @Test
void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"type\":\"deregisterInstance\",\"success\":true}";
InstanceResponse response = mapper.readValue(json, InstanceResponse.class);
assertEquals(NamingRemoteConstants.DE_REGISTER_INST... |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldLoadIgnoresFromSvnPartial() throws Exception {
String buildXmlPartial =
"""
<svn url="file:///tmp/testSvnRepo/project1/trunk" >
<filter>
<ignore pattern="x"/>
... |
@Override
public void put(final Bytes rawBaseKey,
final byte[] value) {
final long timestamp = baseKeySchema.segmentTimestamp(rawBaseKey);
observedStreamTime = Math.max(observedStreamTime, timestamp);
final long segmentId = segments.segmentId(timestamp);
final S s... | @Test
public void shouldPutAndBackwardFetchEdgeKeyRange() {
final String keyA = "a";
final String keyB = "b";
final Bytes serializedKeyAStart = serializeKey(new Windowed<>(keyA, startEdgeWindow), false,
Integer.MAX_VALUE);
final Bytes serializedKeyAEnd = serializeKey(new... |
public static String initNamespaceForNaming(NacosClientProperties properties) {
String tmpNamespace = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAME... | @Test
void testInitNamespaceFromAnsWithCloudParsing() {
String expect = "ans";
System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, expect);
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAM... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Server ID", server.getId());
setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel());
... | @Test
public void toProtobuf_whenInstanceIsNotManaged_shouldWriteNothing() {
when(commonSystemInformation.getManagedInstanceProviderName()).thenReturn(null);
ProtobufSystemInfo.Section protobuf = underTest.toProtobuf();
assertThatAttributeDoesNotExist(protobuf, "External Users and Groups Provisioning");
... |
@Override
public Optional<SchemaDescription> getSchema(String topic, Target type) {
String subject = schemaSubject(topic, type);
return getSchemaBySubject(subject)
.flatMap(schemaMetadata ->
//schema can be not-found, when schema contexts configured improperly
getSchemaById(sch... | @Test
void returnsEmptyDescriptorIfSchemaNotRegisteredInSR() {
String topic = "test";
assertThat(serde.getSchema(topic, Serde.Target.KEY)).isEmpty();
assertThat(serde.getSchema(topic, Serde.Target.VALUE)).isEmpty();
} |
public static boolean isChinese(CharSequence value) {
return isMatchRegex(PatternPool.CHINESES, value);
} | @Test
public void isChineseTest() {
assertTrue(Validator.isChinese("全都是中文"));
assertTrue(Validator.isChinese("㐓㐘"));
assertFalse(Validator.isChinese("not全都是中文"));
} |
public void processNullMessage(Null nullMessage, Afnemersbericht afnemersbericht){
if (afnemersbericht != null && afnemersbericht.getType() == Afnemersbericht.Type.Av01){
afnemersberichtRepository.delete(afnemersbericht);
}
logger.info("Received null message");
} | @Test
public void testProcessNullMessageNotAv01(){
Null testNullMessage = TestDglMessagesUtil.createTestNullMessage();
when(afnemersbericht.getType()).thenReturn(Afnemersbericht.Type.Ap01);
classUnderTest.processNullMessage(testNullMessage, afnemersbericht);
verify(afnemersbericht... |
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
Object result = getCurrentQueryResult().getValue(columnIndex, type);
wasNull = getCurrentQueryResult().wasNull();
return result;
} | @Test
void assertGetValue() throws SQLException {
QueryResult queryResult = mock(QueryResult.class);
when(queryResult.getValue(1, Object.class)).thenReturn("1");
streamMergedResult.setCurrentQueryResult(queryResult);
assertThat(streamMergedResult.getValue(1, Object.class).toString(),... |
@VisibleForTesting
public void validateSmsTemplateCodeDuplicate(Long id, String code) {
SmsTemplateDO template = smsTemplateMapper.selectByCode(code);
if (template == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if (id == null) {
throw exception(... | @Test
public void testValidateSmsTemplateCodeDuplicate_valueDuplicateForCreate() {
// 准备参数
String code = randomString();
// mock 数据
smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code)));
// 调用,校验异常
assertServiceException(() -> smsTemplateService.validat... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefin... | @Test
public void testConvertBfile() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("bfile")
.dataType("bfile")
.length(2147483647L)
... |
public static List<Date> matchedDates(String patternStr, Date start, int count, boolean isMatchSecond) {
return matchedDates(patternStr, start, DateUtil.endOfYear(start), count, isMatchSecond);
} | @Test
public void matchedDatesTest2() {
//测试每小时执行
List<Date> matchedDates = CronPatternUtil.matchedDates("0 0 */1 * * *", DateUtil.parse("2018-10-15 14:33:22"), 5, true);
assertEquals(5, matchedDates.size());
assertEquals("2018-10-15 15:00:00", matchedDates.get(0).toString());
assertEquals("2018-10-15 16:00:... |
public static URI parse(String featureIdentifier) {
return parse(FeaturePath.parse(featureIdentifier));
} | @Test
void reject_directory_form() {
Executable testMethod = () -> FeatureIdentifier.parse(URI.create("classpath:/path/to"));
IllegalArgumentException actualThrown = assertThrows(IllegalArgumentException.class, testMethod);
assertThat("Unexpected exception message", actualThrown.getMessage()... |
public boolean fileIsInAllowedPath(Path path) {
if (allowedPaths.isEmpty()) {
return true;
}
final Path realFilePath = resolveRealPath(path);
if (realFilePath == null) {
return false;
}
for (Path allowedPath : allowedPaths) {
final Pat... | @Test
public void outsideOfAllowedPath() throws IOException {
final Path permittedPath = permittedTempDir.getRoot().toPath();
final Path filePath = forbiddenTempDir.newFile(FILE).toPath();
pathChecker = new AllowedAuxiliaryPathChecker(new TreeSet<>(Collections.singleton(permittedPath)));
... |
@Override
@MethodNotAvailable
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor,
Object... arguments) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testInvokeAll() {
Set<Integer> keys = new HashSet<>(asList(23, 65, 88));
adapter.invokeAll(keys, new ICacheReplaceEntryProcessor(), "value", "newValue");
} |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void sessionWindowedCogroupedZeroArgCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.cogroup((key, value, aggregate) -> value)
.windowedBy(SessionWindows.ofInact... |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeGeometry() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.GEOMETRY), instanceOf(MySQLStringLenencBinaryProtocolValue.class));
} |
public static String substringBefore(String s, String splitter) {
int endIndex = s.indexOf(splitter);
if (endIndex >= 0) {
return s.substring(0, endIndex);
}
return s;
} | @Test
void testSubstringBeforeSplitterMultiChar() {
assertThat(substringBefore("this is a test", " is ")).isEqualTo("this");
assertThat(substringBefore("this is a test", " was ")).isEqualTo("this is a test");
} |
@Override
public void connect(
ChannelHandlerContext ctx,
SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "CONNECT", remoteAddress, localAddres... | @Test
public void shouldLogChannelConnect() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.connect(new InetSocketAddress(80)).await();
verify(appender).doAppend(argThat(new RegexLogMatcher(".+CONNECT: 0.0.0.0/0.0.0.0:80$")));
} |
public boolean isSupported(final SQLStatement sqlStatement) {
for (Class<? extends SQLStatement> each : supportedSQLStatements) {
if (each.isAssignableFrom(sqlStatement.getClass())) {
return true;
}
}
for (Class<? extends SQLStatement> each : unsupportedSQ... | @Test
void assertIsSupportedWithOverlappedList() {
assertTrue(new SQLSupportedJudgeEngine(Collections.singleton(SelectStatement.class), Collections.singleton(SQLStatement.class)).isSupported(mock(SelectStatement.class)));
} |
public static <T> TimeLimiterOperator<T> of(TimeLimiter timeLimiter) {
return new TimeLimiterOperator<>(timeLimiter);
} | @Test
public void timeoutUsingFlux() {
given(timeLimiter.getTimeLimiterConfig())
.willReturn(toConfig(Duration.ofMillis(1)));
Flux<?> flux = Flux.interval(Duration.ofSeconds(1))
.transformDeferred(TimeLimiterOperator.of(timeLimiter));
StepVerifier.create(flux)
... |
@Override
public synchronized boolean remove(Object o) {
int idx = originList.indexOf(o);
if (idx > -1 && rootSet.get(idx)) {
rootSet.set(idx, false);
return true;
}
if (CollectionUtils.isNotEmpty(tailList)) {
return tailList.remove(o);
}
... | @Test
void testRemove() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertTrue(bitList.remove("A"));
Assertions.assertFalse(bitList.remove("A"));
Assertions.assertTrue(bitList.removeAll(Collections.singletonL... |
public List<MappingField> resolveAndValidateFields(
List<MappingField> userFields,
Map<String, String> options,
NodeEngine nodeEngine
) {
final InternalSerializationService serializationService = (InternalSerializationService) nodeEngine
.getSerializationS... | @Test
@Parameters({
"__key",
"this"
})
public void when_renamedKeyOrThis_then_throws(String fieldName) {
MappingField field = field(fieldName, QueryDataType.INT, "renamed");
assertThatThrownBy(() -> resolvers.resolveAndValidateFields(singletonList(field), emptyMap(), ... |
public FontMetrics parse() throws IOException
{
return parseFontMetric(false);
} | @Test
void testMalformedFloat() throws IOException
{
AFMParser parser = new AFMParser(
new FileInputStream("src/test/resources/afm/MalformedFloat.afm"));
try
{
parser.parse();
fail("The AFMParser should have thrown an IOException because of a malfo... |
public static Set<X509Certificate> filterValid( X509Certificate... certificates )
{
final Set<X509Certificate> results = new HashSet<>();
if (certificates != null)
{
for ( X509Certificate certificate : certificates )
{
if ( certificate == null )
... | @Test
public void testFilterValidWithOneValidCert() throws Exception
{
// Setup fixture.
final X509Certificate valid = KeystoreTestUtils.generateValidCertificate().getCertificate();
final Collection<X509Certificate> input = new ArrayList<>();
input.add( valid );
// Execu... |
public static void registry(NotificationListener notificationListener,
Class<? extends NotificationType> typeClass) {
if (!isEnable()) {
return;
}
List<NotificationListener> listenerList = NOTIFICATION_LISTENER_MAP.computeIfAbsent(
typeClass.getCanonicalNa... | @Test
public void registry() {
NotificationManager.registry(new ListenerTest(), NettyNotificationType.class);
Optional<?> mapOptional = ReflectUtils.getStaticFieldValue(NotificationManager.class, LISTENER_MAP);
Assert.assertTrue(mapOptional.isPresent());
Map<String, List<Notification... |
@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && isApplicableType(field)) {
if (node.has("minimum")) {
final Class<? extends Annotatio... | @Test
public void testNotUsed() {
when(config.isIncludeJsr303Annotations()).thenReturn(true);
when(node.has("minimum")).thenReturn(false);
when(node.has("maximum")).thenReturn(false);
when(fieldVar.type().boxify().fullName()).thenReturn(fieldClass.getTypeName());
JFieldVar r... |
static void dissectResolve(
final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
int absoluteOffset = offset;
absoluteOffset += dissectLogHeader(CONTEXT, NAME_RESOLUTION_RESOLVE, buffer, absoluteOffset, builder);
final boolean isReResolution = 1 == buff... | @Test
void dissectResolve() throws UnknownHostException
{
final String resolver = "testResolver";
final long durationNs = 32167;
final String hostname = "localhost";
final boolean isReResolution = false;
final InetAddress address = InetAddress.getByName("127.0.0.1");
... |
static Object[] calculateActualParams(Method m, NamedParameter[] params) {
logger.trace("calculateActualParams {} {}", m, params);
List<String> names = getParametersNames(m);
Object[] actualParams = new Object[names.size()];
boolean isVariableParameters =
m.getParameterCo... | @Test
void calculateActualParams() throws NoSuchMethodException {
// CeilingFunction.invoke(@ParameterName( "n" ) BigDecimal n)
Method m = CeilingFunction.class.getMethod("invoke", BigDecimal.class);
assertNotNull(m);
NamedParameter[] parameters = {new NamedParameter("n", BigDecimal.... |
public Response put(URL url, Request request) throws IOException {
return call(HttpMethods.PUT, url, request);
} | @Test
public void testPut() throws IOException {
verifyCall(HttpMethods.PUT, FailoverHttpClient::put);
} |
public static Schema convert(final org.apache.iceberg.Schema schema) {
ImmutableList.Builder<Field> fields = ImmutableList.builder();
for (NestedField f : schema.columns()) {
fields.add(convert(f));
}
return new Schema(fields.build());
} | @Test
public void convertPrimitive() {
Schema iceberg =
new Schema(
Types.NestedField.optional(0, INTEGER_FIELD, IntegerType.get()),
Types.NestedField.optional(1, BOOLEAN_FIELD, BooleanType.get()),
Types.NestedField.required(2, DOUBLE_FIELD, DoubleType.get()),
... |
@JsonIgnore
public ValidationResult validate() {
final ValidationResult validation = new ValidationResult();
if (title().isEmpty()) {
validation.addError(FIELD_TITLE, "Notification title cannot be empty.");
}
try {
validation.addAll(config().validate());
... | @Test
public void testValidEmailNotification() {
final NotificationDto validNotification = getEmailNotification();
final ValidationResult validationResult = validNotification.validate();
assertThat(validationResult.failed()).isFalse();
assertThat(validationResult.getErrors()).isEmpt... |
public static NamenodeRole convert(NamenodeRoleProto role) {
switch (role) {
case NAMENODE:
return NamenodeRole.NAMENODE;
case BACKUP:
return NamenodeRole.BACKUP;
case CHECKPOINT:
return NamenodeRole.CHECKPOINT;
}
return null;
} | @Test
public void testConvertDatanodeID() {
DatanodeID dn = DFSTestUtil.getLocalDatanodeID();
DatanodeIDProto dnProto = PBHelperClient.convert(dn);
DatanodeID dn2 = PBHelperClient.convert(dnProto);
compare(dn, dn2);
} |
@Override
public Set<Name> getLocations() {
if(StringUtils.isNotBlank(session.getHost().getRegion())) {
final S3Region region = new S3Region(session.getHost().getRegion());
if(log.isDebugEnabled()) {
log.debug(String.format("Return single region %s set in bookmark", r... | @Test
public void testEmptyThirdPartyProvider() {
final Host host = new Host(new S3Protocol(), "mys3");
final S3Session session = new S3Session(host);
assertTrue(new S3LocationFeature(session).getLocations().isEmpty());
} |
public BlobOperationResponse listBlobs(final Exchange exchange) {
final ListBlobsOptions listBlobOptions = configurationProxy.getListBlobOptions(exchange);
final Duration timeout = configurationProxy.getTimeout(exchange);
final String regex = configurationProxy.getRegex(exchange);
List<B... | @Test
void testListBlob() {
when(client.listBlobs(any(), any())).thenReturn(listBlobsMock());
final BlobContainerOperations blobContainerOperations = new BlobContainerOperations(configuration, client);
final BlobOperationResponse response = blobContainerOperations.listBlobs(null);
... |
@GET
@Produces({MediaType.APPLICATION_JSON})
public Map<String, Object> requestFormats() {
return SUPPORTED_FORMATS;
} | @Test
public void testFormats() {
assertEquals(1, server.requestFormats().size());
assertEquals( ((List)server.requestFormats().get("responseTypes")).get(0), "application/json");
} |
@VisibleForTesting
long customShuffleTransfer(WritableByteChannel target, long position)
throws IOException {
long actualCount = this.count - position;
if (actualCount < 0 || position < 0) {
throw new IllegalArgumentException(
"position out of range: " + position +
... | @Test(timeout = 100000)
public void testCustomShuffleTransfer() throws IOException {
File absLogDir = new File("target",
TestFadvisedFileRegion.class.getSimpleName() +
"LocDir").getAbsoluteFile();
String testDirPath =
StringUtils.join(Path.SEPARATOR,
new String[] { a... |
public <T extends ShardingSphereRule> T getSingleRule(final Class<T> clazz) {
Collection<T> foundRules = findRules(clazz);
Preconditions.checkState(1 == foundRules.size(), "Rule `%s` should have and only have one instance.", clazz.getSimpleName());
return foundRules.iterator().next();
} | @Test
void assertGetSingleRule() {
assertThat(ruleMetaData.getSingleRule(ShardingSphereRuleFixture.class), instanceOf(ShardingSphereRuleFixture.class));
} |
@Override
protected void doStop() throws Exception {
shutdownReconnectService(reconnectService);
LOG.debug("Disconnecting from: {}...", getEndpoint().getConnectionString());
super.doStop();
closeSession();
LOG.info("Disconnected from: {}", getEndpoint().getConnectionString... | @Test
public void doStopShouldNotCloseTheSMPPSessionIfItIsNull() throws Exception {
when(endpoint.getConnectionString())
.thenReturn("smpp://smppclient@localhost:2775");
consumer.doStop();
} |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_SINT32_BE() {
final MutableData data = new MutableData(new byte[4]);
data.setValue(0x00fdfdfe, Data.FORMAT_UINT32_BE, 0);
assertArrayEquals(new byte[] { (byte) 0x00, (byte) 0xFD, (byte) 0xFD, (byte) 0xFE } , data.getValue());
} |
@Override
public void execute(Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void execute_whenNoBaseMeasure_shouldNotRaiseEvent() {
when(measureRepository.getBaseMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.empty());
underTest.execute(new TestComputationStepContext());
verifyNoMoreInteractions(eventRepository);
} |
public static int MAXIM(@NonNull final byte[] data, final int offset, final int length) {
return CRC(0x8005, 0x0000, data, offset, length, true, true, 0xFFFF);
} | @Test
public void MAXIM_empty() {
final byte[] data = new byte[0];
assertEquals(0xFFFF, CRC16.MAXIM(data, 0, 0));
} |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testValidationSkippedWhenCmdLineSwitchIsDefined()
throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
new FSConfigToCSConfigArgumentHandler(conversionOptions,
mockValidator);
String[] args = getArgumentsAs... |
public PrefetchableIterable<V> get(K key) {
checkState(
!isClosed,
"Multimap user state is no longer usable because it is closed for %s",
keysStateRequest.getStateKey());
Object structuralKey = mapKeyCoder.structuralValue(key);
KV<K, List<V>> pendingAddValues = pendingAdds.get(struc... | @Test
public void testImmutableValues() throws Exception {
FakeBeamFnStateClient fakeClient =
new FakeBeamFnStateClient(
ImmutableMap.of(
createMultimapKeyStateKey(),
KV.of(ByteArrayCoder.of(), singletonList(A1)),
createMultimapValueStateKey(A1),... |
public Result parse(final String string) throws DateNotParsableException {
return this.parse(string, new Date());
} | @Test
public void testDefaultTZ() throws Exception {
NaturalDateParser.Result today = naturalDateParser.parse("today");
assertThat(today.getFrom()).as("From should not be null").isNotNull();
assertThat(today.getTo()).as("To should not be null").isNotNull();
assertThat(today.getDateTi... |
public ServiceInfo processServiceInfo(String json) {
ServiceInfo serviceInfo = JacksonUtils.toObj(json, ServiceInfo.class);
serviceInfo.setJsonFromServer(json);
return processServiceInfo(serviceInfo);
} | @Test
void testProcessServiceInfo() {
ServiceInfo info = new ServiceInfo("a@@b@@c");
Instance instance1 = createInstance("1.1.1.1", 1);
Instance instance2 = createInstance("1.1.1.2", 2);
List<Instance> hosts = new ArrayList<>();
hosts.add(instance1);
hosts.add(instanc... |
public void createNamespace(Namespace namespace, Map<String, String> metadata) {
checkNamespaceIsValid(namespace);
getRef().checkMutable();
ContentKey key = ContentKey.of(namespace.levels());
org.projectnessie.model.Namespace content =
org.projectnessie.model.Namespace.of(key.getElements(), meta... | @Test
public void testCreateNamespaceInvalid() throws NessieConflictException, NessieNotFoundException {
String branch = "createNamespaceInvalidBranch";
createBranch(branch);
NessieIcebergClient client = new NessieIcebergClient(api, branch, null, Map.of());
assertThatThrownBy(() -> client.createNames... |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_rerun_file_and_remove_existing_tag_filters() throws IOException {
RuntimeOptions existing = RuntimeOptions.defaultOptions();
existing.setTagExpressions(Collections.singletonList(TagExpressionParser.parse("@example")));
Path path = mockFileResource("classpath:path/to.f... |
public String validate(final String xml) {
final Source source = new SAXSource(reader, new InputSource(IOUtils.toInputStream(xml, Charset.defaultCharset())));
return validate(source);
} | @Test
public void testValidXML() throws Exception {
String payload = IOUtils.toString(ClassLoader.getSystemResourceAsStream("xml/article-1.xml"),
Charset.defaultCharset());
logger.info("Validating payload: {}", payload);
// validate
String result = getProcessor("sch... |
@Override
protected OutputStream createObject(String key) throws IOException {
return new GCSOutputStream(mBucketName, key, mClient,
mUfsConf.getList(PropertyKey.TMP_DIRS));
} | @Test
public void testCreateObject() throws IOException, ServiceException {
// test successful create object
Mockito.when(mClient.putObject(ArgumentMatchers.anyString(),
ArgumentMatchers.any(GSObject.class))).thenReturn(null);
OutputStream result = mGCSUnderFileSystem.createObject(KEY);
Assert... |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testValidator420() {
UrlValidator validator = new UrlValidator();
assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue"));
assertTrue(validator.isValid("http://example.com/serach?address=Main%20Avenue"));
assertTrue(validator.isValid("http://examp... |
public Path getSegmentsDirectory(final Path file) {
return new Path(file.getParent(), String.format("%s%s", prefix, file.getName()), EnumSet.of(Path.Type.directory));
} | @Test
public void testGetSegmentsDirectory() {
final SwiftSegmentService service = new SwiftSegmentService(session, ".prefix/");
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
final String name = UUID.randomUUID().toString();
... |
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(
RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString())
.trim();
if (ConfigUtils.isEmpty(value)) {
... | @Test
void testMockInvokerFromOverride_Invoke_check_int() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
... |
public static Optional<String> maybeCreateProcessingLogTopic(
final KafkaTopicClient topicClient,
final ProcessingLogConfig config,
final KsqlConfig ksqlConfig) {
if (!config.getBoolean(ProcessingLogConfig.TOPIC_AUTO_CREATE)) {
return Optional.empty();
}
final String topicName = getT... | @Test
public void shouldNotCreateLogTopicIfNotConfigured() {
// Given:
final ProcessingLogConfig config = new ProcessingLogConfig(
ImmutableMap.of(ProcessingLogConfig.TOPIC_AUTO_CREATE, false)
);
// When:
final Optional<String> createdTopic = ProcessingLogServerUtils.maybeCreateProcessing... |
public static Duration parseDuration(String text) {
checkNotNull(text);
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while ... | @Test
void testParseDurationNanos() {
assertThat(TimeUtils.parseDuration("424562ns").getNano()).isEqualTo(424562);
assertThat(TimeUtils.parseDuration("424562nano").getNano()).isEqualTo(424562);
assertThat(TimeUtils.parseDuration("424562nanos").getNano()).isEqualTo(424562);
assertThat... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testCursorStrategyCutIfBeginAndEndIndexAreDisabled() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.cursorStrategy(CUT)
.sourceField("msg")
.callback(new Callable<Result[]>() {
@Override
... |
@GwtIncompatible("java.util.regex.Pattern")
public void containsMatch(@Nullable Pattern regex) {
checkNotNull(regex);
if (actual == null) {
failWithActual("expected a string that contains a match for", regex);
} else if (!regex.matcher(actual).find()) {
failWithActual("expected to contain a ma... | @Test
@GwtIncompatible("Pattern")
public void stringContainsMatchStringUsesFind() {
assertThat("aba").containsMatch("[b]");
assertThat("aba").containsMatch(Pattern.compile("[b]"));
} |
public short toShort() {
int s = (mOwnerBits.ordinal() << 6) | (mGroupBits.ordinal() << 3) | mOtherBits.ordinal();
return (short) s;
} | @Test
public void toShort() {
Mode mode = new Mode(Mode.Bits.ALL, Mode.Bits.READ_EXECUTE, Mode.Bits.READ_EXECUTE);
assertEquals(0755, mode.toShort());
mode = Mode.defaults();
assertEquals(0777, mode.toShort());
mode = new Mode(Mode.Bits.READ_WRITE, Mode.Bits.READ, Mode.Bits.READ);
assertEqua... |
public static Optional<String> maybeCreateProcessingLogTopic(
final KafkaTopicClient topicClient,
final ProcessingLogConfig config,
final KsqlConfig ksqlConfig) {
if (!config.getBoolean(ProcessingLogConfig.TOPIC_AUTO_CREATE)) {
return Optional.empty();
}
final String topicName = getT... | @Test
public void shouldThrowOnUnexpectedKafkaClientError() {
// Given:
doThrow(new RuntimeException("bad"))
.when(mockTopicClient)
.createTopic(anyString(), anyInt(), anyShort());
// When:
final Exception e = assertThrows(
RuntimeException.class,
() -> ProcessingLogSe... |
public static ProxyBackendHandler newInstance(final DatabaseType databaseType, final String sql, final SQLStatement sqlStatement,
final ConnectionSession connectionSession, final HintValueContext hintValueContext) throws SQLException {
if (sqlStatement instanceo... | @Test
void assertNewInstanceWithQueryableRALStatementInTransaction() throws SQLException {
when(connectionSession.getTransactionStatus().isInTransaction()).thenReturn(true);
String sql = "SHOW TRANSACTION RULE;";
SQLStatement sqlStatement = ProxySQLComQueryParser.parse(sql, databaseType, con... |
public static TriggerStateMachine stateMachineForTrigger(RunnerApi.Trigger trigger) {
switch (trigger.getTriggerCase()) {
case AFTER_ALL:
return AfterAllStateMachine.of(
stateMachinesForTriggers(trigger.getAfterAll().getSubtriggersList()));
case AFTER_ANY:
return AfterFirstSt... | @Test
public void testOrFinallyTranslation() {
RunnerApi.Trigger trigger =
RunnerApi.Trigger.newBuilder()
.setOrFinally(
RunnerApi.Trigger.OrFinally.newBuilder()
.setMain(subtrigger1)
.setFinally(subtrigger2))
.build();
Or... |
@Override
public HttpResponse sendAsIs(HttpRequest httpRequest) throws IOException {
HttpURLConnection connection = connectionFactory.openConnection(httpRequest.url());
connection.setRequestMethod(httpRequest.method().toString());
httpRequest.headers().names().stream()
.filter(headerName -> !Ascii... | @Test
public void sendAsIs_always_returnsExpectedHttpResponse()
throws IOException, InterruptedException {
mockWebServer.setDispatcher(new SendAsIsTestDispatcher());
mockWebServer.start();
String expectedResponseBody = SendAsIsTestDispatcher.buildBody("GET", "");
HttpUrl baseUrl = mockWebServer... |
@Override
public <T> UncommittedBundle<T> createRootBundle() {
// The DirectRunner is responsible for these elements, but they need not be encodable.
return underlying.createRootBundle();
} | @Test
public void rootBundleSucceedsIgnoresCoder() {
WindowedValue<Record> one = WindowedValue.valueInGlobalWindow(new Record());
WindowedValue<Record> two = WindowedValue.valueInGlobalWindow(new Record());
CommittedBundle<Record> root =
factory.<Record>createRootBundle().add(one).add(two).commit(... |
@Override
public PipelineProcessConfiguration swapToObject(final YamlPipelineProcessConfiguration yamlConfig) {
return null == yamlConfig
? null
: new PipelineProcessConfiguration(
readConfigSwapper.swapToObject(yamlConfig.getRead()), writeConfigSwappe... | @Test
void assertSwapToObjectWithNull() {
assertNull(new YamlPipelineProcessConfigurationSwapper().swapToObject(null));
} |
public static StructType convert(Schema schema) {
return (StructType) TypeUtil.visit(schema, new TypeToSparkType());
} | @Test
public void testSchemaConversionWithMetaDataColumnSchema() {
StructType structType = SparkSchemaUtil.convert(TEST_SCHEMA_WITH_METADATA_COLS);
List<AttributeReference> attrRefs =
scala.collection.JavaConverters.seqAsJavaList(structType.toAttributes());
for (AttributeReference attrRef : attrRe... |
public HttpMethod method() {
return this.httpMethod;
} | @Test
public void methodTest() {
ShenyuRequest.HttpMethod httpMethod = retryableException.method();
Assert.assertNotNull(httpMethod);
} |
public static boolean isUnclosedQuote(final String line) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
int quoteStart = -1;
for (int i = 0; i < line.length(); ++i) {
if (quoteStart < 0 && isQuoteChar(line, i)) {
quoteStart = i;
} else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !... | @Test
public void shouldNotFindUnclosedQuote_twoQuote() {
// Given:
final String line = "some line 'this is in a quote'''";
// Then:
assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.