focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the number of milliseconds since 1970-01-01 00:00:00 UTC/GMT."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'."
+ " The system default time... | @Test
public void shouldThrowIfParseFails() {
// When:
final KsqlFunctionException e = assertThrows(
KsqlFunctionException.class,
() -> udf.stringToTimestamp("invalid", "yyyy-MM-dd'T'HH:mm:ss.SSS")
);
// Then:
assertThat(e.getMessage(), containsString("Text 'invalid' could not be ... |
@Override public Date getScheduledDate() {
return new Date();
} | @Test
public void shouldNotReturnNullForScheduledDate() {
PipelineInstanceModel pipeline = PipelineInstanceModel.createPreparingToSchedule("pipeline-name", new StageInstanceModels());
assertThat(pipeline.getScheduledDate(), is(not(nullValue())));
} |
@Override
public Long del(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key: keys) {
write(key, LongCodec.INSTANCE, RedisCommands.DEL, key);
}
return null;
}
CommandBatchService es = new CommandBatchService(executorSe... | @Test
public void testDel() {
List<byte[]> keys = new ArrayList<>();
for (int i = 0; i < 10; i++) {
byte[] key = ("test" + i).getBytes();
keys.add(key);
connection.set(key, ("test" + i).getBytes());
}
assertThat(connection.del(keys.toArray(new byte... |
public QueueConnection queueConnection(QueueConnection connection) {
// It is common to implement both interfaces
if (connection instanceof XAQueueConnection) {
return xaQueueConnection((XAQueueConnection) connection);
}
return TracingConnection.create(connection, this);
} | @Test void queueConnection_doesntDoubleWrap() {
QueueConnection wrapped = jmsTracing.queueConnection(mock(QueueConnection.class));
assertThat(jmsTracing.queueConnection(wrapped))
.isSameAs(wrapped);
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testUnnestInnerScalarAlias()
{
analyze("SELECT * FROM (SELECT array[1,2] a) a CROSS JOIN UNNEST(a) AS T(x)");
} |
@Override
public ExecuteContext doBefore(ExecuteContext context) {
LogUtils.printHttpRequestBeforePoint(context);
final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class);
HttpHost httpHost = (HttpHost) context.getArguments()[0];
final HttpReq... | @Test
public void doBefore() throws Exception {
final HttpClient4xInterceptor interceptor = new HttpClient4xInterceptor();
interceptor.ready();
final ExecuteContext context = buildContext();
PlugEffectStrategyCache.INSTANCE.resolve(DynamicConfigEventType.CREATE, "");
intercep... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testNotFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
int[] expectedHistorySnapshot = {1, 2};
testHistory(history, expectedHistorySnapshot);
} |
public static Iterable<String> expandAtNFilepattern(String filepattern) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
Matcher match = AT_N_SPEC.matcher(filepattern);
if (!match.find()) {
builder.add(filepattern);
} else {
int numShards = Integer.parseInt(match.group("N")... | @Test
public void testExpandAtNFilepatternTwoPatterns() throws Exception {
exception.expect(IllegalArgumentException.class);
exception.expectMessage(
"More than one @N wildcard found in filepattern: gs://bucket/object@10.@20.ism");
Filepatterns.expandAtNFilepattern("gs://bucket/object@10.@20.ism")... |
public EnumSet<RepositoryFilePermission> processCheckboxes() {
return processCheckboxes( false );
} | @Test
public void testProcessCheckboxesReadCheckedEnableAppropriateFalse() {
when( readCheckbox.isChecked() ).thenReturn( true );
when( writeCheckbox.isChecked() ).thenReturn( false );
when( deleteCheckbox.isChecked() ).thenReturn( false );
when( manageCheckbox.isChecked() ).thenReturn( false );
a... |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
final Optional<ValueRange> valueRange = getValueRangeBody(message);
String range = message.getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A:A").toString();
String majorDimension = message
... | @Test
public void testTransformToValueRangeWithJsonObject() throws Exception {
Exchange inbound = new DefaultExchange(camelContext);
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A1:B2");
String body = "{\"spreadsheetId\": \"" + spreadsheetId + "\", \"A\":... |
public SCM find(final String scmId) {
return stream().filter(scm -> scm.getId().equals(scmId)).findFirst().orElse(null);
} | @Test
void shouldReturnNullIfNoMatchingSCMFound() {
assertThat(new SCMs().find("not-found")).isNull();
} |
@Override
public void validate(final String methodName, final Class<?>[] parameterTypes, final Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (Objects.nonNull(methodClass)) {
groups.add(methodCl... | @Test
public void testValidateWhenMeetsConstraintThenValidationFailed() throws Exception {
assertThrows(ValidationException.class, () -> apacheDubboClientValidatorUnderTest
.validate(
"methodTwo",
new Class<?>[]{MockValidationParameter.class},
... |
public MessageType convert(Class<? extends TBase<?, ?>> thriftClass) {
return convert(toStructType(thriftClass));
} | @Test
public void testToMessageType() throws Exception {
String expected = "message ParquetSchema {\n" + " optional group persons (LIST) = 1 {\n"
+ " repeated group persons_tuple {\n"
+ " required group name = 1 {\n"
+ " optional binary first_name (UTF8) = 1;\n"
+ "... |
@Udf
public final <T> T nullIf(
@UdfParameter(description = "expression 1") final T expr1,
@UdfParameter(description = "expression 2") final T expr2
) {
if (expr1 == null) {
return null;
}
if (expr1.equals(expr2)) {
return null;
} else {
return expr1;
}
} | @Test
public void shouldReturnNullIfBothValuesAreNulls() {
assertThat(udf.nullIf(null, null), is(nullValue()));
} |
static KiePMMLTextIndex getKiePMMLTextIndex(final TextIndex textIndex) {
final LOCAL_TERM_WEIGHTS localTermWeights = textIndex.getLocalTermWeights() != null ?
LOCAL_TERM_WEIGHTS.byName(textIndex.getLocalTermWeights().value()) : null;
final COUNT_HITS countHits = textIndex.getCountHits() ... | @Test
void getKiePMMLTextIndex() {
final TextIndex toConvert = getRandomTextIndex();
final KiePMMLTextIndex retrieved = KiePMMLTextIndexInstanceFactory.getKiePMMLTextIndex(toConvert);
commonVerifyKiePMMLTextIndex(retrieved, toConvert);
} |
public static Map<String, String> parseToMap(String attributesModification) {
if (Strings.isNullOrEmpty(attributesModification)) {
return new HashMap<>();
}
// format: +key1=value1,+key2=value2,-key3,+key4=value4
Map<String, String> attributes = new HashMap<>();
Stri... | @Test
public void parseToMap_NullString_ReturnsEmptyMap() {
String attributesModification = null;
Map<String, String> result = AttributeParser.parseToMap(attributesModification);
assertTrue(result.isEmpty());
} |
@Override
public WindowStoreIterator<V> backwardFetch(final K key,
final Instant timeFrom,
final Instant timeTo) throws IllegalArgumentException {
Objects.requireNonNull(key, "key can't be null");
final L... | @Test
public void shouldBackwardFetchKeyRangeAcrossStoresWithNullKeyFromKeyTo() {
final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE);
stubProviderTwo.addStore(storeName, secondUnderlying);
underlyingWindowStore.put("a", "a", 0L);
... |
public static Schema schemaFromJavaBeanClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testNestedBean() {
Schema schema =
JavaBeanUtils.schemaFromJavaBeanClass(
new TypeDescriptor<NestedBean>() {}, GetterTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(NESTED_BEAN_SCHEMA, schema);
} |
@ScalarFunction
public static boolean isJson(String inputStr) {
try {
JsonUtils.stringToJsonNode(inputStr);
return true;
} catch (Exception e) {
return false;
}
} | @Test(dataProvider = "isJson")
public void testIsJson(String input, boolean expectedValue) {
assertEquals(StringFunctions.isJson(input), expectedValue);
} |
@Override
public ObjectNode encode(KubevirtLoadBalancer lb, CodecContext context) {
checkNotNull(lb, "Kubevirt load balancer cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(NAME, lb.name())
.put(VIP, lb.vip().toString())
... | @Test
public void testKubevirtLoadBalancerEncode() {
KubevirtLoadBalancer lb = DefaultKubevirtLoadBalancer.builder()
.name("lb-1")
.networkId("net-1")
.vip(IpAddress.valueOf("10.10.10.10"))
.members(ImmutableSet.of(IpAddress.valueOf("10.10.10.1... |
public static String extractMinionInstanceTag(TableConfig tableConfig, String taskType) {
TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
if (tableTaskConfig != null) {
Map<String, String> configs = tableTaskConfig.getConfigsForTaskType(taskType);
if (configs != null && !configs.isEmp... | @Test
public void testExtractMinionInstanceTag() {
// correct minionInstanceTag extraction
Map<String, String> tableTaskConfigs = getDummyTaskConfig();
tableTaskConfigs.put(PinotTaskManager.MINION_INSTANCE_TAG_CONFIG, "minionInstance1");
TableTaskConfig tableTaskConfig =
new TableTaskConfig(Co... |
@VisibleForTesting
AmazonS3 getAmazonS3Client() {
return this.amazonS3.get();
} | @Test
public void testGetPathStyleAccessEnabled() throws URISyntaxException {
S3FileSystem s3FileSystem =
new S3FileSystem(s3ConfigWithCustomEndpointAndPathStyleAccessEnabled("s3"));
URL s3Url = s3FileSystem.getAmazonS3Client().getUrl("bucket", "file");
assertEquals("https://s3.custom.dns/bucket/f... |
public static String rc2name( int row, int col ){
StringBuilder sb = new StringBuilder();
int b = 26;
int p = 1;
if( col >= b ){
col -= b;
p *= b;
}
if( col >= b*b ){
col -= b*b;
p *= b;
}
while( p > 0 ){
... | @Test
public void testRowColumnToCellNAme() {
assertThat(rc2name(0, 0)).isEqualTo("A1");
assertThat(rc2name(0, 10)).isEqualTo("K1");
assertThat(rc2name(0, 42)).isEqualTo("AQ1");
assertThat(rc2name(9, 27)).isEqualTo("AB10");
assertThat(rc2name(99, 53)).isEqualTo("BB100");
... |
@SuppressWarnings("unchecked")
public static <T, S extends T> Optional<S> downcast(T obj, Class<S> klass) {
Preconditions.checkArgument(obj != null);
if (obj.getClass().equals(Objects.requireNonNull(klass))) {
return Optional.of((S) obj);
} else {
return Optional.empt... | @Test
public void testDowncast() {
Number a = Integer.valueOf(10);
Assert.assertTrue(Util.downcast(a, Integer.class).isPresent());
Assert.assertFalse(Util.downcast(a, String.class).isPresent());
} |
@Override
public Object getObject(final int columnIndex) throws SQLException {
return mergeResultSet.getValue(columnIndex, Object.class);
} | @Test
void assertGetObjectWithString() throws SQLException {
String result = "foo";
when(mergeResultSet.getValue(1, String.class)).thenReturn(result);
assertThat(shardingSphereResultSet.getObject(1, String.class), is(result));
} |
@Override
public void modifyPath(Function<String, String> pathModifier) {
request.setHttpURI(HttpURI.build(request.getHttpURI()).path(pathModifier.apply(request.getHttpURI().getPath())).asImmutable());
} | @Test
public void shouldAlterRequestUriOnRequest() {
when(request.getHttpURI()).thenReturn(HttpURI.from("foo/bar/baz?a=b&c=d"));
jettyRequest.modifyPath(path -> path.replaceAll("^foo/bar/baz", "foo/junk"));
verify(request).setHttpURI(capturedUri.capture());
assertThat(capturedUri.ge... |
public JetSqlRow project(Object object) {
target.setTarget(object, null);
return ExpressionUtil.projection(predicate, projection, this, evalContext);
} | @Test
public void test_project() {
RowProjector projector = new RowProjector(
new String[]{"target"},
new QueryDataType[]{INT},
new IdentityTarget(),
null,
singletonList(
MultiplyFunction.create(ColumnExp... |
static void populateCorrectMiningModel(final MiningModel miningModel) {
final List<Segment> segments = miningModel.getSegmentation().getSegments();
for (int i = 0; i < segments.size(); i++) {
Segment segment = segments.get(i);
populateCorrectSegmentId(segment, miningModel.getMode... | @Test
void populateCorrectMiningModel() throws Exception {
final InputStream inputStream = getFileInputStream(NO_MODELNAME_NO_SEGMENT_ID_NOSEGMENT_TARGET_FIELD_SAMPLE);
final PMML pmml = org.jpmml.model.PMMLUtil.unmarshal(inputStream);
final Model retrieved = pmml.getModels().get(0);
... |
public double d(int[] x, int[] y) {
if (x.length != y.length)
throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length));
double dist = 0.0;
if (weight == null) {
for (int i = 0; i < x.length; i++) {
... | @Test
public void testDistanceInt() {
System.out.println("distance");
int[] x = {1, 2, 3, 4};
int[] y = {4, 3, 2, 1};
assertEquals(8, new ManhattanDistance().d(x, y), 1E-6);
} |
public String getServiceUUID(Connection connection, String serviceEntityId, int consumingServiceIdx) {
if (connection == null || serviceEntityId == null)
return null;
EntityDescriptor serviceEntityDescriptor = resolveEntityDescriptorFromMetadata(connection, serviceEntityId);
if (se... | @Test
void metadataResponseMapperMapsSuccessResponseTest() {
String samlData = "samlData";
Connection connection = newConnection(SAML_COMBICONNECT, true, true, true);
Service service = newService(true);
String requestStatus = "OK";
SamlMetadataResponse metadataResponse = sam... |
public DataPoint addDataPoint(Object label) {
DataPoint dp = new DataPoint();
labels.add(label);
dataPoints.add(dp);
return dp;
} | @Test
public void testAddDataPoint() {
cm = new ChartModel(FOO, BAR, ZOO);
long time = System.currentTimeMillis();
cm.addDataPoint(time)
.data(FOO, VALUES1[0])
.data(BAR, VALUES2[0])
.data(ZOO, VALUES3[0]);
cm.addDataPoint(time + 1)
... |
@Override
public void lock() {
try {
lockInterruptibly(-1, null);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
} | @Test
public void testIsHeldByCurrentThreadOtherThread() throws InterruptedException {
RLock lock = redisson.getSpinLock("lock");
lock.lock();
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getSpinLock("lock");
Assertions.asse... |
@Override
public void start() throws BundleException {
throw newException();
} | @Test
void require_that_start_throws_exception() throws BundleException {
assertThrows(RuntimeException.class, () -> {
new DisableOsgiFramework().start();
});
} |
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) {
Objects.requireNonNull(metric);
if (batchMeasure == null) {
return Optional.empty();
}
Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder();
switch (metric.getType().getValueType()) {
... | @Test
public void toMeasure_throws_NPE_if_both_arguments_are_null() {
assertThatThrownBy(() -> underTest.toMeasure(null, null))
.isInstanceOf(NullPointerException.class);
} |
public static int intClamp(int value, int min, int max) {
if (value > max)
return max;
if (value < min)
return min;
return value;
} | @Test
void testIntClamp() {
assertEquals(5, NumberUtil.intClamp(100, 0, 5));
assertEquals(5, NumberUtil.intClamp(-25, 5, 10));
assertEquals(5, NumberUtil.intClamp(5, 0, 10));
} |
@Override
public String getAlertFilter() {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();
chec... | @Test
public void testGetAlertFilter() throws Exception {
voltConfig.getAlertFilter();
} |
@Nullable
public Integer getIntValue(@IntFormat final int formatType,
@IntRange(from = 0) final int offset) {
if ((offset + getTypeLen(formatType)) > size()) return null;
return switch (formatType) {
case FORMAT_UINT8 -> unsignedByteToInt(mValue[offset]);
case FORMAT_UINT16_LE -> unsignedBytesToIn... | @Test
public void getValue_UINT24() {
final Data data = new Data(new byte[] { 0x03, 0x02, 0x01 });
final int value = data.getIntValue(Data.FORMAT_UINT24_LE, 0);
assertEquals(0x010203, value);
} |
@Override
public String dumpSchedulerLogs(String time, HttpServletRequest hsr)
throws IOException {
// Step1. We will check the time parameter to
// ensure that the time parameter is not empty and greater than 0.
if (StringUtils.isBlank(time)) {
routerMetrics.incrDumpSchedulerLogsFailedRetri... | @Test
public void testDumpSchedulerLogs() throws Exception {
HttpServletRequest mockHsr = mockHttpServletRequestByUserName("admin");
String dumpSchedulerLogsMsg = interceptor.dumpSchedulerLogs("1", mockHsr);
// We cannot guarantee the calling order of the sub-clusters,
// We guarantee that the return... |
public static <T> List<List<T>> split(List<T> list, int size) {
return partition(list, size);
} | @Test
public void splitTest() {
List<List<Object>> lists = ListUtil.split(null, 3);
assertEquals(ListUtil.empty(), lists);
lists = ListUtil.split(Arrays.asList(1, 2, 3, 4), 1);
assertEquals("[[1], [2], [3], [4]]", lists.toString());
lists = ListUtil.split(Arrays.asList(1, 2, 3, 4), 2);
assertEquals("[[1, ... |
public static Write write() {
return new Write(null /* Configuration */, "");
} | @Test
public void testWriting() throws Exception {
final String table = tmpTable.getName();
final String key = "key";
final String value = "value";
final int numMutations = 100;
createTable(table);
p.apply("multiple rows", Create.of(makeMutations(key, value, numMutations)))
.apply("w... |
@VisibleForTesting
static List<Tuple2<ConfigGroup, String>> generateTablesForClass(
Class<?> optionsClass, Collection<OptionWithMetaInfo> optionWithMetaInfos) {
ConfigGroups configGroups = optionsClass.getAnnotation(ConfigGroups.class);
List<OptionWithMetaInfo> allOptions = selectOptions... | @Test
void testConfigGroupWithEnumConstantExclusion() {
final String expectedTable =
"<table class=\"configuration table table-bordered\">\n"
+ " <thead>\n"
+ " <tr>\n"
+ " <th class=\"text-left\" st... |
@Override
public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final S3Object object = new S3WriteFeature(session, acl).getDetails(file, status);
// ID for the initiated multipart upload.
... | @Test
public void testWriteVirtualHost() throws Exception {
final S3AccessControlListFeature acl = new S3AccessControlListFeature(virtualhost);
final S3MultipartWriteFeature feature = new S3MultipartWriteFeature(virtualhost, acl);
final TransferStatus status = new TransferStatus();
s... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if(directory.isRoot()) {
final String bucket = RequestEntityRestStorageService.findBucketInHostname(session.getHost());
if(StringUtils.isEmpty(bucket)) {... | @Test
public void testListMultipartUploadDot() throws Exception {
final Path bucket = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path placeholder = new S3Dir... |
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) {
final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace();
final String importerDMNName = ((Definitions) importElement.getParent()).getName(... | @Test
void nSonly() {
final Import i = makeImport("ns1", null, null);
final List<QName> available = Arrays.asList(new QName("ns1", "m1"),
new QName("ns2", "m2"),
new QName("ns3", "m3"));
f... |
public static byte[] createByteArray( int size ) {
return new byte[size];
} | @Test
public void testCreateByteArray() {
assertTrue( Const.createByteArray( 5 ).length == 5 );
} |
public double calculateAveragePercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) {
int skippedResourceTypes = 0;
double total = 0.0;
if (usedMemoryMb > totalMemoryMb) {
throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb);
}... | @Test
public void testCalculateAvgWithOnlyCpu() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 2)));
NormalizedResources usedResources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_R... |
public Filter parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) {
if (!filterExpression.contains(FIELD_AND_VALUE_SEPARATOR)) {
throw new IllegalArgumentException(WRONG_FILTER_EXPR_FORMAT_ERROR_MSG);
}
final String[] split = filterExpression.... | @Test
void parsesFilterExpressionCorrectlyForIntRanges() {
final List<EntityAttribute> entityAttributes = List.of(EntityAttribute.builder()
.id("number")
.title("Number")
.type(SearchQueryField.Type.INT)
.filterable(true)
.build... |
public String keyToString(Object key) {
// This string should be in the format of:
// "<TYPE>:<KEY>" for internally supported types or "T:<KEY_CLASS>:<KEY>" for custom types
// e.g.:
// "S:my string key"
// "I:75"
// "D:5.34"
// "B:f"
// "T:com.myorg.MyType:STRI... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testKeyToStringWithDefaultTransformerForNonSerializableObject() {
NonSerializableKey key = new NonSerializableKey("test");
keyTransformationHandler.keyToString(key);
} |
public void dismiss() {
mDialogController.dismiss();
} | @Test
public void testDismiss() {
Application context = ApplicationProvider.getApplicationContext();
ShadowApplication shadowApplication = Shadows.shadowOf(context);
final AddOnStoreSearchController underTest = new AddOnStoreSearchController(context, "add on");
underTest.searchForAddOns();
Asser... |
@Override
public boolean test(final Path test) {
return this.equals(new DefaultPathPredicate(test));
} | @Test
public void testPredicateFileIdDirectory() {
final Path t = new Path("/f", EnumSet.of(Path.Type.directory), new PathAttributes().withFileId("1"));
assertTrue(new DefaultPathPredicate(t).test(t));
assertTrue(new DefaultPathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.directory)... |
String substituteParametersInSqlString(String sql, SqlParameterSource paramSource) {
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
List<SqlParameter> declaredParams = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
if (declaredParams.isEmpty()) {
... | @Test
public void substituteParametersInSqlString_DoubleLongType() {
double sum = 0.00000021d;
long price = 100000;
String sql = "Select * from Table Where sum = :sum AND price = :price";
String sqlToUse = "Select * from Table Where sum = 2.1E-7 AND price = 100000";
ctx.add... |
@Override
public V joinInternal() {
return resolve(super.joinInternal());
} | @Test
public void test_joinInternal() {
Object value = "value";
DeserializingCompletableFuture<Object> future = new DeserializingCompletableFuture<>(serializationService, deserialize);
future.complete(value);
assertEquals(value, future.joinInternal());
} |
@VisibleForTesting
static String parseHostMachine() {
String hostMachine = System.getProperty("host_machine");
return StringUtils.isNotEmpty(hostMachine) ? hostMachine : null;
} | @Test
public void parseHostMachine() {
String old = System.getProperty("host_machine");
try {
System.setProperty("host_machine", "xxx");
Assert.assertEquals("xxx", SystemInfo.parseHostMachine());
} finally {
if (old == null) {
System.clearP... |
@VisibleForTesting
List<ExecNode<?>> calculatePipelinedAncestors(ExecNode<?> node) {
List<ExecNode<?>> ret = new ArrayList<>();
AbstractExecNodeExactlyOnceVisitor ancestorVisitor =
new AbstractExecNodeExactlyOnceVisitor() {
@Override
protected ... | @Test
void testCalculatePipelinedAncestors() {
// P = InputProperty.DamBehavior.PIPELINED, E = InputProperty.DamBehavior.END_INPUT
//
// 0 ------P----> 1 -E--> 2
// \-----P----> 3 -P-/
// 4 -E-> 5 -P-/ /
// 6 -----E-----/
TestingBatchExecNode[] nodes = new T... |
public static String createFullName(Deque<String> fieldNames) {
String result = "";
if (!fieldNames.isEmpty()) {
Iterator<String> iter = fieldNames.descendingIterator();
result = iter.next();
if (!iter.hasNext()) {
return result;
}
StringBuilder sb = new StringBuilder();
... | @Test
void testCreateFullName() {
String result = HoodieAvroUtils.createFullName(new ArrayDeque<>(Arrays.asList("a", "b", "c")));
String resultSingle = HoodieAvroUtils.createFullName(new ArrayDeque<>(Collections.singletonList("a")));
assertEquals("c.b.a", result);
assertEquals("a", resultSingle);
} |
@Override
protected void doStart() throws Exception {
super.doStart();
listener = getListener();
connection.addIRCEventListener(listener);
LOG.debug("Sleeping for {} seconds before sending commands.", configuration.getCommandTimeout() / 1000);
// sleep for a few seconds as t... | @Test
public void doStartTest() throws Exception {
consumer.doStart();
verify(connection).addIRCEventListener(listener);
verify(endpoint).joinChannels();
} |
public List<ProductPagingSimpleResponse> findAllWithPagingByCategoryId(
final Long memberId,
final Long productId,
final Long categoryId,
final int pageSize
) {
QProduct product = QProduct.product;
QProductImage productImage = QProductImage.productImag... | @Test
void no_offset_페이징_첫_조회() {
// given
for (long i = 1L; i <= 20L; i++) {
productRepository.save(Product.builder()
.id(i)
.categoryId(1L)
.memberId(1L)
.description(new Description("title", "content", Loc... |
public static Optional<TableSchema> getUpdatedSchema(
TableSchema oldSchema, TableSchema newSchema) {
Result updatedFields = getUpdatedSchema(oldSchema.getFieldsList(), newSchema.getFieldsList());
if (updatedFields.isEquivalent()) {
return Optional.empty();
} else {
return updatedFields
... | @Test
public void testEquivalentSchema() {
TableSchema baseSchema1 =
TableSchema.newBuilder()
.addFields(
TableFieldSchema.newBuilder().setName("a").setType(TableFieldSchema.Type.STRING))
.addFields(
TableFieldSchema.newBuilder().setName("b").setType... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void noRetryOnConnectionClosed() {
HttpGet request = new HttpGet("/");
assertThat(retryStrategy.retryRequest(request, new ConnectionClosedException(), 1, null))
.isFalse();
} |
@Override
public ExecuteContext doBefore(ExecuteContext context) {
DatabaseInfo databaseInfo = getDataBaseInfo(context);
String database = databaseInfo.getDatabaseName();
Query query = (Query) context.getArguments()[0];
String sql = query.toString((ParameterList) context.getArguments... | @Test
public void testDoBefore() throws Exception {
// Database write prohibition switch turned off
GLOBAL_CONFIG.setEnablePostgreSqlWriteProhibition(false);
ExecuteContext context = ExecuteContext.forMemberMethod(queryExecutor, methodMock, argument, null, null);
queryExecutorImplInt... |
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("flags", flags)
.add("type", type)
.add("peerDistinguisher", Arrays.toString(peerDistinguisher))
.add("peerAddress", peerAddress.getHostAddress())
... | @Test
public void testToStringBmp() throws Exception {
BmpPeer bmpPeer = deserializer.deserialize(headerBytes, 0, headerBytes.length);
String str = bmpPeer.toString();
assertTrue(StringUtils.contains(str, "flags=" + flags));
assertTrue(StringUtils.contains(str, "type=" + type));
... |
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 assertNewInstanceWithEmptyString() throws SQLException {
String sql = "";
ProxyBackendHandler actual = ProxyBackendHandlerFactory.newInstance(databaseType, sql, new EmptyStatement(), connectionSession, new HintValueContext());
assertThat(actual, instanceOf(SkipBackendHandler.class... |
public MapConfig setMergePolicyConfig(MergePolicyConfig mergePolicyConfig) {
this.mergePolicyConfig = checkNotNull(mergePolicyConfig,
"mergePolicyConfig cannot be null!");
return this;
} | @Test
public void testSetMergePolicyConfig() {
MergePolicyConfig mergePolicyConfig = new MergePolicyConfig()
.setPolicy(PassThroughMergePolicy.class.getName())
.setBatchSize(2342);
MapConfig config = new MapConfig();
config.setMergePolicyConfig(mergePolicyCon... |
@Override
public boolean contains(Object o) {
if (o instanceof Uuid) {
Uuid topicId = (Uuid) o;
TopicImage topicImage = image.getTopic(topicId);
if (topicImage == null) return false;
return topicNames.contains(topicImage.name());
}
return false... | @Test
public void testContains() {
Uuid fooUuid = Uuid.randomUuid();
Uuid barUuid = Uuid.randomUuid();
Uuid bazUuid = Uuid.randomUuid();
Uuid quxUuid = Uuid.randomUuid();
TopicsImage topicsImage = new MetadataImageBuilder()
.addTopic(fooUuid, "foo", 3)
... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromEmpty_Array_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", InnerObject.emptyInner("inner"));
Getter parentGetter = GetterFactory.newFieldGetter(object, null, inn... |
@Override
public FinishedTriggersSet copy() {
return fromSet(Sets.newHashSet(finishedTriggers));
} | @Test
public void testCopy() throws Exception {
FinishedTriggersSet finishedSet = FinishedTriggersSet.fromSet(new HashSet<>());
assertThat(
finishedSet.copy().getFinishedTriggers(),
not(theInstance(finishedSet.getFinishedTriggers())));
} |
public static void main(String[] args) {
Converter<UserDto, User> userConverter = new UserConverter();
UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
User user = userConverter.convertFromDto(dtoUser);
LOGGER.info("Entity converted from DTO: {}", user);
var users = ... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
public PluginDescriptor find(Path pluginPath) {
Properties properties = readProperties(pluginPath);
return createPluginDescriptor(properties);
} | @Test
public void testFind() throws Exception {
PluginDescriptorFinder descriptorFinder = new PropertiesPluginDescriptorFinder();
PluginDescriptor plugin1 = descriptorFinder.find(pluginsPath.resolve("test-plugin-1"));
PluginDescriptor plugin2 = descriptorFinder.find(pluginsPath.resolve("tes... |
public static Status unblock(
final UnsafeBuffer logMetaDataBuffer,
final UnsafeBuffer termBuffer,
final int blockedOffset,
final int tailOffset,
final int termId)
{
Status status = NO_ACTION;
int frameLength = frameLengthVolatile(termBuffer, blockedOffset);
... | @Test
void shouldTakeNoActionToEndOfPartitionIfMessageNonCommittedAfterScan()
{
final int messageLength = HEADER_LENGTH * 4;
final int termOffset = TERM_BUFFER_CAPACITY - messageLength;
final int tailOffset = TERM_BUFFER_CAPACITY;
when(mockTermBuffer.getIntVolatile(termOffset))
... |
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 testNonReadinessOfPodCanPreventAllPodRestarts(VertxTestContext context) {
final String followerPodNonReady = "name-zookeeper-1";
final String leaderPodNeedsRestart = "name-zookeeper-2";
final String followerPodNeedsRestart = "name-zookeeper-0";
final Set<String> ne... |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test
@SuppressWarnings("deprecation")
public void testPagingContextParamType()
{
String testParamKey = "testParam";
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class);
PagingContext pagingContext = new PagingContext(RestConstants.DEFAULT_START, RestConstants... |
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersion.class) ||
resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersions.class)) {
checkVersion(... | @Test
public void testFilterWithInvalidVersion() throws Exception {
final Method resourceMethod = TestResourceWithMethodAnnotationRequiresES7.class.getMethod("methodWithAnnotation");
when(resourceInfo.getResourceMethod()).thenReturn(resourceMethod);
when(versionProvider.get()).thenReturn(el... |
@VisibleForTesting
protected static String getRefreshStatement(
ObjectIdentifier tableIdentifier,
String definitionQuery,
Map<String, String> partitionSpec,
Map<String, String> dynamicOptions) {
String tableIdentifierWithDynamicOptions =
genera... | @Test
void testGetManuallyRefreshStatement() {
ObjectIdentifier tableIdentifier =
ObjectIdentifier.of("catalog", "database", "my_materialized_table");
String query = "SELECT * FROM my_source_table";
assertThat(
MaterializedTableManager.getRefreshStatem... |
public void syncTimerCheckPoint() {
String masterAddrBak = this.masterAddr;
if (masterAddrBak != null) {
try {
if (null != brokerController.getMessageStore().getTimerMessageStore() &&
!brokerController.getTimerMessageStore().isShouldRunningDequeue()) {... | @Test
public void testSyncTimerCheckPoint() throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, MQBrokerException, InterruptedException {
when(brokerOuterAPI.getTimerCheckPoint(anyString())).thenReturn(timerCheckpoint);
slaveSynchronize.syncTimerCheckPoint();
... |
public static TableElements of(final TableElement... elements) {
return new TableElements(ImmutableList.copyOf(elements));
} | @Test
public void shouldIterateElements() {
// Given:
final TableElement te1 = tableElement("k0", STRING_TYPE, KEY_CONSTRAINT);
final TableElement te2 = tableElement("v0", INT_TYPE);
// When:
final Iterable<TableElement> iterable = TableElements.of(ImmutableList.of(te1, te2));
// Then:
a... |
public static Expression convert(Filter[] filters) {
Expression expression = Expressions.alwaysTrue();
for (Filter filter : filters) {
Expression converted = convert(filter);
Preconditions.checkArgument(
converted != null, "Cannot convert filter to Iceberg: %s", filter);
expression =... | @Test
public void testDateFilterConversion() {
LocalDate localDate = LocalDate.parse("2018-10-18");
Date date = Date.valueOf(localDate);
long epochDay = localDate.toEpochDay();
Expression localDateExpression = SparkFilters.convert(GreaterThan.apply("x", localDate));
Expression dateExpression = Sp... |
@Override
public BigDecimal getBigNumber( Object object ) throws KettleValueException {
Long timestampAsInteger = getInteger( object );
if ( null != timestampAsInteger ) {
return BigDecimal.valueOf( timestampAsInteger );
} else {
return null;
}
} | @Test
public void testConvertTimestampToBigNumber_Nanoseconds() throws KettleValueException {
System.setProperty( Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE,
Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE_NANOSECONDS );
ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp();
BigDecimal r... |
public Properties translate(Properties source) {
Properties hikariProperties = new Properties();
// Iterate over source Properties and translate from HZ to Hikari
source.forEach((key, value) -> {
String keyString = (String) key;
if (PROPERTY_MAP.containsKey(keyString)) {... | @Test
public void testUnknownProperty() {
// Unknown Hikari property is considered as DataSource property
String unknownProperty = "unknownProperty";
Properties hzProperties = new Properties();
hzProperties.put(unknownProperty, "value");
Properties hikariProperties = hikariT... |
public static boolean isCompleteHost(final String host) {
if (host == null) {
return false;
}
return IP_PATTERN.matcher(host).matches();
} | @Test
public void testIsCompleteHost() {
assertTrue(IpUtils.isCompleteHost("192.168.1.166"));
assertFalse(IpUtils.isCompleteHost("192.168."));
assertFalse(IpUtils.isCompleteHost("192.."));
} |
Object getFromSignalDependency(String signalDependencyName, String paramName) {
try {
return executor
.submit(() -> fromSignalDependency(signalDependencyName, paramName))
.get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new MaestroInternalError(
... | @Test
public void testGetFromSignalDependency() {
when(signalDependenciesParams.get("dev/foo/bar"))
.thenReturn(
Collections.singletonList(
Collections.singletonMap(
"param1", StringParameter.builder().evaluatedResult("hello").build())));
assertEquals("h... |
public String getLowerLimit()
{
String retval = null;
COSArray arr = node.getCOSArray(COSName.LIMITS);
if( arr != null )
{
retval = arr.getString( 0 );
}
return retval;
} | @Test
void testLowerLimit() throws IOException
{
assertEquals("Actinium", this.node5.getLowerLimit());
assertEquals("Actinium", this.node2.getLowerLimit());
assertEquals("Xenon", this.node24.getLowerLimit());
assertEquals("Xenon", this.node4.getLowerLimit());
assertEqua... |
@Override
public int size() {
return soi.getAllStructFieldRefs().size();
} | @Test
public void testSize() throws Exception {
HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector());
Assert.assertEquals(4, r.size());
} |
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 matchedDatesTest() {
//测试每30秒执行
List<Date> matchedDates = CronPatternUtil.matchedDates("0/30 * 8-18 * * ?", DateUtil.parse("2018-10-15 14:33:22"), 5, true);
assertEquals(5, matchedDates.size());
assertEquals("2018-10-15 14:33:30", matchedDates.get(0).toString());
assertEquals("2018-10-15 14... |
@Override
public ExecuteContext after(ExecuteContext context) {
if (InvokeUtils.isKafkaInvokeBySermant(Thread.currentThread().getStackTrace())) {
return context;
}
KafkaConsumerWrapper kafkaConsumerWrapper = KafkaConsumerController.getKafkaConsumerCache()
.get(con... | @Test
public void testAfter() {
ExecuteContext context = ExecuteContext.forMemberMethod(mockConsumer, null, null, null, null);
interceptor.after(context);
Assert.assertEquals(topics,
KafkaConsumerController.getKafkaConsumerCache().get(mockConsumer.hashCode()).getOriginalTopic... |
@Override
public Optional<String> nodeIdToHostName(String nodeId) {
return nodeById(nodeId)
.map(jsonNode -> jsonNode.path("host"))
.filter(host -> !host.isMissingNode())
.map(JsonNode::asText);
} | @Test
void handlesMissingHostField() throws Exception {
mockNodesResponse();
assertThat(this.clusterAdapter.nodeIdToHostName(nodeId)).isEmpty();
} |
static <T> T copy(T object, DataComplexTable alreadyCopied) throws CloneNotSupportedException
{
if (object == null)
{
return null;
}
else if (isComplex(object))
{
DataComplex src = (DataComplex) object;
@SuppressWarnings("unchecked")
T found = (T) alreadyCopied.get(src);
... | @Test
public void testListClonesHaveDifferentHashValues() throws CloneNotSupportedException
{
DataList originalList = new DataList();
originalList.add("value");
DataList copyList = originalList.copy();
// The objects should be "equal," but not identical.
assertTrue(copyList.equals(originalList... |
public ClassData getClassDataOrNull(String className) {
ClassData classData = loadBytecodesFromClientCache(className);
if (classData != null) {
return classData;
}
if (providerMode == UserCodeDeploymentConfig.ProviderMode.OFF) {
return null;
}
clas... | @Test
public void givenProviderModeSetToOFF_whenMapClassContainsClass_thenReturnNull() {
UserCodeDeploymentConfig.ProviderMode providerMode = OFF;
String className = "className";
ClassSource classSource = newMockClassSource();
ClassLoader parent = getClass().getClassLoader();
... |
@Override
public void eventAdded( KettleLoggingEvent event ) {
Object messageObject = event.getMessage();
checkNotNull( messageObject, "Expected log message to be defined." );
if ( messageObject instanceof LogMessage ) {
LogMessage message = (LogMessage) messageObject;
LoggingObjectInterface l... | @Test
public void testAddLogEventJob() {
when( logObjProvider.apply( logChannelId ) ).thenReturn( loggingObject );
when( loggingObject.getObjectType() ).thenReturn( LoggingObjectType.JOB );
when( loggingObject.getFilename() ).thenReturn( "filename" );
when( message.getLevel() ).thenReturn( LogLevel.BA... |
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml4(input));
} | @Test
public void shouldDecorateCode() {
assertThat(Markdown.convertToHtml("This is a ``line of code``")).isEqualTo("This is a <code>line of code</code>");
assertThat(Markdown.convertToHtml("This is not a ``line of code")).isEqualTo("This is not a ``line of code");
} |
public static void enableDeepLinkInstallSource(boolean enable) {
mEnableDeepLinkInstallSource = enable;
} | @Test
public void enableDeepLinkInstallSource() {
DeepLinkManager.enableDeepLinkInstallSource(true);
} |
@Override
public void commitJob(JobContext originalContext) throws IOException {
JobContext jobContext = TezUtil.enrichContextWithVertexId(originalContext);
JobConf jobConf = jobContext.getJobConf();
long startTime = System.currentTimeMillis();
LOG.info("Committing job {} has started", jobContext.get... | @Test
public void testRetryTask() throws IOException {
HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter();
Table table = table(temp.toFile().getPath(), false);
JobConf conf = jobConf(table, 2);
// Write records and abort the tasks
writeRecords(table.name(), 2, 0, false, true,... |
@Override
public Optional<String> getNewCodeReferenceBranch() {
if (!newCodeReferenceBranch.isInitialized()) {
return Optional.empty();
}
return Optional.of(newCodeReferenceBranch.getProperty());
} | @Test
public void get_new_code_reference_branch_return_empty_when_holder_is_not_initialized() {
assertThat(underTest.getNewCodeReferenceBranch()).isEmpty();
} |
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog, int subpartitionId)
throws IOException {
boolean recycleBuffer = true;
try {
if (expectedSequenceNumber != sequenceNumber) {
onError(new BufferReorderingException(expectedSequenceNumber, sequenc... | @Test
void testNotifyOnPriority() throws IOException {
SingleInputGate inputGate = new SingleInputGateBuilder().build();
RemoteInputChannel channel = InputChannelTestUtils.createRemoteInputChannel(inputGate, 0);
CheckpointOptions options = new CheckpointOptions(CHECKPOINT, getDefault());
... |
public Command create(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext context) {
return create(statement, context.getServiceContext(), context);
} | @Test
public void shouldValidatePlannedQuery() {
// Given:
givenPlannedQuery();
// When:
commandFactory.create(configuredStatement, executionContext);
// Then:
verify(executionContext).plan(serviceContext, configuredStatement);
verify(executionContext).execute(
serviceContext,
... |
@Override
public String exportResources( VariableSpace space, Map<String, ResourceDefinition> definitions,
ResourceNamingInterface namingInterface, Repository repository, IMetaStore metaStore ) throws KettleException {
// Try to load the transformation from repository or file.
... | @Ignore( "Test can't be properly mocked" )
@Test
public void testExportResources() throws KettleException {
JobEntryTrans jobEntryTrans = spy( getJobEntryTrans() );
TransMeta transMeta = mock( TransMeta.class );
String testName = "test";
doReturn( transMeta ).when( jobEntryTrans ).getTransMeta( an... |
@Override
public Optional<KsqlConstants.PersistentQueryType> getPersistentQueryType() {
if (!queryPlan.isPresent()) {
return Optional.empty();
}
// CREATE_AS and CREATE_SOURCE commands contain a DDL command and a Query plan.
if (ddlCommand.isPresent()) {
if (ddlCommand.get() instanceof Cr... | @Test
public void shouldReturnCreateAsPersistentQueryTypeOnCreateStream() {
// Given:
final CreateStreamCommand ddlCommand = Mockito.mock(CreateStreamCommand.class);
final KsqlPlanV1 plan = new KsqlPlanV1(
"stmt",
Optional.of(ddlCommand),
Optional.of(queryPlan1));
// When/Then... |
@JsonProperty("progress")
public int progress() {
if (indices.isEmpty()) {
return 100; // avoid division by zero. No indices == migration is immediately done
}
final BigDecimal sum = indices.stream()
.filter(i -> i.progress() != null)
.map(RemoteR... | @Test
void testProgress() {
final RemoteReindexMigration migration = withIndices(
index("one", RemoteReindexingMigrationAdapter.Status.FINISHED),
index("two", RemoteReindexingMigrationAdapter.Status.FINISHED),
index("three", RemoteReindexingMigrationAdapter.St... |
public static void executeWithRetries(
final Function function,
final RetryBehaviour retryBehaviour
) throws Exception {
executeWithRetries(() -> {
function.call();
return null;
}, retryBehaviour);
} | @Test
public void shouldRetryIfSupplierThrowsExecutionExceptionWrapingRetriable() throws Exception {
// Given:
final AtomicInteger counts = new AtomicInteger(5);
final Callable<Object> throwsExecutionExceptionThenSucceeds = () -> {
if (counts.decrementAndGet() == 0) {
return null;
}
... |
public RouteResult<T> route(HttpMethod method, String path) {
return route(method, path, Collections.emptyMap());
} | @Test
void testSplatWildcard() {
RouteResult<String> routed = router.route(GET, "/download/foo/bar.png");
assertThat(routed.target()).isEqualTo("download");
assertThat(routed.pathParams()).hasSize(1);
assertThat(routed.pathParams().get("*")).isEqualTo("foo/bar.png");
} |
public static void setCallTimeout(Operation op, long callTimeout) {
op.setCallTimeout(callTimeout);
} | @Test
public void testSetCallTimeout() {
Operation operation = new DummyOperation();
setCallTimeout(operation, 10);
assertEquals(10, operation.getCallTimeout());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.