focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public InputSplit[] getSplits(JobConf job, int numSplits)
throws IOException {
StopWatch sw = new StopWatch().start();
FileStatus[] stats = listStatus(job);
// Save the number of input files for metrics/loadgen
job.setLong(NUM_INPUT_FILES, stats.length);
long totalSize = 0; ... | @Test
public void testSplitLocationInfo() throws Exception {
Configuration conf = getConfiguration();
conf.set(org.apache.hadoop.mapreduce.lib.input.FileInputFormat.INPUT_DIR,
"test:///a1/a2");
JobConf job = new JobConf(conf);
TextInputFormat fileInputFormat = new TextInputFormat();
fileIn... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setMyName() {
retry.setEnabled(false);
BaseResponse response = bot.execute(new SetMyName().name("name").languageCode("en"));
if (!response.isOk()) {
assertEquals(429, response.errorCode());
assertTrue(response.description().startsWith("Too Many Reque... |
@Override
public int getGroupKeyLength() {
return _groupByColumns.size();
} | @Test
public void testGetGroupKeyLength() {
// Run the test
final int result = _groupByResultSetUnderTest.getGroupKeyLength();
// Verify the results
assertEquals(1, result);
} |
public static Map<String, Object> compare(byte[] baselineImg, byte[] latestImg, Map<String, Object> options,
Map<String, Object> defaultOptions) throws MismatchException {
boolean allowScaling = toBool(defaultOptions.get("allowScaling"));
ImageComparison im... | @Test
void testMissingBaseline() {
ImageComparison.MismatchException exception = assertThrows(ImageComparison.MismatchException.class, () ->
ImageComparison.compare(null, R_1x1_IMG, opts(), opts()));
assertTrue(exception.getMessage().contains("baseline image was empty or not found")... |
public int toBaseUnitsRounded() {
return (int) (toBaseUnits() + 0.5d);
} | @Test
public void calculateRoundedUpValueInBaseUnits() throws Exception {
Quantity<Metrics> quantity = new Quantity<Metrics>(51, Metrics.cm);
assertThat(quantity.toBaseUnitsRounded()).isEqualTo(1);
} |
@Override
public Processor createPostProcessor(Exchange exchange, DynamicAwareEntry entry) {
Processor postProcessor = null;
if (DynamicRouterControlConstants.SHOULD_OPTIMIZE.test(entry.getUri())) {
postProcessor = ex -> {
Message message = exchange.getMessage();
... | @Test
void createPostProcessor() throws Exception {
Mockito.when(exchange.getMessage()).thenReturn(message);
Mockito.when(message.removeHeader(any())).thenReturn("test");
String originalUri = "dynamic-router-control:subscribe?subscriptionId=testSub1";
String uri = "dynamic-router-con... |
private Mono<ServerResponse> search(ServerRequest request) {
return Mono.fromSupplier(
() -> new SearchParam(request.queryParams()))
.map(param -> {
var option = new SearchOption();
option.setIncludeTypes(List.of(PostHaloDocumentsProvider.POST_DOCUMENT... | @Test
void shouldFailWhenSearchEngineIsUnavailable() {
when(searchService.search(any(SearchOption.class)))
.thenReturn(Mono.error(new SearchEngineUnavailableException()));
client.post().uri("/indices/-/search")
.bodyValue(new SearchOption())
.exchange()
... |
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 testNestedInInsideNot() {
Not filter =
Not.apply(And.apply(EqualTo.apply("col1", 1), In.apply("col2", new Integer[] {1, 2})));
Expression converted = SparkFilters.convert(filter);
Assert.assertNull("Expression should not be converted", converted);
} |
public static Expression compile(String expression, String... variableNames) throws ExpressionException {
return new Expression(expression, variableNames);
} | @Test
public void testErrors() {
// test lexer errors
{
ExpressionException e = assertThrows(ExpressionException.class,
() -> compile("#"));
assertEquals(0, e.getPosition(), "Error position");
}
// test parser errors
{
Expre... |
public static String encode(String raw) {
return new BCryptPasswordEncoder().encode(raw);
} | @Test
void encode() {
String str = PasswordEncoderUtil.encode("nacos");
String str2 = PasswordEncoderUtil.encode("nacos");
assertNotEquals(str2, str);
} |
public JobConf() {
checkAndWarnDeprecation();
} | @SuppressWarnings("deprecation")
@Test (timeout=5000)
public void testJobConf() {
JobConf conf = new JobConf();
// test default value
Pattern pattern = conf.getJarUnpackPattern();
assertEquals(Pattern.compile("(?:classes/|lib/).*").toString(),
pattern.toString());
// default value
as... |
public static NotFoundException appNotFound(String appId) {
return new NotFoundException("app not found for appId:%s", appId);
} | @Test
public void testAppNotFoundException() {
NotFoundException exception = NotFoundException.appNotFound(appId);
assertEquals(exception.getMessage(), "app not found for appId:app-1001");
} |
public synchronized ImmutableList<Struct> readTableRecords(String tableId, String... columnNames)
throws IllegalStateException {
return readTableRecords(tableId, ImmutableList.copyOf(columnNames));
} | @Test
public void testReadRecordsShouldThrowExceptionWhenCalledBeforeExecuteDdlStatement() {
ImmutableList<String> columnNames = ImmutableList.of("SingerId");
assertThrows(
IllegalStateException.class, () -> testManager.readTableRecords("Singers", columnNames));
assertThrows(
IllegalState... |
@Override
public DropStatement withoutDeleteClause() {
return new DropTable(getLocation(), getName(), getIfExists(), false);
} | @Test
public void shouldCopyWithoutDeleteTopic() {
// Given:
final DropTable table = new DropTable(SOME_NAME, true, true);
// When:
final DropTable result = (DropTable) table.withoutDeleteClause();
// Then:
assertThat(result, is(new DropTable(SOME_NAME, true, false)));
} |
public String extractVersion(String rawXml) {
Matcher m = p.matcher(rawXml);
if (m.find()) {
return m.group(1);
}
throw new IllegalArgumentException("Impossible to extract version from the file");
} | @Test
public void extractVersionWhenXmlPrologIsPresent() {
String version = instance.extractVersion("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ScenarioSimulationModel version=\"1.1\">");
assertThat(version).isEqualTo("1.1");
} |
static String escapeAndJoin(List<String> parts) {
return parts.stream()
.map(ZetaSqlIdUtils::escapeSpecialChars)
.map(ZetaSqlIdUtils::replaceWhitespaces)
.map(ZetaSqlIdUtils::backtickIfNeeded)
.collect(joining("."));
} | @Test
public void testHandlesMixedIds() {
List<String> id = Arrays.asList("aaa", "Bb---B", "zAzzz00");
assertEquals("aaa.`Bb---B`.zAzzz00", ZetaSqlIdUtils.escapeAndJoin(id));
} |
@Override
public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() {
return new UnbindChangeProcessor();
} | @Test
public void innerJoinShouldPropagateNewPrimaryKey() {
final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>();
innerJoinProcessor.init(context);
context.setRecordMetadata("topic", 0, 0);
final LeftValue leftR... |
public static DispatcherRunner create(
LeaderElection leaderElection,
FatalErrorHandler fatalErrorHandler,
DispatcherLeaderProcessFactory dispatcherLeaderProcessFactory)
throws Exception {
final DefaultDispatcherRunner dispatcherRunner =
new Defaul... | @Test
public void grantLeadership_withExistingLeader_waitsForTerminationOfFirstLeader()
throws Exception {
final UUID firstLeaderSessionId = UUID.randomUUID();
final UUID secondLeaderSessionId = UUID.randomUUID();
final StartStopDispatcherLeaderProcess firstTestingDispatcherLead... |
@Override
public void verify(X509Certificate certificate, Date date) {
logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(),
certificate.getIssuerX500Principal());
// Create trustAnchors
final Set<TrustAnchor> trustAnchors = getTrusted().stream().map(
... | @Test
public void shouldThrowExceptionIfIntermediateIsMissing() {
thrown.expect(VerificationException.class);
thrown.expectMessage("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
createC... |
public static DisruptContext error(long latency)
{
if (latency < 0)
{
throw new IllegalArgumentException("Latency cannot be smaller than 0");
}
return new ErrorDisruptContext(latency);
} | @Test
public void testError()
{
final long latency = 4200;
DisruptContexts.ErrorDisruptContext context =
(DisruptContexts.ErrorDisruptContext) DisruptContexts.error(latency);
Assert.assertEquals(context.mode(), DisruptMode.ERROR);
Assert.assertEquals(context.latency(), latency);
} |
@Override
public int findConfigHistoryCountByTime(final Timestamp startTime) {
HistoryConfigInfoMapper historyConfigInfoMapper = mapperManager.findMapper(
dataSourceService.getDataSourceType(), TableConstant.HIS_CONFIG_INFO);
MapperContext context = new MapperContext();
conte... | @Test
void testFindConfigHistoryCountByTime() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//mock count
Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))).thenReturn(308);
//execute & verify
int ... |
private MetricDto getMetric(String key) {
return requireNonNull(metricsByKeys.get(key), () -> String.format("Metric with key %s not found", key));
} | @Test
public void getMetric() {
Collection<MetricDto> metrics = asList(METRIC_1, METRIC_2);
MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT, FILE), metrics, new ArrayList<>());
assertThat(underTest.getMetricByUuid(METRIC_2.getUuid())).isSameAs(METRIC_2);
} |
public void expectLogMessage(int level, String tag, Matcher<String> messageMatcher) {
expectLog(level, tag, messageMatcher, null);
} | @Test
public void testExpectedLogMessageFailureOutput() {
Log.e("Mytag", "message1");
Log.e("Mytag", "message2"); // Not expected
rule.expectLogMessage(Log.ERROR, "Mytag", "message1");
rule.expectLogMessage(Log.ERROR, "Mytag", "message3"); // Not logged
expectedException.expect(
new TypeS... |
public static boolean isCaseSensitiveCustomerId(final String customerId) {
return NEW_CUSTOMER_CASE_SENSISTIVE_PATTERN.matcher(customerId).matches();
} | @Test
public void testCaseSensitiveNewCustomerIds() {
for (String validValue : CustomerIdExamples.VALID_CASE_SENSISTIVE_NEW_CUSTOMER_IDS) {
assertTrue(validValue + " is case-insensitive customer ID.",
BaseSupportConfig.isCaseSensitiveCustomerId(validValue));
}
} |
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
// will throw UnsupportedOperationException; delegate anyway for testability
return underlying().computeIfPresent(key, remappingFunction);
} | @Test
public void testDelegationOfUnsupportedFunctionComputeIfPresent() {
final BiFunction<Object, Object, Object> mockBiFunction = mock(BiFunction.class);
new PCollectionsHashMapWrapperDelegationChecker<>()
.defineMockConfigurationForUnsupportedFunction(mock -> mock.computeIfPresent(eq(... |
@Override
public void fenceZombieSourceTasks(final String connName, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting zombie fencing request {}", connName);
if (requestNotSignedProperly(requestSignature, callback)) {
return;
}
... | @Test
public void testFenceZombiesInvalidSignature() {
// Don't have to run the whole gamut of scenarios (invalid signature, missing signature, earlier protocol that doesn't require signatures)
// since the task config tests cover that pretty well. One sanity check to ensure that this method is guar... |
public Command create(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext context) {
return create(statement, context.getServiceContext(), context);
} | @Test
public void shouldCreateCommandForPauseQuery() {
// Given:
givenPause();
// When:
final Command command = commandFactory.create(configuredStatement, executionContext);
// Then:
assertThat(command, is(Command.of(configuredStatement)));
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void banChatMember() {
BaseResponse response = bot.execute(new BanChatMember(channelName, chatId).untilDate(123).revokeMessages(true));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
assertEquals("Bad Request: can't remove chat owner", response.de... |
public static Matrix.SVD svd(IMatrix A, int k) {
return svd(A, k, Math.min(3 * k, Math.min(A.nrow(), A.ncol())), 1E-6);
} | @Test
public void testSVD() {
System.out.println("SVD sparse matrix");
double[][] A = {
{1, 0, 0, 1, 0, 0, 0, 0, 0},
{1, 0, 1, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0},
{0, 1, 1, 2, 0, ... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void testNameExprToString() {
final TypedExpression left = expr(THIS_PLACEHOLDER + ".getName", String.class);
final TypedExpression right = expr("$maxName", Comparable.class);
final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, true).coerc... |
public static List<Element> getDirectChildren(Element parent, String namespace, String tag) {
List<Element> directChildren = new ArrayList<>();
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNod... | @Test
void getDirectChildren() {
List<Element> children = XmlUtil.getDirectChildren(parent, "http://example.com", "child");
assertEquals(2, children.size());
assertEquals("child", children.get(0).getLocalName());
assertEquals("child", children.get(1).getLocalName());
} |
public static ProjectPath projectPathFromId(String projectId) {
return new ProjectPath(String.format("projects/%s", projectId));
} | @Test
public void projectPathFromIdWellFormed() {
ProjectPath path = PubsubClient.projectPathFromId("test");
assertEquals("projects/test", path.getPath());
} |
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < 1) {
return;
}
// read one byte to guess protocol
final int magic = in.getByte(in.readerIndex());
ChannelPipeline p = ctx.pipelin... | @Test
void testDecodeHttp() throws Exception {
ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'G'});
ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class);
ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class);
Mockito.when(context.pipeline()).thenRetur... |
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi... | @Test
public void testPermutorForRule_FEED_TITLE_DESC_NullTitle() {
Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.FEED_TITLE_Z_A);
List<FeedItem> itemList = getTestList();
itemList.get(1) // itemId 3
.getFeed().setTitle(null);
assertTrue(checkIdOr... |
@Override
public void checkSubjectAccess(
final KsqlSecurityContext securityContext,
final String subjectName,
final AclOperation operation
) {
checkAccess(new CacheKey(securityContext,
AuthObjectType.SUBJECT,
subjectName,
operation));
} | @Test
public void shouldCheckBackendValidatorOnFirstSubjectAccessRequest() {
// When
cache.checkSubjectAccess(securityContext, SUBJECT_1, AclOperation.READ);
// Then
verify(backendValidator, times(1))
.checkSubjectAccess(securityContext, SUBJECT_1, AclOperation.READ);
verifyNoMoreInteract... |
@Override
public List<ColumnarFeature> process(String value) {
try {
LocalDate date = LocalDate.parse(value, formatter);
List<ColumnarFeature> features = new ArrayList<>(featureTypes.size());
for (DateFeatureType f : featureTypes) {
int featureValue = f.ex... | @Test
public void testInvalidBehaviour() {
String notADateFormatString = "not-a-date-format-string";
try {
DateFieldProcessor proc = new DateFieldProcessor("test",
EnumSet.of(DateFieldProcessor.DateFeatureType.DAY),
notADateFormatString);
... |
@Private
public void scheduleAllReduces() {
for (ContainerRequest req : pendingReduces) {
scheduledRequests.addReduce(req);
}
pendingReduces.clear();
} | @Test(timeout = 30000)
public void testExcessReduceContainerAssign() throws Exception {
final Configuration conf = new Configuration();
conf.setFloat(MRJobConfig.COMPLETED_MAPS_FOR_REDUCE_SLOWSTART, 0.0f);
final MyResourceManager2 rm = new MyResourceManager2(conf);
rm.start();
final RMApp app = Mock... |
void setAssociationPolicy(LeafNodeAssociationPolicy associationPolicy) {
this.associationPolicy = associationPolicy;
} | @Test
public void testSerialization() throws Exception
{
// Setup fixture.
final DefaultNodeConfiguration config = new DefaultNodeConfiguration(false);
config.setDeliverPayloads( !config.isDeliverPayloads() ); // invert all defaults to improve test coverage.
config.setMaxPayload... |
public static JsonToRowWithErrFn withExceptionReporting(Schema rowSchema) {
return JsonToRowWithErrFn.forSchema(rowSchema);
} | @Test
@Category(NeedsRunner.class)
public void testParsesRowsDeadLetterNoErrors() throws Exception {
PCollection<String> jsonPersons = pipeline.apply("jsonPersons", Create.of(JSON_PERSON));
ParseResult results = jsonPersons.apply(JsonToRow.withExceptionReporting(PERSON_SCHEMA));
PCollection<Row> pers... |
public URI baseUri() {
return server.configuration().baseUri();
} | @Test
void run_callback() {
var baseUri = application.baseUri();
var sessionID = UUID.randomUUID().toString();
var response =
given()
.log()
.all()
.cookie("session_id", sessionID)
.formParam("code", "code")
.when()
.get(bas... |
public static String encodeHexString(byte[] bytes) {
int l = bytes.length;
char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS_LOWER[(0xF0 & bytes[i]) >>> 4];
out[j++] = DIGITS_LOWER[0x0F & bytes[i]];
}
... | @Test
void testEncodeHexString() {
assertEquals("", MD5Utils.encodeHexString(new byte[0]));
assertEquals("010203", MD5Utils.encodeHexString(new byte[] {1, 2, 3}));
} |
@Nonnull
@Override
public Optional<? extends INode> parse(
@Nullable final String str, @Nonnull DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
for (IMapper mapper : jcaSpecificAlgorithmMappers) {
Optional<? extend... | @Test
void aeCipher() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaAlgorithmMapper jcaAlgorithmMapper = new JcaAlgorithmMapper();
Optional<? extends INode> assetOptional =
jcaAlgorithmMa... |
@Override
public Path touch(final Path file, final TransferStatus status) throws BackgroundException {
if(file.isFile()) {
try {
Files.createFile(session.toPath(file));
}
catch(FileAlreadyExistsException e) {
//
}
ca... | @Test
public void testTouch() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
assertNotNull(session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCance... |
public void test() {
User user = new User();
user.setName("yupi");
User resultUser = userService.getUser(user);
System.out.println(resultUser.getName());
} | @Test
void test1() {
exampleService.test();
} |
public void openFile() {
openFile( false );
} | @Test
public void testLoadLastUsedTransLocalWithRepository() throws Exception {
String repositoryName = "repositoryName";
String fileName = "fileName";
setLoadLastUsedJobLocalWithRepository( false, repositoryName, null, fileName, true );
verify( spoon ).openFile( fileName, null, true );
} |
public void stopRunning( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
if ( this.isStopped() || sdi.isDisposed() ) {
return;
}
final DatabaseJoinData data = (DatabaseJoinData) sdi;
dbLock.lock();
try {
if ( data.db != null && data.db.getConnection() != null &&... | @Test
public void testStopRunningWhenStepIsNotStoppedNorStepDataInterfaceIsDisposedAndDatabaseConnectionIsNotValid() throws KettleException {
doReturn( false ).when( mockDatabaseJoin ).isStopped();
doReturn( false ).when( mockStepDataInterface ).isDisposed();
when( mockStepDataInterface.db.getConnection()... |
static int readHeapBuffer(InputStream f, ByteBuffer buf) throws IOException {
int bytesRead = f.read(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining());
if (bytesRead < 0) {
// if this resulted in EOF, don't update position
return bytesRead;
} else {
buf.position(buf.positio... | @Test
public void testHeapPositionAndLimit() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocate(20);
readBuffer.position(5);
readBuffer.limit(13);
readBuffer.mark();
MockInputStream stream = new MockInputStream(7);
int len = DelegatingSeekableInputStream.readHeapBuffer(stream, re... |
@Override
public void deleteGroup(Long id) {
// 校验存在
validateGroupExists(id);
// 校验分组下是否有用户
validateGroupHasUser(id);
// 删除
memberGroupMapper.deleteById(id);
} | @Test
public void testDeleteGroup_success() {
// mock 数据
MemberGroupDO dbGroup = randomPojo(MemberGroupDO.class);
groupMapper.insert(dbGroup);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbGroup.getId();
// 调用
groupService.deleteGroup(id);
// 校验数据不存在了
... |
@Override
public void create(final String path, final byte[] data, final List<ACL> acl, final CreateMode createMode,
final AsyncCallback.StringCallback cb, final Object ctx)
{
final RetryCallback callback = new RetryCallback() {
@Override
protected void retry() {
if (!cr... | @Test
public void testCreate() throws NoSuchMethodException
{
testCreateHelper(_dummyData);
} |
@Override
public void updateMailSendResult(Long logId, String messageId, Exception exception) {
// 1. 成功
if (exception == null) {
mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now())
.setSendStatus(MailSendStatusEnum.SUCCESS.getStatus... | @Test
public void testUpdateMailSendResult_exception() {
// mock 数据
MailLogDO log = randomPojo(MailLogDO.class, o -> {
o.setSendStatus(MailSendStatusEnum.INIT.getStatus());
o.setSendTime(null).setSendMessageId(null).setSendException(null)
.setTemplateParam... |
public static LocalDateTime formatLocalDateTimeFromTimestamp(final Long timestamp) {
return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.ofHours(8));
} | @Test
public void testFormatLocalDateTimeFromTimestamp() {
LocalDateTime localDateTime1 = LocalDateTime.now(ZoneOffset.ofHours(8));
LocalDateTime localDateTime2 = DateUtils.formatLocalDateTimeFromTimestamp(ZonedDateTime.of(localDateTime1, ZoneOffset.ofHours(8)).toInstant().toEpochMilli());
a... |
@Override
public V getValueForExactAddress(IpPrefix prefix) {
String prefixString = getPrefixString(prefix);
if (prefix.isIp4()) {
return ipv4Tree.getValueForExactKey(prefixString);
}
if (prefix.isIp6()) {
return ipv6Tree.getValueForExactKey(prefixString);
... | @Test
public void testGetValueForExactAddress() {
assertThat("IPv4 prefix has not been inserted correctly",
radixTree.getValueForExactAddress(ipv4PrefixKey1), is(1));
assertThat("IPv4 prefix has not been inserted correctly",
radixTree.getValueForExactAddress(ipv4Prefi... |
static Object actualCoerceParameter(Type requiredType, Object valueToCoerce) {
Object toReturn = valueToCoerce;
if (valueToCoerce instanceof LocalDate localDate &&
requiredType == BuiltInType.DATE_TIME) {
return DateTimeEvalHelper.coerceDateTime(localDate);
}
... | @Test
void actualCoerceParameterNotConverted() {
Object value = "TEST_OBJECT";
Object retrieved = CoerceUtil.actualCoerceParameter(BuiltInType.DATE_TIME, value);
assertNotNull(retrieved);
assertEquals(value, retrieved);
value = LocalDate.now();
retrieved = CoerceUtil... |
public static String getCertFingerPrint(Certificate cert) {
byte [] digest = null;
try {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance("SHA-1");
digest = md.digest(encCertInfo);
} catch (Exception e) {
logger... | @Test
public void testGetCertFingerPrintPrimary() throws Exception {
X509Certificate cert = null;
try (InputStream is = Config.getInstance().getInputStreamFromFile("primary.crt")){
CertificateFactory cf = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) cf.ge... |
@ExceptionHandler(ConstraintViolationException.class)
protected ShenyuAdminResult handleConstraintViolationException(final ConstraintViolationException e) {
LOG.warn("constraint violation exception", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
return ShenyuAdmin... | @Test
public void testHandleConstraintViolationException() {
ConstraintViolationException exception = spy(new ConstraintViolationException(Collections.emptySet()));
Set<ConstraintViolation<?>> violations = spy(Collections.emptySet());
when(exception.getConstraintViolations()).thenReturn(viol... |
public Optional<Object> evaluate(final Map<String, Object> columnPairsMap, final String outputColumn,
final String regexField) {
boolean matching = true;
boolean isRegex =
regexField != null && columnValues.containsKey(regexField) && (boolean) columnV... | @Test
void evaluateKeyFoundNotMatchingRegex() {
KiePMMLRow kiePMMLRow = new KiePMMLRow(COLUMN_VALUES);
Optional<Object> retrieved = kiePMMLRow.evaluate(Collections.singletonMap("KEY-1", "[435345]"), "KEY-0",
REGEX_FIELD);
assertThat(re... |
@Override
public void readOne(TProtocol in, TProtocol out) throws TException {
readOneStruct(in, out);
} | @Test
public void testEnumMissingSchema() throws Exception {
CountingErrorHandler countingHandler = new CountingErrorHandler();
BufferedProtocolReadToWrite p = new BufferedProtocolReadToWrite(
ThriftSchemaConverter.toStructType(StructWithEnum.class), countingHandler);
final ByteArrayOutputStream i... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
final IRODSFileSystemAO fs = session.getClient();
final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(file.getAbsolute());
if(!f.exists... | @Test
public void testFind() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/iRODS (iPlant Collaborat... |
public static void disablePullConsumption(DefaultLitePullConsumerWrapper wrapper, Set<String> topics) {
Set<String> subscribedTopic = wrapper.getSubscribedTopics();
if (subscribedTopic.stream().anyMatch(topics::contains)) {
suspendPullConsumer(wrapper);
return;
}
... | @Test
public void testDisablePullConsumptionWithAssignNoSubTractTopics() {
subscribedTopics = new HashSet<>();
subscribedTopics.add("test-topic-2");
Collection<MessageQueue> messageQueues = new ArrayList<>();
MessageQueue messageQueue = new MessageQueue("test-topic-2", "broker-1", 1)... |
@Override
public KeyValue<K, V> next() {
final KeyValue<K, ValueAndTimestamp<V>> innerKeyValue = innerIterator.next();
return KeyValue.pair(innerKeyValue.key, getValueOrNull(innerKeyValue.value));
} | @Test
public void shouldReturnPlainKeyValuePairOnGet() {
when(mockedKeyValueIterator.next()).thenReturn(
new KeyValue<>("key", ValueAndTimestamp.make("value", 42L)));
assertThat(keyValueIteratorFacade.next(), is(KeyValue.pair("key", "value")));
} |
static Double convertToDouble(Object toConvert) {
if (!(toConvert instanceof Number )) {
throw new IllegalArgumentException("Input data must be declared and sent as Number, received " + toConvert);
}
return (Double) DATA_TYPE.DOUBLE.getActualValue(toConvert);
} | @Test
void convertToDouble_invalidValues() {
List<Object> inputs = Arrays.asList("3", "3.0", true);
inputs.forEach(number -> {
assertThatThrownBy(() -> KiePMMLClusteringModel.convertToDouble(number))
.isInstanceOf(IllegalArgumentException.class);
});
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(file.getType().contains(Path.Type.upload)) {
// Pending large file upload
final Wr... | @Test
public void testHideMarker() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path directory = new B2DirectoryFeature(session, fileid).mkdir(n... |
@Override
public int getNettyWriteBufferHighWaterMark() {
return clientConfig.getPropertyAsInteger(WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_BUFFER_HIGH_WATER_MARK);
} | @Test
void testGetNettyWriteBufferHighWaterMarkOverride() {
clientConfig.set(ConnectionPoolConfigImpl.WRITE_BUFFER_HIGH_WATER_MARK, 40000);
assertEquals(40000, connectionPoolConfig.getNettyWriteBufferHighWaterMark());
} |
public static int findLevelWithThreadName(Level expectedLevel, String threadName) {
int count = 0;
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
Log log = logList.get(i);
if (log.getLogLevel().equals(expectedLevel) && log.getLogThre... | @Test
void testFindLevelWithThreadName() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
when(log.getLogThread()).thenReturn("thread-1");
log = mock(Log.class);
DubboAppender.logList.add(log);
when(... |
@Override
public String[] split(String text) {
boundary.setText(text);
List<String> words = new ArrayList<>();
int start = boundary.first();
int end = boundary.next();
while (end != BreakIterator.DONE) {
String word = text.substring(start, end).trim();
... | @Test
public void testSplitSingleQuote() {
System.out.println("tokenize single quote");
String text = "String literals can be enclosed in matching single "
+ "quotes ('). But it's also appearing in contractions such as can't.";
String[] expResult = {"String", "literals", "ca... |
@Override
public void open(Configuration parameters) throws Exception {
this.rateLimiterTriggeredCounter =
getRuntimeContext()
.getMetricGroup()
.addGroup(
TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT)
.counter(TableMain... | @Test
void testCommitCount() throws Exception {
TriggerManager manager =
manager(sql.tableLoader(TABLE_NAME), new TriggerEvaluator.Builder().commitCount(3).build());
try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness =
harness(manager)) {
testHarness.o... |
@Override
public CompletableFuture<Map<String, BrokerLookupData>> filterAsync(
Map<String, BrokerLookupData> brokers,
ServiceUnitId serviceUnit,
LoadManagerContext context) {
if (brokers.isEmpty()) {
return CompletableFuture.completedFuture(brokers);
}... | @Test
public void test() throws BrokerFilterException, ExecutionException, InterruptedException {
LoadManagerContext context = getContext();
context.brokerConfiguration().setLoadManagerClassName(ExtensibleLoadManagerImpl.class.getName());
BrokerLoadManagerClassFilter filter = new BrokerLoadM... |
@Override
public int run(String[] args) throws Exception {
YarnConfiguration yarnConf =
getConf() == null ? new YarnConfiguration() : new YarnConfiguration(
getConf());
boolean isHAEnabled =
yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED,
YarnConfiguration.DEFAULT_... | @Test
public void testAddToClusterNodeLabels() throws Exception {
// successfully add labels
String[] args =
{ "-addToClusterNodeLabels", "x", "-directlyAccessNodeLabelStore" };
assertEquals(0, rmAdminCLI.run(args));
assertTrue(dummyNodeLabelsManager.getClusterNodeLabelNames().containsAll(
... |
private String getEnv(String envName, InterpreterLaunchContext context) {
String env = context.getProperties().getProperty(envName);
if (StringUtils.isBlank(env)) {
env = System.getenv(envName);
}
if (StringUtils.isBlank(env)) {
LOGGER.warn("environment variable: {} is empty", envName);
... | @Test
void testYarnClusterMode_2() throws IOException {
SparkInterpreterLauncher launcher = new SparkInterpreterLauncher(zConf, null);
Properties properties = new Properties();
properties.setProperty("SPARK_HOME", sparkHome);
properties.setProperty("property_1", "value_1");
properties.setProperty(... |
public static List<Pair<InstrumentSelector, ViewBuilder>> getMetricsView() {
ArrayList<Pair<InstrumentSelector, ViewBuilder>> res = new ArrayList<>();
InstrumentSelector providerRpcLatencySelector = InstrumentSelector.builder()
.setType(InstrumentType.HISTOGRAM)
.setName(HISTOGR... | @Test
public void getMetricsView() {
TieredStoreMetricsManager.getMetricsView();
} |
static void verifyAddMissingValues(final List<KiePMMLMiningField> notTargetMiningFields,
final PMMLRequestData requestData) {
logger.debug("verifyMissingValues {} {}", notTargetMiningFields, requestData);
Collection<ParameterInfo> requestParams = requestData.getReq... | @Test
void verifyAddMissingValuesMissingReturnInvalid() {
assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> {
List<KiePMMLMiningField> miningFields = IntStream.range(0, 3).mapToObj(i -> {
DATA_TYPE dataType = DATA_TYPE.values()[i];
return KiePMML... |
public List<TypeDescriptor<?>> getArgumentTypes(Method method) {
Invokable<?, ?> typedMethod = token.method(method);
List<TypeDescriptor<?>> argTypes = Lists.newArrayList();
for (Parameter parameter : typedMethod.getParameters()) {
argTypes.add(new SimpleTypeDescriptor<>(parameter.getType()));
}
... | @Test
public void testGetArgumentTypes() throws Exception {
Method identity = Id.class.getDeclaredMethod("identity", Object.class);
TypeToken<Id<String>> token = new TypeToken<Id<String>>() {};
TypeDescriptor<Id<String>> descriptor = new TypeDescriptor<Id<String>>() {};
assertEquals(
token.me... |
public static <T> RBFNetwork<T> fit(T[] x, int[] y, RBF<T>[] rbf) {
return fit(x, y, rbf, false);
} | @Test
public void testIris() {
System.out.println("Iris");
MathEx.setSeed(19650218); // to get repeatable results.
ClassificationMetrics metrics = LOOCV.classification(Iris.x, Iris.y,
(x, y) -> RBFNetwork.fit(x, y, RBF.fit(x, 10)));
System.out.println("RBF Network:... |
@GET
@Path("{path:.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8})
public Response get(@PathParam("path") String path,
@Context UriInfo uriInfo,
@QueryParam(OperationParam.NAME) O... | @Test
@TestDir
@TestJetty
@TestHdfs
public void testECPolicy() throws Exception {
createHttpFSServer(false, false);
final ErasureCodingPolicy ecPolicy = SystemErasureCodingPolicies
.getByID(SystemErasureCodingPolicies.RS_3_2_POLICY_ID);
final String ecPolicyName = ecPolicy.getName();
// ... |
public Plan validateReservationUpdateRequest(
ReservationSystem reservationSystem, ReservationUpdateRequest request)
throws YarnException {
ReservationId reservationId = request.getReservationId();
Plan plan = validateReservation(reservationSystem, reservationId,
AuditConstants.UPDATE_RESERV... | @Test
public void testUpdateReservationExceedsGangSize() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 4);
Resource resource = Resource.newInstance(512, 1);
when(plan.getTotalCapacity()).thenReturn(resource);
Plan plan = null;
try {
plan = rrVa... |
@Override
protected SchemaTransform from(Configuration configuration) {
return new ExplodeTransform(configuration);
} | @Test
@Category(NeedsRunner.class)
public void testZipProduct() {
PCollection<Row> input = pipeline.apply(Create.of(INPUT_ROWS)).setRowSchema(INPUT_SCHEMA);
PCollection<Row> exploded =
PCollectionRowTuple.of(JavaExplodeTransformProvider.INPUT_ROWS_TAG, input)
.apply(
new... |
public ReadyCheckingSideInputReader createReaderForViews(
Collection<PCollectionView<?>> newContainedViews) {
if (!containedViews.containsAll(newContainedViews)) {
Set<PCollectionView<?>> currentlyContained = ImmutableSet.copyOf(containedViews);
Set<PCollectionView<?>> newRequested = ImmutableSet.... | @Test
public void withViewsForViewNotInContainerFails() {
PCollection<KV<String, String>> input =
pipeline.apply(Create.empty(new TypeDescriptor<KV<String, String>>() {}));
PCollectionView<Map<String, Iterable<String>>> newView = input.apply(View.asMultimap());
thrown.expect(IllegalArgumentExcept... |
@PostConstruct
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public void init() {
// All servers have jobs that modify usage, idempotent.
ConfigExecutor.scheduleCorrectUsageTask(() -> {
LOGGER.info("[capacityManagement] start correct usage");
StopWatch watch = new StopW... | @Test
void testInit() {
service.init();
} |
@Override
public ParameterType<?> parameterType() {
return parameterType;
} | @Test
void can_define_parameter_type_converters_with_var_args() throws NoSuchMethodException {
Method method = JavaParameterTypeDefinitionTest.class.getMethod("convert_varargs_capture_group_to_string",
String[].class);
JavaParameterTypeDefinition definition = new JavaParameterTypeDefinit... |
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
@SuppressWarnings("unchecked")
final GHPoint3D other = (GHPoint3D) obj;
if (Double.isNaN(ele))
// very special case necessary in QueryGraph, asserted via test
return NumH... | @Test
public void testEquals() {
GHPoint3D point1 = new GHPoint3D(1, 2, Double.NaN);
GHPoint3D point2 = new GHPoint3D(1, 2, Double.NaN);
assertEquals(point1, point2);
point1 = new GHPoint3D(1, 2, 0);
point2 = new GHPoint3D(1, 2, 1);
assertNotEquals(point1, point2);
... |
public static <T> Supplier<T> memoizeConcurrent(Supplier<T> onceSupplier) {
return new ConcurrentMemoizingSupplier<>(onceSupplier);
} | @Test(expected = NullPointerException.class)
public void when_memoizeConcurrentWithNullSupplier_then_exception() {
Supplier<Object> supplier = () -> null;
memoizeConcurrent(supplier).get();
} |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetMap3() {
Map<String, String> map1 = new LinkedHashMap(1);
Map<String, String> map2 = new LinkedHashMap(2);
map1.put("key", "value");
map2.put("key1", "value1");
map2.put("key2", "value2");
Iterator<Map.Entry<String, String>> iter = map1.entrySet().it... |
public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) {
if (fqjt.isArray()) {
// if array, then calculate the name of the base (non-array) type
// then add the array indicators back in
String fqn = fqjt.getFullyQualifiedName();
... | @Test
void testArray() {
Interface interfaze = new Interface(new FullyQualifiedJavaType("com.foo.UserMapper"));
interfaze.addImportedType(new FullyQualifiedJavaType("java.math.BigDecimal[]"));
FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("java.math.BigDecimal[]");
asser... |
public static int getTag(byte[] raw) {
try (final Asn1InputStream is = new Asn1InputStream(raw)) {
return is.readTag();
}
} | @Test
public void getTagTripleByte() {
assertEquals(0x7f8102, Asn1Utils.getTag(new byte[] { 0x7f, (byte) 0x81, 02, 0}));
} |
public void execute() {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
.visit(treeRootHolder.getReportTreeRoot());
} | @Test
public void compute_and_aggregate_duplicated_lines_density_using_lines() {
addDuplicatedBlock(FILE_1_REF, 2);
addDuplicatedBlock(FILE_2_REF, 3);
when(FILE_1_ATTRS.getLines()).thenReturn(10);
when(FILE_2_ATTRS.getLines()).thenReturn(40);
// this should have no effect as it's a test file
... |
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder)
throws CoderException {
if (value == null) {
return noopMutationDetector();
} else {
return new CodedValueMutationDetector<>(value, coder);
}
} | @Test
public void testImmutableSet() throws Exception {
Set<Integer> value = Sets.newHashSet(Arrays.asList(1, 2, 3, 4));
MutationDetector detector =
MutationDetectors.forValueWithCoder(value, IterableCoder.of(VarIntCoder.of()));
detector.verifyUnmodified();
} |
@Override
public DnsServerAddressStream nameServerAddressStream(String hostname) {
for (;;) {
int i = hostname.indexOf('.', 1);
if (i < 0 || i == hostname.length() - 1) {
return defaultNameServerAddresses.stream();
}
DnsServerAddresses address... | @Test
public void defaultLookupShouldReturnResultsIfOnlySingleFileSpecified(@TempDir Path tempDir) throws Exception {
File f = buildFile(tempDir, "domain linecorp.local\n" +
"nameserver 127.0.0.2\n" +
"nameserver 127.0.0.3\n");
UnixResolverDnsSer... |
public static Slice truncateToLength(Slice slice, Type type)
{
requireNonNull(type, "type is null");
if (!isVarcharType(type)) {
throw new IllegalArgumentException("type must be the instance of VarcharType");
}
return truncateToLength(slice, VarcharType.class.cast(type));... | @Test
public void testTruncateToLength()
{
// Single byte code points
assertEquals(truncateToLength(Slices.utf8Slice("abc"), 0), Slices.utf8Slice(""));
assertEquals(truncateToLength(Slices.utf8Slice("abc"), 1), Slices.utf8Slice("a"));
assertEquals(truncateToLength(Slices.utf8Slic... |
public Optional<Measure> toMeasure(@Nullable LiveMeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getDataAsString();
switch (metric.getType().getValueType()) {... | @Test
public void toMeasure_returns_no_QualityGateStatus_if_alertStatus_has_data_in_wrong_case_for_Level_Metric() {
Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setData("waRn"), SOME_STRING_METRIC);
assertThat(measure).isPresent();
assertThat(measure.get().hasQualityGateStatus()).i... |
@Override
public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment,
Map<InstancePartitionsType, InstancePartitions> instancePartitionsMap) {
Preconditions.checkState(instancePartitionsMap.size() == 1, "One instance partition type should be provided");
Inst... | @Test
public void testAssignSegment() {
assertTrue(_segmentAssignment instanceof StrictRealtimeSegmentAssignment);
Map<InstancePartitionsType, InstancePartitions> onlyConsumingInstancePartitionMap =
ImmutableMap.of(InstancePartitionsType.CONSUMING, _instancePartitionsMap.get(InstancePartitionsType.CON... |
@Override
public HttpResponse send(HttpRequest httpRequest) throws IOException {
return send(httpRequest, null);
} | @Test
public void send_whenGetRequest_returnsExpectedHttpResponse() throws IOException {
String responseBody = "test response";
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(HttpStatus.OK.code())
.setHeader(CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString())
... |
@Override
String getInterfaceName(Invoker invoker, String prefix) {
return DubboUtils.getInterfaceName(invoker, prefix);
} | @Test
public void testDegradeSync() {
try (MockedStatic<TimeUtil> mocked = super.mockTimeUtil()) {
setCurrentMillis(mocked, 1740000000000L);
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
... |
@Override
public synchronized void putConnectorConfig(String connName,
final Map<String, String> config,
boolean allowReplace,
final Callback<Created<ConnectorInfo>> callba... | @Test
public void testPutConnectorConfig() throws Exception {
initialize(true);
Map<String, String> connConfig = connectorConfig(SourceSink.SOURCE);
Map<String, String> newConnConfig = new HashMap<>(connConfig);
newConnConfig.put("foo", "bar");
Callback<Map<String, String>> ... |
public static KeyValueBytesStoreSupplier inMemoryKeyValueStore(final String name) {
Objects.requireNonNull(name, "name cannot be null");
return new InMemoryKeyValueBytesStoreSupplier(name);
} | @Test
public void shouldThrowIfIMemoryKeyValueStoreStoreNameIsNull() {
final Exception e = assertThrows(NullPointerException.class, () -> Stores.inMemoryKeyValueStore(null));
assertEquals("name cannot be null", e.getMessage());
} |
public void write(ImageWriter writer, ImageWriterOptions options) {
if (options.metadataVersion().isScramSupported()) {
for (Entry<ScramMechanism, Map<String, ScramCredentialData>> mechanismEntry : mechanisms.entrySet()) {
for (Entry<String, ScramCredentialData> userEntry : mechanism... | @Test
public void testImage1withInvalidIBP() {
ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder().
setMetadataVersion(MetadataVersion.IBP_3_4_IV0).build();
RecordListWriter writer = new RecordListWriter();
try {
IMAGE1.write(writer, imageWrit... |
List<GSBlobIdentifier> getComponentBlobIds(GSFileSystemOptions options) {
String temporaryBucketName = BlobUtils.getTemporaryBucketName(finalBlobIdentifier, options);
List<GSBlobIdentifier> componentBlobIdentifiers =
componentObjectIds.stream()
.map(
... | @Test
public void shouldGetComponentBlobIdsWithEntropy() {
// configure options, if this test configuration has a temporary bucket name, set it
Configuration flinkConfig = new Configuration();
if (temporaryBucketName != null) {
flinkConfig.set(GSFileSystemOptions.WRITER_TEMPORAR... |
public RetryableException(final String message, final Throwable cause,
final Date retryAfter, final ShenyuRequest request) {
super(message, cause);
this.httpMethod = request.getHttpMethod();
this.retryAfter = Optional.ofNullable(retryAfter).map(Date::getTime).orElse... | @Test
public void retryableExceptionTest() {
Assert.assertNotNull(retryableException);
} |
@Override
public RouteContext route(final ShardingRule shardingRule) {
RouteContext result = new RouteContext();
Collection<DataNode> dataNodes = getDataNodes(shardingRule, shardingRule.getShardingTable(logicTableName));
result.getOriginalDataNodes().addAll(originalDataNodes);
for (D... | @Test
void assertRouteByMixedWithHintTableOnly() {
SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class).defaultAnswer(RETURNS_DEEP_STUBS));
when(((TableAvailable) sqlStatementContext).getTablesContext().getTableNames()).thenRe... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
int lastRuleWasSatisfiedAfterBars = 0;
int startIndex = index;
if (!initialRule.isSatisfied(index, tradingRecord)) {
traceIsSatisfied(index, false);
return false;
}
traceIs... | @Test
public void isSatisfied() {
assertFalse(chainRule.isSatisfied(0));
assertTrue(chainRule.isSatisfied(4));
assertTrue(chainRule.isSatisfied(6));
assertFalse(chainRule.isSatisfied(7));
} |
@VisibleForTesting
PlanNodeStatsEstimate addJoinComplementStats(
PlanNodeStatsEstimate sourceStats,
PlanNodeStatsEstimate innerJoinStats,
PlanNodeStatsEstimate joinComplementStats)
{
double innerJoinRowCount = innerJoinStats.getOutputRowCount();
double joinCom... | @Test
public void testAddJoinComplementStats()
{
double statsToAddNdv = 5;
PlanNodeStatsEstimate statsToAdd = planNodeStats(RIGHT_ROWS_COUNT,
variableStatistics(LEFT_JOIN_COLUMN, 0.0, 5.0, 0.2, statsToAddNdv));
PlanNodeStatsEstimate addedStats = planNodeStats(TOTAL_ROWS_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.