focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
boolean swapReplicas(BrokerAndSortedReplicas toSwap,
BrokerAndSortedReplicas toSwapWith,
double meanDiskUsage,
ClusterModel clusterModel,
Set<String> excludedTopics) {
if (LOG.isTraceEnabled()) {
LOG.trace("Swapping re... | @Test
public void testSwapReplicas() {
Properties props = KafkaCruiseControlUnitTestUtils.getKafkaCruiseControlProperties();
props.setProperty(AnalyzerConfig.MAX_REPLICAS_PER_BROKER_CONFIG, Long.toString(10L));
props.setProperty(AnalyzerConfig.OVERPROVISIONED_MAX_REPLICAS_PER_BROKER_CONFIG, Long.toString(... |
public StreamConfig getConfiguration() {
return configuration;
} | @Test
void testEarlyCanceling() throws Exception {
final StreamConfig cfg = new StreamConfig(new Configuration());
cfg.setOperatorID(new OperatorID(4711L, 42L));
cfg.setStreamOperator(new SlowlyDeserializingOperator());
cfg.setTimeCharacteristic(TimeCharacteristic.ProcessingTime);
... |
private void replay(ApiMessage message, Optional<OffsetAndEpoch> snapshotId, long offset) {
if (log.isTraceEnabled()) {
if (snapshotId.isPresent()) {
log.trace("Replaying snapshot {} record {}",
Snapshots.filenameFromSnapshotId(snapshotId.get()),
... | @Test
public void testActivationRecordsPartialTransactionNoSupport() {
SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
FeatureControlManager featureControlManager = new FeatureControlManager.Builder()
.setSnapshotRegistry(snapshotRegistry)
.setMeta... |
public List<UrlRewriteRule> getUrlRewriteRules() {
return urlRewriteRules;
} | @Test
public void testUrlRewriteRules() {
ExternalServiceConfig config = new ExternalServiceConfig();
assert config.getUrlRewriteRules().size() == 2;
} |
@Override
public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) {
ParamCheckResponse paramCheckResponse = new ParamCheckResponse();
if (paramInfos == null) {
paramCheckResponse.setSuccess(true);
return paramCheckResponse;
}
for (ParamInfo pa... | @Test
void testCheckParamInfoForNamespaceId() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
// Max Length
String namespaceId = buildStringLength(65);
paramInfo.setNamespaceId(namespaceId);
... |
public Optional<Throwable> run(String... arguments) {
try {
if (isFlag(HELP, arguments)) {
parser.printHelp(stdOut);
} else if (isFlag(VERSION, arguments)) {
parser.printVersion(stdOut);
} else {
final Namespace namespace = pars... | @Test
void handlesLongHelpCommands() throws Exception {
assertThat(cli.run("--help"))
.isEmpty();
assertThat(stdOut)
.hasToString(String.format(
"usage: java -jar dw-thing.jar [-h] [-v] {check,custom} ...%n" +
"... |
public void setStringValue( List<String> value ) {
this.stringValue = value;
} | @Test
public void setStringValue() {
JobScheduleParam jobScheduleParam = mock( JobScheduleParam.class );
doCallRealMethod().when( jobScheduleParam ).setStringValue( any() );
List<String> stringValue = new ArrayList<>();
stringValue.add( "hitachi" );
jobScheduleParam.setStringValue( stringValue );
... |
public void addIndexes(int maxIndex, int[] dictionaryIndexes, int indexCount)
{
if (indexCount == 0 && indexRetainedBytes > 0) {
// Ignore empty segment, since there are other segments present.
return;
}
checkState(maxIndex >= lastMaxIndex, "LastMax is greater than the... | @Test(expectedExceptions = {IllegalStateException.class})
public void testDecreasingMaxThrows()
{
DictionaryRowGroupBuilder rowGroupBuilder = new DictionaryRowGroupBuilder();
rowGroupBuilder.addIndexes(5, new int[0], 0);
rowGroupBuilder.addIndexes(3, new int[1], 1);
} |
@Override
public Long sendSingleSms(String mobile, Long userId, Integer userType,
String templateCode, Map<String, Object> templateParams) {
// 校验短信模板是否合法
SmsTemplateDO template = validateSmsTemplate(templateCode);
// 校验短信渠道是否合法
SmsChannelDO smsChannel =... | @Test
public void testSendSingleSms_successWhenSmsTemplateDisable() {
// 准备参数
String mobile = randomString();
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = randomString();
Map<String, Object> templa... |
public static void setWorkingDirectory(Job job, Path workingDirectory) {
job.getConfiguration().set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH,
workingDirectory.toString());
} | @Test
public void testSetWorkingDirectory() {
try {
Job job = Job.getInstance(new Configuration());
Assert.assertEquals(null, CopyOutputFormat.getWorkingDirectory(job));
job.getConfiguration().set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, "");
Assert.assertEquals(null, CopyOutputFormat... |
public void close(ThreadLocal<DelegatingDbSessionSupplier> dbSessionThreadLocal, String label) {
DelegatingDbSessionSupplier delegatingDbSessionSupplier = dbSessionThreadLocal.get();
boolean getCalled = delegatingDbSessionSupplier.isPopulated();
if (getCalled) {
try {
DbSession res = delegatin... | @Test
void openSession_with_caching_returns_DbSession_that_rolls_back_on_close_if_any_mutation_call_was_not_followed_by_commit_nor_rollback() throws SQLException {
DbSession dbSession = openSessionAndDoSeveralMutatingAndNeutralCalls();
dbSession.close();
verify(myBatisDbSession).rollback();
} |
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public static TableReference parseTableSpec(String tableSpec) {
Matcher match = BigQueryIO.TABLE_SPEC.matcher(tableSpec);
if (!match.matches()) {
throw new IllegalArgumentException(
String.format(
... | @Test
public void testTablesspecParsingStandardSql() {
TableReference ref = BigQueryHelpers.parseTableSpec("my-project.data_set.table_name");
assertEquals("my-project", ref.getProjectId());
assertEquals("data_set", ref.getDatasetId());
assertEquals("table_name", ref.getTableId());
} |
static String resolveRegion(AwsConfig awsConfig, AwsMetadataApi metadataApi, Environment environment) {
if (!isNullOrEmptyAfterTrim(awsConfig.getRegion())) {
return awsConfig.getRegion();
}
if (environment.isRunningOnEcs()) {
return regionFrom(metadataApi.availabilityZon... | @Test
public void resolveRegionAwsConfig() {
// given
String region = "us-east-1";
AwsConfig awsConfig = AwsConfig.builder().setRegion(region).build();
AwsMetadataApi awsMetadataApi = mock(AwsMetadataApi.class);
Environment environment = mock(Environment.class);
// w... |
@Override
public void finished(boolean allStepsExecuted) {
if (postProjectAnalysisTasks.length == 0) {
return;
}
ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED);
for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) {
... | @Test
@UseDataProvider("booleanValues")
public void organization_is_null(boolean allStepsExecuted) {
underTest.finished(allStepsExecuted);
verify(postProjectAnalysisTask).finished(taskContextCaptor.capture());
assertThat(taskContextCaptor.getValue().getProjectAnalysis().getOrganization()).isEmpty();
... |
public abstract int[] toTopLevelIndexes(); | @Test
void testToTopLevelIndexes() {
assertThat(Projection.of(new int[] {1, 2, 3, 4}).toTopLevelIndexes())
.isEqualTo(new int[] {1, 2, 3, 4});
assertThat(
Projection.of(new int[][] {new int[] {4}, new int[] {1}, new int[] {2}})
... |
@Override
public Long clusterCountKeysInSlot(int slot) {
RedisClusterNode node = clusterGetNodeForSlot(slot);
MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort()));
RFuture<Long> f = executorService.readAsync(entry, St... | @Test
public void testClusterCountKeysInSlot() {
Long t = connection.clusterCountKeysInSlot(1);
assertThat(t).isZero();
} |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatCtasWithClause() {
final String statementString = "CREATE TABLE S WITH(partitions=4) AS SELECT * FROM address;";
final Statement statement = parseSingle(statementString);
final String result = SqlFormatter.formatSql(statement);
assertThat(result, startsWith("CREATE TABL... |
public static String getDbNameFromJdbcUrl(String jdbcUrl) {
Matcher matcher = JDBC_PATTERN.matcher(jdbcUrl);
if (matcher.find()) {
return matcher.group(3);
} else {
LOG.error("jdbc url {} is not valid.", jdbcUrl);
}
return null;
} | @Test
public void getDbTest() {
assert ObReaderUtils.getDbNameFromJdbcUrl("jdbc:mysql://127.0.0.1:3306/testdb").equalsIgnoreCase("testdb");
assert ObReaderUtils.getDbNameFromJdbcUrl("jdbc:oceanbase://127.0.0.1:2883/testdb").equalsIgnoreCase("testdb");
assert ObReaderUtils.getDbNameFromJdbcUr... |
@Override
public <R extends MessageResponse<?>> void chatStream(Prompt<R> prompt, StreamResponseListener<R> listener, ChatOptions options) {
LlmClient llmClient = new SseClient();
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.... | @Test()
public void testChat01() {
OpenAiLlmConfig config = new OpenAiLlmConfig();
config.setApiKey("sk-alQ9N********");
config.setEndpoint("https://api.moonshot.cn");
config.setModel("moonshot-v1-8k");
// config.setDebug(true);
Llm llm = new OpenAiLlm(config);
// ... |
@Override
public TimelineEntity getEntity(TimelineReaderContext context,
TimelineDataToRetrieve dataToRetrieve) throws IOException {
String flowRunPathStr = getFlowRunPath(context.getUserId(),
context.getClusterId(), context.getFlowName(), context.getFlowRunId(),
context.getAppId());
Pat... | @Test
void testAppFlowMappingCsv() throws Exception {
// Test getting an entity by cluster and app where flow entry
// in app flow mapping csv has commas.
TimelineEntity result = reader.getEntity(
new TimelineReaderContext("cluster1", null, null, null, "app2",
"app", "id_5"),
n... |
static S3ResourceId fromUri(String uri) {
Matcher m = S3_URI.matcher(uri);
checkArgument(m.matches(), "Invalid S3 URI: [%s]", uri);
String scheme = m.group("SCHEME");
String bucket = m.group("BUCKET");
String key = Strings.nullToEmpty(m.group("KEY"));
if (!key.startsWith("/")) {
key = "/" ... | @Test
public void testInvalidPathNoBucketAndSlash() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Invalid S3 URI: [s3:///]");
S3ResourceId.fromUri("s3:///");
} |
@Override
public FailureResult howToHandleFailure(
Throwable failure, CompletableFuture<Map<String, String>> failureLabels) {
FailureResult failureResult = howToHandleFailure(failure);
if (reportEventsAsSpans) {
// TODO: replace with reporting as event once events are support... | @Test
void testHowToHandleFailureRejectedByStrategy() throws Exception {
final Configuration configuration = new Configuration();
configuration.set(TraceOptions.REPORT_EVENTS_AS_SPANS, Boolean.TRUE);
final List<Span> spanCollector = new ArrayList<>(1);
final UnregisteredMetricGroups.... |
public boolean allSearchFiltersVisible() {
return hiddenSearchFiltersIDs.isEmpty();
} | @Test
void testAllSearchFiltersVisibleReturnsTrueIfHiddenFilterIsAllowed() {
toTest = new SearchFilterVisibilityCheckStatus(Collections.singletonList("Allowed hidden one"));
assertTrue(toTest.allSearchFiltersVisible(ImmutableList.of("Allowed hidden one", "Another allowed hidden one")));
} |
public static boolean isBlank(final CharSequence cs) {
final int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
... | @Test
void testIsBlank() {
assertTrue(StringUtils.isBlank(null));
assertTrue(StringUtils.isBlank(""));
assertTrue(StringUtils.isBlank(" "));
assertFalse(StringUtils.isBlank("bob"));
assertFalse(StringUtils.isBlank(" bob "));
} |
@Override
public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) {
for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) {
Map<String, ?> sourceOffset = offsetEntry.getValue();
if (sourceOffset == null)... | @Test
public void testAlterOffsetsTombstones() {
MirrorCheckpointConnector connector = new MirrorCheckpointConnector();
Function<Map<String, ?>, Boolean> alterOffsets = partition -> connector.alterOffsets(
null,
Collections.singletonMap(partition, null)
);
... |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationHasDisabledCronExpressionValueShouldBeDeleted() {
new ApplicationContextRunner()
.withBean(RecurringJobPostProcessor.class)
.withBean(JobScheduler.class, () -> jobScheduler)
.withPropertyValues("my-job... |
public IssuesChangesNotification newIssuesChangesNotification(Set<DefaultIssue> issues, Map<String, UserDto> assigneesByUuid) {
AnalysisChange change = new AnalysisChange(analysisMetadataHolder.getAnalysisDate());
Set<ChangedIssue> changedIssues = issues.stream()
.map(issue -> new ChangedIssue.Builder(iss... | @Test
public void newIssuesChangesNotification_fails_with_NPE_if_issue_has_no_rule() {
DefaultIssue issue = new DefaultIssue();
Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid();
analysisMetadata.setAnalysisDate(new Random().nextLong());
assertThatThrownBy(() -> underTest.newIssuesChan... |
public void release() {
if (isReleased()) {
return;
}
released = true;
// decrease ref count when buffer is released from memory.
buffer.recycleBuffer();
} | @Test
void testBufferReleaseRepeatedly() {
bufferContext.release();
assertThatNoException()
.as("repeatedly release should only recycle buffer once.")
.isThrownBy(() -> bufferContext.release());
} |
@Override
public CompletableFuture<MeterStoreResult> addOrUpdateMeter(Meter meter) {
checkArgument(validIndex(meter), "Meter index is not valid");
CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
MeterKey key = MeterKey.key(meter.deviceId(), meter.meterCellId());
... | @Test(expected = IllegalArgumentException.class)
public void testInvalidCellId() {
initMeterStore(true);
// MF defines an end index equals to 10
Meter meterBad = DefaultMeter.builder()
.forDevice(did3)
.fromApp(APP_ID)
.withCellId(invalidCid)
... |
@Override
public void reset() {
resetCount++;
super.reset();
initEvaluatorMap();
initCollisionMaps();
root.recursiveReset();
resetTurboFilterList();
cancelScheduledTasks();
fireOnReset();
resetListenersExceptResetResistant();
resetStatu... | @Test
public void evaluatorMapPostReset() {
lc.reset();
assertNotNull(lc.getObject(CoreConstants.EVALUATOR_MAP));
} |
void handleCollision(Collection<? extends Point> toCheck, Map<Integer, Bubble> allBubbles) {
var toBePopped = false; //if any other bubble collides with it, made true
for (var point : toCheck) {
var otherId = point.id;
if (allBubbles.get(otherId) != null //the bubble hasn't been popped yet
... | @Test
void handleCollisionTest() {
var b1 = new Bubble(0, 0, 1, 2);
var b2 = new Bubble(1, 1, 2, 1);
var b3 = new Bubble(10, 10, 3, 1);
var bubbles = new HashMap<Integer, Bubble>();
bubbles.put(1, b1);
bubbles.put(2, b2);
bubbles.put(3, b3);
var bubblesToCheck = new ArrayList<Point>();... |
public static int standardErrorToBuckets(double maxStandardError)
{
checkCondition(maxStandardError >= LOWEST_MAX_STANDARD_ERROR && maxStandardError <= HIGHEST_MAX_STANDARD_ERROR,
INVALID_FUNCTION_ARGUMENT,
"Max standard error must be in [%s, %s]: %s", LOWEST_MAX_STANDARD_ERR... | @Test
public void testStandardErrorToBuckets()
{
assertEquals(standardErrorToBuckets(0.0326), 1024);
assertEquals(standardErrorToBuckets(0.0325), 1024);
assertEquals(standardErrorToBuckets(0.0324), 2048);
assertEquals(standardErrorToBuckets(0.0231), 2048);
assertEquals(st... |
public void validateAll(final Map<String, Object> properties) {
final Set<String> propsDenied = Sets.intersection(immutableProps, properties.keySet());
if (!propsDenied.isEmpty()) {
throw new KsqlException(String.format("One or more properties overrides set locally are "
+ "prohibited by the KSQ... | @Test
public void shouldNotThrowOnAllowedProp() {
validator.validateAll(ImmutableMap.of(
"mutable-1", "v1",
"anything", "v2"
));
} |
public PartitionMetadata from(Struct row) {
return PartitionMetadata.newBuilder()
.setPartitionToken(row.getString(COLUMN_PARTITION_TOKEN))
.setParentTokens(Sets.newHashSet(row.getStringList(COLUMN_PARENT_TOKENS)))
.setStartTimestamp(row.getTimestamp(COLUMN_START_TIMESTAMP))
.setEndT... | @Test
public void testMapPartitionMetadataFromResultSet() {
final Struct row =
Struct.newBuilder()
.set(COLUMN_PARTITION_TOKEN)
.to("token")
.set(COLUMN_PARENT_TOKENS)
.toStringArray(Collections.singletonList("parentToken"))
.set(COLUMN_START_TIM... |
static public Entry buildMenuStructure(String xml) {
final Reader reader = new StringReader(xml);
return buildMenuStructure(reader);
} | @Test
public void givenXmlWithChildEntryWithBuilderSpecificAttribute_createsStructureWithChildEntry() {
String xmlWithoutContent = "<FreeplaneUIEntries><Entry builderSpecificAttribute='Value'/></FreeplaneUIEntries>";
Entry builtMenuStructure = XmlEntryStructureBuilder.buildMenuStructure(xmlWithoutContent);
Ent... |
@GET
@Path("enabledPackage")
public Response getAllEnabledPackageInfo() {
try {
return new JsonResponse<>(Response.Status.OK, "", helium.getAllEnabledPackages()).build();
} catch (RuntimeException e) {
logger.error(e.getMessage(), e);
return new JsonResponse<>(Response.Status.INTERNAL_SERV... | @Test
void testGetAllEnabledPackageInfo() throws IOException {
// No enabled packages initially
CloseableHttpResponse get1 = httpGet("/helium/enabledPackage");
assertThat(get1, isAllowed());
Map<String, Object> resp1 = gson.fromJson(EntityUtils.toString(get1.getEntity(), StandardCharsets.UTF_8),
... |
private PiMulticastGroupEntry(int groupId, Set<PiPreReplica> replicas) {
this.groupId = groupId;
this.replicas = replicas;
} | @Test
public void testPiMulticastGroupEntry() {
assertThat("Invalid group ID",
group1.groupId(), is(groupId1));
assertThat("Invalid replicas size",
group1.replicas().size(), is(2));
assertThat("Invalid replicas",
group1.replicas(), con... |
public Map<NodeId, Set<NodeLabel>> getNodeLabelsInfo() {
Map<NodeId, Set<NodeLabel>> nodeToLabels =
generateNodeLabelsInfoPerNode(NodeLabel.class);
return nodeToLabels;
} | @Test
@Timeout(5000)
void testGetNodeLabelsInfo() throws IOException {
mgr.addToCluserNodeLabels(Arrays.asList(NodeLabel.newInstance("p1", false),
NodeLabel.newInstance("p2", true), NodeLabel.newInstance("p3", false)));
mgr.addLabelsToNode(ImmutableMap.of(toNodeId("n1"), toSet("p2")));
mgr.addLa... |
@Override
public synchronized List<PrivilegedOperation> preStart(Container container)
throws ResourceHandlerException {
String containerIdStr = container.getContainerId().toString();
// Assign Gpus to container if requested some.
GpuResourceAllocator.GpuAllocation allocation = gpuAllocator.assignGp... | @Test
public void testAllocationStored() throws Exception {
initializeGpus();
/* Start container 1, asks 3 containers */
Container container = mockContainerWithGpuRequest(1,
createResourceRequest(3));
gpuResourceHandler.preStart(container);
verify(mockNMStateStore).storeAssignedResources... |
public List<ChangeStreamRecord> toChangeStreamRecords(
PartitionMetadata partition,
ChangeStreamResultSet resultSet,
ChangeStreamResultSetMetadata resultSetMetadata) {
if (this.isPostgres()) {
// In PostgresQL, change stream records are returned as JsonB.
return Collections.singletonLi... | @Test
public void testMappingUpdateStructJsonNewValuesToDataChangeRecord() {
final DataChangeRecord dataChangeRecord =
new DataChangeRecord(
"partitionToken",
Timestamp.ofTimeSecondsAndNanos(10L, 20),
"serverTransactionId",
true,
"1",
... |
public static Optional<Map<?, ?>> findCachedServices(final Class<?> spiClass, final Collection<?> types) {
return Optional.ofNullable(cache.get()).map(optional -> optional.get(new Key(spiClass, types)));
} | @Test
void assertNotFindCachedServices() {
assertFalse(OrderedServicesCache.findCachedServices(OrderedSPIFixture.class, Collections.singleton(new OrderedInterfaceFixtureImpl())).isPresent());
} |
protected boolean removeService(Service service) {
LOG.debug("Removing service {}", service.getName());
synchronized (serviceList) {
return serviceList.remove(service);
}
} | @Test
public void testRemoveService() {
CompositeService testService = new CompositeService("TestService") {
@Override
public void serviceInit(Configuration conf) {
Integer notAService = new Integer(0);
assertFalse("Added an integer as a service",
addIfService(notAService))... |
public static ReadRows readRows() {
return new AutoValue_JdbcIO_ReadRows.Builder()
.setFetchSize(DEFAULT_FETCH_SIZE)
.setOutputParallelization(true)
.setStatementPreparator(ignored -> {})
.build();
} | @Test
public void testReadRowsWithNumericFields() {
PCollection<Row> rows =
pipeline.apply(
JdbcIO.readRows()
.withDataSourceConfiguration(DATA_SOURCE_CONFIGURATION)
.withQuery(
String.format(
"SELECT CAST(1 AS NUMERIC... |
public Set<String> getClusters(Service service) {
return serviceClusterIndex.getOrDefault(service, new HashSet<>());
} | @Test
void testGetClusters() {
Set<String> clusters = serviceStorage.getClusters(SERVICE);
assertNotNull(clusters);
for (String cluster : clusters) {
assertEquals(NACOS, cluster);
}
} |
@Override
public Collection<SQLTokenGenerator> getSQLTokenGenerators() {
Collection<SQLTokenGenerator> result = new LinkedList<>();
addSQLTokenGenerator(result, new ShardingTableTokenGenerator(shardingRule));
addSQLTokenGenerator(result, new ShardingDistinctProjectionPrefixTokenGenerator());... | @Test
void assertGetSQLTokenGenerators() throws Exception {
when(routeContext.containsTableSharding()).thenReturn(true);
SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(sqlStatementContext.getProjectionsContext().getAggregationProject... |
@Override
public void write(final Path file, final Distribution distribution, final LoginCallback prompt) throws BackgroundException {
final Path container = session.getFeature(PathContainerService.class).getContainer(file);
try {
if(null == distribution.getId()) {
// No ... | @Test
public void testWriteNewStreaming() throws Exception {
final AtomicBoolean set = new AtomicBoolean();
final CloudFrontDistributionConfiguration configuration = new CloudFrontDistributionConfiguration(session,
new S3LocationFeature(session), new DisabledX509TrustManager(), new D... |
@Override
public int read() {
return (mPosition < mLimit) ? (mData[mPosition++] & 0xff) : -1;
} | @Test
void testWrongLength() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(new byte[1], 0, 100);
});
} |
public boolean setStatus(DefaultIssue issue, String status, IssueChangeContext context) {
if (!Objects.equals(status, issue.status())) {
issue.setFieldChange(context, STATUS, issue.status(), status);
issue.setStatus(status);
issue.setUpdateDate(context.date());
issue.setChanged(true);
... | @Test
void set_status() {
boolean updated = underTest.setStatus(issue, Issue.STATUS_OPEN, context);
assertThat(updated).isTrue();
assertThat(issue.status()).isEqualTo(Issue.STATUS_OPEN);
FieldDiffs.Diff diff = issue.currentChange().get(STATUS);
assertThat(diff.oldValue()).isNull();
assertThat... |
public static byte[] readFileBytes(File file) {
if (file.exists()) {
String result = readFile(file);
if (result != null) {
return ByteUtils.toBytes(result);
}
}
return null;
} | @Test
void testReadFileBytes() {
assertNotNull(DiskUtils.readFileBytes(testFile));
} |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testJsonConversionForPartiallySerializedValues() throws Exception {
SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class);
options.setInteger(5);
SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, options);
options2.setString("TestValue");
SimpleTypes opt... |
@Override
public ZIPCompressionOutputStream createOutputStream( OutputStream out ) throws IOException {
return new ZIPCompressionOutputStream( out, this );
} | @Test
public void testCreateOutputStream() throws IOException {
ZIPCompressionProvider provider = (ZIPCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME );
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream( out );
ZIPCompressionOut... |
public static DynamicVoter parse(String input) {
input = input.trim();
int atIndex = input.indexOf("@");
if (atIndex < 0) {
throw new IllegalArgumentException("No @ found in dynamic voter string.");
}
if (atIndex == 0) {
throw new IllegalArgumentException(... | @Test
public void testNoColonFollowingHostname() {
assertEquals("No colon following hostname could be found.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("2@localhost8020K90IZ-0DRNazJ49kCZ1EMQ")).
getMessage());
} |
@Override
public void streamRequest(StreamRequest request, Callback<StreamResponse> callback)
{
streamRequest(request, new RequestContext(), callback);
} | @Test(invocationCount = 3, dataProvider = "isD2Async")
public void testStreamRequestWithNoIsFullRequest(boolean isD2Async) throws Exception {
int responseDelayNano = 100000000; //1s till response comes back
int backupDelayNano = 50000000; // make backup request after 0.5 second
Deque<URI> hostsReceivingRe... |
public static boolean isTopic(String destinationName) {
if (destinationName == null) {
throw new IllegalArgumentException("destinationName is null");
}
return destinationName.startsWith("topic:");
} | @Test
public void testIsTopic() {
assertTrue(DestinationNameParser.isTopic("topic:foo.DestinationNameParserTest"));
assertFalse(DestinationNameParser.isTopic("queue:bar.DestinationNameParserTest"));
assertFalse(DestinationNameParser.isTopic("bar"));
} |
@VisibleForTesting
static void startSqlGateway(PrintStream stream, String[] args) {
SqlGatewayOptions cliOptions = SqlGatewayOptionsParser.parseSqlGatewayOptions(args);
if (cliOptions.isPrintHelp()) {
SqlGatewayOptionsParser.printHelpSqlGateway(stream);
return;
}
... | @Test
void testPrintStartGatewayHelp() {
String[] args = new String[] {"--help"};
SqlGateway.startSqlGateway(new PrintStream(output), args);
assertThat(output.toString())
.contains(
"Start the Flink SQL Gateway as a daemon to submit Flink SQL.\n"
... |
@Override
@MethodNotAvailable
public Map<K, Object> executeOnKeys(Set<K> keys, com.hazelcast.map.EntryProcessor entryProcessor) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testExecuteOnKeys() {
Set<Integer> keys = new HashSet<>(singleton(23));
adapter.executeOnKeys(keys, new IMapReplaceEntryProcessor("value", "newValue"));
} |
public static CacheStats of(@NonNegative long hitCount, @NonNegative long missCount,
@NonNegative long loadSuccessCount, @NonNegative long loadFailureCount,
@NonNegative long totalLoadTime, @NonNegative long evictionCount,
@NonNegative long evictionWeight) {
// Many parameters of the same type in ... | @Test(dataProvider = "badArgs")
public void invalid(int hitCount, int missCount, int loadSuccessCount, int loadFailureCount,
int totalLoadTime, int evictionCount, int evictionWeight) {
assertThrows(IllegalArgumentException.class, () -> {
CacheStats.of(hitCount, missCount, loadSuccessCount,
l... |
@Override
public int get(PageId pageId, int bytesToRead, CacheScope scope) {
boolean seen = false;
for (int i = 0; i < mSegmentBloomFilters.length(); ++i) {
seen |= mSegmentBloomFilters.get(i).mightContain(pageId);
}
if (seen) {
mShadowCachePageHit.getAndIncrement();
mShadowCacheByte... | @Test
public void getNotExist() throws Exception {
assertEquals(0, mCacheManager.get(PAGE_ID1, PAGE1_BYTES, SCOPE1));
} |
public StoreMode getStoreMode() {
return storeMode;
} | @Test
public void testGetStoreMode() {
metadata.setStoreMode(StoreMode.RAFT);
Assertions.assertEquals(StoreMode.RAFT, metadata.getStoreMode());
} |
public static void main(String[] args) {
String relDir = args.length == 1 ? args[0] : "";
GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf");
routing(hopper);
speedModeVersusFlexibleMode(hopper);
alternativeRoute(hopper);
customizableRou... | @Test
public void main() {
Helper.removeDir(new File("target/routing-graph-cache"));
RoutingExample.main(new String[]{"../"});
Helper.removeDir(new File("target/routing-tc-graph-cache"));
RoutingExampleTC.main(new String[]{"../"});
} |
public CrossFilterConfig getCross() {
return cross;
} | @Test
public void testCrossFilterConfig() {
ShenyuConfig.CrossFilterConfig cross = config.getCross();
cross.setAllowCredentials(false);
cross.setEnabled(false);
cross.setAllowedExpose("test");
cross.setAllowedMethods("test");
cross.setAllowedHeaders("test");
c... |
public Future<Collection<Integer>> resizeAndReconcilePvcs(KafkaStatus kafkaStatus, List<PersistentVolumeClaim> pvcs) {
Set<Integer> podIdsToRestart = new HashSet<>();
List<Future<Void>> futures = new ArrayList<>(pvcs.size());
for (PersistentVolumeClaim desiredPvc : pvcs) {
Future<V... | @Test
public void testVolumesResizing(VertxTestContext context) {
List<PersistentVolumeClaim> pvcs = List.of(
createPvc("data-pod-0"),
createPvc("data-pod-1"),
createPvc("data-pod-2")
);
ResourceOperatorSupplier supplier = ResourceUtils.suppl... |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testLessThan() {
UnboundPredicate<Integer> expected =
org.apache.iceberg.expressions.Expressions.lessThan("field1", 1);
Optional<org.apache.iceberg.expressions.Expression> actual =
FlinkFilters.convert(resolve(Expressions.$("field1").isLess(Expressions.lit(1))));
assertT... |
static void populateSchemaFromListOfRanges(Schema toPopulate, List<RangeNode> ranges) {
Range range = consolidateRanges(ranges);
if (range != null) {
if (range.getLowEndPoint() != null) {
if (range.getLowEndPoint() instanceof BigDecimal bigDecimal) {
toPop... | @Test
void evaluateUnaryTestsForNumberRange() {
List<String> toRange = Arrays.asList("(>1)", "(<=10)");
List<RangeNode> ranges = getBaseNodes(toRange, RangeNode.class);
Schema toPopulate = OASFactory.createObject(Schema.class);
RangeNodeSchemaMapper.populateSchemaFromListOfRanges(toP... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestRecordingPosition()
{
internalEncodeLogHeader(buffer, 0, 12, 32, () -> 10_000_000_000L);
final RecordingPositionRequestEncoder requestEncoder = new RecordingPositionRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder)
... |
public static boolean isSameWeek(final Date date1, final Date date2, boolean isMon) {
if (date1 == null || date2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return CalendarUtil.isSameWeek(calendar(date1), calendar(date2), isMon);
} | @Test
public void isSameWeekTest() {
// 周六与周日比较
final boolean isSameWeek = DateUtil.isSameWeek(DateTime.of("2022-01-01", "yyyy-MM-dd"), DateTime.of("2022-01-02", "yyyy-MM-dd"), true);
assertTrue(isSameWeek);
// 周日与周一比较
final boolean isSameWeek1 = DateUtil.isSameWeek(DateTime.of("2022-01-02", "yyyy-MM-dd"), D... |
@Override
public void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
// Charset is a global setting on Oracle, it can't be set on a specified schema with a
// different value. To not block users who already have a SonarQube schema, charset
// is verified only on fr... | @Test
public void fresh_install_verifies_utf8_charset() throws Exception {
answerCharset("UTF8");
underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL);
} |
@Override
public double getWeight(int source, int target) {
return graph[source][target];
} | @Test
public void testGetWeight() {
System.out.println("getWeight");
assertEquals(0.0, g1.getWeight(1, 2), 1E-10);
assertEquals(0.0, g1.getWeight(1, 1), 1E-10);
assertEquals(1.0, g2.getWeight(1, 2), 1E-10);
assertEquals(1.0, g2.getWeight(2, 1), 1E-10);
assertEquals(... |
@Override
public boolean retainAll(Collection<?> c) {
boolean changed = false;
for (Iterator<?> iterator = iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
if (!c.contains(object)) {
iterator.remove();
changed = true... | @Test
public void testRetainAll() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
for (int i = 0; i < 200; i++) {
set.add(i);
}
Assertions.assertTrue(set.retainAll(Arrays.asList(1, 2)));
Assertions.assertEquals(2, set.size());
} |
@Override
public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff)
throws IOException, InterruptedException {
IOException lastException = null;
do {
try {
Collection<Metadata> files = FileSystems.match(filePattern).metadata();
LOG.debug(
"Found file(s... | @Test
public void testReadWithRetriesFailsWhenOutputDirEmpty() throws Exception {
FilePatternMatchingShardedFile shardedFile = new FilePatternMatchingShardedFile(filePattern);
thrown.expect(IOException.class);
thrown.expectMessage(containsString("Unable to read file(s) after retrying"));
shardedFile.... |
public Duration cacheMinTimeToLive() {
return cacheMinTimeToLive;
} | @Test
void cacheMinTimeToLive() {
assertThat(builder.build().cacheMinTimeToLive()).isEqualTo(DEFAULT_CACHE_MIN_TIME_TO_LIVE);
Duration cacheMinTimeToLive = Duration.ofSeconds(5);
builder.cacheMinTimeToLive(cacheMinTimeToLive);
assertThat(builder.build().cacheMinTimeToLive()).isEqualTo(cacheMinTimeToLive);
} |
@Override
@TpsControl(pointName = "HealthCheck")
public HealthCheckResponse handle(HealthCheckRequest request, RequestMeta meta) {
return new HealthCheckResponse();
} | @Test
void testHandle() {
HealthCheckRequestHandler handler = new HealthCheckRequestHandler();
HealthCheckResponse response = handler.handle(null, null);
assertNotNull(response);
} |
public String defaultRemoteUrl() {
final String sanitizedUrl = sanitizeUrl();
try {
URI uri = new URI(sanitizedUrl);
if (uri.getUserInfo() != null) {
uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri... | @Test
void shouldNotModifyAbsoluteFilePaths() {
assertThat(new HgUrlArgument("/tmp/foo").defaultRemoteUrl(), is("/tmp/foo"));
} |
static BigtableReadOptions translateToBigtableReadOptions(
BigtableReadOptions readOptions, BigtableOptions options) {
BigtableReadOptions.Builder builder = readOptions.toBuilder();
builder.setWaitTimeout(
org.joda.time.Duration.millis(options.getRetryOptions().getReadPartialRowTimeoutMillis()));
... | @Test
public void testBigtableOptionsToBigtableReadOptions() throws Exception {
BigtableOptions options =
BigtableOptions.builder()
.setCallOptionsConfig(
CallOptionsConfig.builder()
.setReadRowsRpcAttemptTimeoutMs(100)
.setReadRowsRpcTim... |
@Override
public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
return filter(links.values(), link -> deviceId.equals(link.src().deviceId()));
} | @Test
public final void testGetDeviceEgressLinks() {
LinkKey linkId1 = LinkKey.linkKey(new ConnectPoint(DID1, P1), new ConnectPoint(DID2, P2));
LinkKey linkId2 = LinkKey.linkKey(new ConnectPoint(DID2, P2), new ConnectPoint(DID1, P1));
LinkKey linkId3 = LinkKey.linkKey(new ConnectPoint(DID1, ... |
LinkedList<RewriteOp> makeRewriteOps(
Iterable<String> srcFilenames,
Iterable<String> destFilenames,
boolean deleteSource,
boolean ignoreMissingSource,
boolean ignoreExistingDest)
throws IOException {
List<String> srcList = Lists.newArrayList(srcFilenames);
List<String> destL... | @Test
public void testMakeRewriteOpsWithOptions() throws IOException {
GcsOptions gcsOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = gcsOptions.getGcsUtil();
gcsUtil.maxBytesRewrittenPerCall = 1337L;
LinkedList<RewriteOp> rewrites =
gcsUtil.makeRewriteOps(makeStrings("s", 1), make... |
@Override
public KsqlVersionMetrics collectMetrics() {
final KsqlVersionMetrics metricsRecord = new KsqlVersionMetrics();
metricsRecord.setTimestamp(TimeUnit.MILLISECONDS.toSeconds(clock.millis()));
metricsRecord.setConfluentPlatformVersion(AppInfo.getVersion());
metricsRecord.setKsqlComponentType(mod... | @Test
public void testCollectMetricsAssignsCurrentTime() {
// Given:
final long t1 = 1000L;
final long t2 = 1001L;
when(clock.millis())
.thenReturn(TimeUnit.SECONDS.toMillis(t1))
.thenReturn(TimeUnit.SECONDS.toMillis(t2));
// When:
KsqlVersionMetrics metrics = basicCollector.c... |
public char toChar(String name) {
return toChar(name, '\u0000');
} | @Test
public void testToChar_String_char() {
System.out.println("toChar");
char expResult;
char result;
Properties props = new Properties();
props.put("value1", "f");
props.put("value2", "w");
props.put("empty", "");
props.put("str", "abc");
p... |
public void containsCell(
@Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value) {
containsCell(
Tables.<@Nullable Object, @Nullable Object, @Nullable Object>immutableCell(
rowKey, colKey, value));
} | @Test
public void containsCellFailure() {
ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val");
expectFailureWhenTestingThat(table).containsCell("row", "row", "val");
assertFailureKeys("value of", "expected to contain", "but was");
assertFailureValue("value of", "table... |
@Override
public Map<Consumer, List<Range>> getConsumerKeyHashRanges() {
Map<Consumer, List<Range>> result = new HashMap<>();
int start = 0;
for (Map.Entry<Integer, Consumer> entry: rangeMap.entrySet()) {
result.computeIfAbsent(entry.getValue(), key -> new ArrayList<>())
... | @Test
public void testGetConsumerKeyHashRanges() throws BrokerServiceException.ConsumerAssignException {
HashRangeAutoSplitStickyKeyConsumerSelector selector = new HashRangeAutoSplitStickyKeyConsumerSelector(2 << 5);
List<String> consumerName = Arrays.asList("consumer1", "consumer2", "consumer3", "c... |
@Override
public Statistics estimateStatistics() {
return estimateStatistics(SnapshotUtil.latestSnapshot(table, branch));
} | @Test
public void testEstimatedRowCount() throws NoSuchTableException {
sql(
"CREATE TABLE %s (id BIGINT, date DATE) USING iceberg TBLPROPERTIES('%s' = '%s')",
tableName, TableProperties.DEFAULT_FILE_FORMAT, format);
Dataset<Row> df =
spark
.range(10000)
.withC... |
@Override
public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId,
final ProcessorContext context,
final long streamTime) {
final TimestampedSegment segment = super.getOrCreateSegmentIfLiv... | @Test
public void shouldNotCreateSegmentThatIsAlreadyExpired() {
final long streamTime = updateStreamTimeAndCreateSegment(7);
assertNull(segments.getOrCreateSegmentIfLive(0, context, streamTime));
assertFalse(new File(context.stateDir(), "test/test.0").exists());
} |
@Override
public Optional<String> getPlacementGroup() {
return awsMetadataApi.placementGroupEc2();
} | @Test
public void getPlacementGroup() {
// given
String placementGroup = "placement-group";
String partitionNumber = "42";
given(awsMetadataApi.placementGroupEc2()).willReturn(Optional.of(placementGroup));
given(awsMetadataApi.placementPartitionNumberEc2()).willReturn(Optiona... |
Subscription addSubscription(final String channel, final int streamId)
{
return addSubscription(channel, streamId, defaultAvailableImageHandler, defaultUnavailableImageHandler);
} | @Test
@InterruptAfter(5)
void addSubscriptionShouldTimeoutWithoutOperationSuccessful()
{
assertThrows(DriverTimeoutException.class, () -> conductor.addSubscription(CHANNEL, STREAM_ID_1));
} |
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 testCalculateAvgWithCpuAndMem() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 2)));
NormalizedResources usedResources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU... |
public Integer doCall() throws Exception {
if (name == null && label == null && filePath == null) {
printer().println("Name or label selector must be set");
return 1;
}
if (label == null) {
String projectName;
if (name != null) {
p... | @Test
public void shouldGetPodLogs() throws Exception {
Pod pod = new PodBuilder()
.withNewMetadata()
.withName("pod")
.withLabels(Collections.singletonMap(BaseTrait.INTEGRATION_LABEL, "routes"))
.endMetadata()
.withNewStatus()
... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void returnOnCompleteUsingCompletable() throws InterruptedException {
RetryConfig config = retryConfig();
Retry retry = Retry.of("testName", config);
RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);
doNothing()
.doThrow(new HelloWorldEx... |
@Override
public void promoteJobPartitions(Collection<ResultPartitionID> partitionsToPromote) {
LOG.debug("Promoting Job Partitions {}", partitionsToPromote);
if (partitionsToPromote.isEmpty()) {
return;
}
final Collection<PartitionTrackerEntry<JobID, TaskExecutorPartit... | @Test
void promoteJobPartitions() throws Exception {
final TestingShuffleEnvironment testingShuffleEnvironment = new TestingShuffleEnvironment();
final CompletableFuture<Collection<ResultPartitionID>> shuffleReleaseFuture =
new CompletableFuture<>();
testingShuffleEnvironment... |
@Override
public String[] getParameterValues(String name) {
return stringMap.get(name);
} | @Test
void testGetParameterValues() {
String[] values = reuseHttpServletRequest.getParameterValues("value");
assertNotNull(values);
assertEquals(1, values.length);
assertEquals("123", values[0]);
} |
public static void verifyPrecondition(boolean assertionResult, String errorMessage) {
if (!assertionResult) {
throw new RuntimeException(errorMessage);
}
} | @Test
public void testVerifyPrecondition() {
verifyPrecondition(true, "");
} |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateMultiStatsWhenAllAvailable() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3");
ColumnStatisticsData data1 = new ColStatsBuilder<>(Decimal.class).numNulls(1).numDVs(3)
.low(ONE).high(THREE).hll(1, 2, 3).kll(1, 2, 3).build();
C... |
public static void register(String name, Object instance) {
try {
Class<Object> mbeanInterface = guessMBeanInterface(instance);
ManagementFactory.getPlatformMBeanServer().registerMBean(new StandardMBean(instance, mbeanInterface), new ObjectName(name));
} catch (MalformedObjectNameException | NotCom... | @Test
public void register_fails_if_mbean_interface_can_not_be_found() {
assertThatThrownBy(() -> Jmx.register(FAKE_NAME, "not a mbean"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Can not find the MBean interface of class java.lang.String");
} |
@Override
public void flush() {
store.flush();
} | @Test
public void shouldFlushVersionedStore() {
givenWrapperWithVersionedStore();
wrapper.flush();
verify(versionedStore).flush();
} |
@Override
public void handle(final ConsumerRecord<String, Bytes> record) {
try {
if (record.key().startsWith("register-")) {
serviceReportProperties(InstanceProperties.parseFrom(record.value().get()));
} else {
keepAlive(InstancePingPkg.parseFrom(recor... | @Test
public void testHandler() {
InstanceProperties properties = InstanceProperties.newBuilder()
.setService(SERVICE)
.setServiceInstance(SERVICE_INSTANCE)
... |
static Multimap<String, Range<Integer>> extractHighlightRanges(Map<String, List<String>> highlight) {
if (highlight == null || highlight.isEmpty()) {
return ImmutableListMultimap.of();
}
final ImmutableListMultimap.Builder<String, Range<Integer>> builder = ImmutableListMultimap.build... | @Test
public void brokenHighlight() throws Exception {
final Map<String, List<String>> highlights = ImmutableMap.of(
"message", ImmutableList.of("/<em>usr</em>/sbin</em>/cron[22390]<em>: (root) CMD (/<em>usr</em>/libexec/atrun)")
);
final Multimap<String, Range<Integer>> res... |
@Override
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.size() < 2) {
printInfo(err);
return 1;
}
int index = 0;
String input = args.get(index);
String option = "all";
if ("-o".equals(input)) {
option = args... | @Test
void repairAfterCorruptBlock() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "after", corruptBlockFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 2 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 5... |
public Point<T> build() {
requireNonNull(epochTime, "Points must have a time");
requireNonNull(latitude, "Points must have a latitude");
requireNonNull(longitude, "Points must have a longitude");
Position pos = new Position(
Instant.ofEpochMilli(epochTime), LatLong.of(latitu... | @Test
public void testCopier() {
Point<String> testPoint = getTestPoint();
Point<String> copiedPoint = (new PointBuilder<>(testPoint)).build();
assertThat(testPoint, is(copiedPoint));
} |
public static boolean validHostPattern(String address) {
return VALID_HOST_CHARACTERS.matcher(address).matches();
} | @Test
public void testHostPattern() {
assertTrue(validHostPattern("127.0.0.1"));
assertTrue(validHostPattern("mydomain.com"));
assertTrue(validHostPattern("MyDomain.com"));
assertTrue(validHostPattern("My_Domain.com"));
assertTrue(validHostPattern("::1"));
assertTrue(... |
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("x=");
stringBuilder.append(this.tileX);
stringBuilder.append(", y=");
stringBuilder.append(this.tileY);
stringBuilder.append(", z=");
stringBuilder.ap... | @Test
public void toStringTest() {
Tile tile = new Tile(1, 2, (byte) 3, TILE_SIZE);
Assert.assertEquals(TILE_TO_STRING, tile.toString());
} |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testExponentialRetry() throws UnreliableException {
UnreliableInterface unreliable = (UnreliableInterface)
RetryProxy.create(UnreliableInterface.class, unreliableImpl,
exponentialBackoffRetry(5, 1L, TimeUnit.NANOSECONDS));
unreliable.alwaysSucceeds();
unreli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.