focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public synchronized void resetExecutionProgressCheckIntervalMs() {
_executionProgressCheckIntervalMs = _requestedExecutionProgressCheckIntervalMs == null ? _defaultExecutionProgressCheckIntervalMs
: _requestedExecutionProgressCheckIntervalMs;
LOG.info("ExecutionProgressCheckInterval has reset to {}, whi... | @Test
public void testResetExecutionProgressCheckIntervalMs() {
KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(getExecutorProperties());
Executor executor = new Executor(config, null, new MetricRegistry(), EasyMock.mock(MetadataClient.class),
null, EasyMock.mock(AnomalyDetectorManager.... |
public void init() {
this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
ApolloThreadFactory
.create("DatabaseDiscoveryWithCache", true)
);
scheduledExecutorService.scheduleAtFixedRate(this::updateCacheTask,
SYNC_TASK_PERIOD_IN_SECOND, SYNC_TASK_PERIOD_IN_... | @Test
void init() {
DatabaseDiscoveryClient client = Mockito.mock(DatabaseDiscoveryClient.class);
DatabaseDiscoveryClientMemoryCacheDecoratorImpl decorator
= new DatabaseDiscoveryClientMemoryCacheDecoratorImpl(client);
decorator.init();
} |
public abstract Map<String, String> properties(final Map<String, String> defaultProperties, final long additionalRetentionMs); | @Test
public void shouldUseSuppliedConfigsForUnwindowedUnversionedChangelogConfig() {
final Map<String, String> configs = new HashMap<>();
configs.put("retention.ms", "1000");
configs.put("retention.bytes", "10000");
configs.put("message.timestamp.type", "LogAppendTime");
fi... |
public void deleteInstanceMetadata(Service service, String metadataId) {
MetadataOperation<InstanceMetadata> operation = buildMetadataOperation(service);
operation.setTag(metadataId);
WriteRequest operationLog = WriteRequest.newBuilder().setGroup(Constants.INSTANCE_METADATA)
.set... | @Test
void testDeleteInstanceMetadata() {
assertThrows(NacosRuntimeException.class, () -> {
String metadataId = "metadataId";
namingMetadataOperateService.deleteInstanceMetadata(service, metadataId);
Mockito.verify(service).getNamespace();
Mockito... |
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(PushNotification pushNotification) {
Message.Builder builder = Message.builder()
.setToken(pushNotification.deviceToken())
.setAndroidConfig(AndroidConfig.builder()
.setPriority(pushNotification.urgent() ? ... | @Test
void testSendMessage() {
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true);
final SettableApiFuture<String> sendFuture = SettableApiFuture.create();
sendFuture.set("message-id... |
UriEndpoint createUriEndpoint(String url, boolean isWs) {
return createUriEndpoint(url, isWs, connectAddress);
} | @Test
void createUriEndpointIPv6Address() {
String test1 = this.builder.host("::1")
.port(8080)
.build()
.createUriEndpoint("/foo", false)
.toExternalForm();
String test2 = this.builder.host("::1")
.port(8080)
.build()
.createUriEndpoint("/foo", true)
.toExternalForm();
assertTha... |
static Properties adminClientConfiguration(String bootstrapHostnames, PemTrustSet kafkaCaTrustSet, PemAuthIdentity authIdentity, Properties config) {
if (config == null) {
throw new InvalidConfigurationException("The config parameter should not be null");
}
config.setProperty(Adm... | @Test
public void testTlsConnection() {
Properties config = DefaultAdminClientProvider.adminClientConfiguration("my-kafka:9092", mockPemTrustSet(), null, new Properties());
assertThat(config.size(), is(8));
assertDefaultConfigs(config);
assertThat(config.get(AdminClientConfig.SECURI... |
@Override
public void validate(final String methodName, final Class<?>[] parameterTypes, final Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (Objects.nonNull(methodClass)) {
groups.add(methodCl... | @Test
public void testItWithMapArg() throws Exception {
final Map<String, String> map = new HashMap<>();
map.put("key", "value");
apacheDubboClientValidatorUnderTest.validate(
"methodFive", new Class<?>[]{Map.class}, new Object[]{map});
} |
@SuppressWarnings("unchecked")
@SneakyThrows(ReflectiveOperationException.class)
public static <T extends ShardingAlgorithm> T newInstance(final String shardingAlgorithmClassName, final Class<T> superShardingAlgorithmClass, final Properties props) {
Class<?> algorithmClass = Class.forName(shardingAlgori... | @Test
void assertNewInstance() {
assertThat(ClassBasedShardingAlgorithmFactory.newInstance(ClassBasedStandardShardingAlgorithmFixture.class.getName(), StandardShardingAlgorithm.class, new Properties()),
instanceOf(ClassBasedStandardShardingAlgorithmFixture.class));
} |
@Override
public void rollback() throws SQLException {
for (TransactionHook each : transactionHooks) {
each.beforeRollback(connection.getCachedConnections().values(), getTransactionContext());
}
if (connection.getConnectionSession().getTransactionStatus().isInTransaction()) {
... | @Test
void assertRollbackForDistributedTransaction() throws SQLException {
ContextManager contextManager = mockContextManager(TransactionType.XA);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
newBackendTransactionManager(TransactionType.XA, true);
... |
@Override
public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) {
ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
result.setOrder(true);
List<MessageExt> msgs = new ArrayList<>();
msgs.add(msg);
MessageQueue m... | @Test
public void testConsumeMessageDirectly_WithNoException() {
Map<ConsumeOrderlyStatus, CMResult> map = new HashMap();
map.put(ConsumeOrderlyStatus.SUCCESS, CMResult.CR_SUCCESS);
map.put(ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT, CMResult.CR_LATER);
map.put(ConsumeOrderl... |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
if (commandLine.hasOptio... | @Test
public void testExecute() throws SubCommandException {
ProducerConnectionSubCommand cmd = new ProducerConnectionSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-producer-group", "-t unit-test", String.format... |
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CeTask ceTask = (CeTask) o;
return uuid.equals(ceTask.uuid);
} | @Test
public void equals_and_hashCode_on_uuid() {
underTest.setType("TYPE_1").setUuid("UUID_1");
CeTask task1 = underTest.build();
CeTask task1bis = underTest.build();
CeTask task2 = new CeTask.Builder().setType("TYPE_1").setUuid("UUID_2").build();
assertThat(task1.equals(task1)).isTrue();
as... |
@Override
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
Map<String, Subscription> subscriptions) {
Map<String, List<TopicPartition>> assignment = new HashMap<>();
List<MemberInfo> memberInfoList = new Arra... | @Test
public void testStaticMemberRoundRobinAssignmentPersistent() {
// Have 3 static members instance1, instance2, instance3 to be persistent
// across generations. Their assignment shall be the same.
String consumer1 = "consumer1";
String instance1 = "instance1";
String con... |
public static QueryBuilder query(final String query) {
return new QueryBuilder() {
protected Query makeQueryObject(EntityManager entityManager) {
return entityManager.createQuery(query);
}
@Override
public String toString() {
retur... | @Test
public void testQueryBuilder() {
QueryBuilder q = QueryBuilder.query("select x from SendEmail x");
assertNotNull(q);
assertEquals("Query: select x from SendEmail x", q.toString());
} |
public static JClass resolveType(JClassContainer _package, String typeDefinition) {
try {
FieldDeclaration fieldDeclaration = (FieldDeclaration) JavaParser.parseBodyDeclaration(typeDefinition + " foo;");
ClassOrInterfaceType c = (ClassOrInterfaceType) ((ReferenceType) fieldDeclaration.g... | @Test
public void testResolveTypeCanHandleExtendsWildcard() {
final JCodeModel codeModel = new JCodeModel();
final JClass _class = TypeUtil.resolveType(codeModel.rootPackage(), "java.util.List<? extends java.lang.Number>");
assertThat(_class.erasure(), equalTo(codeModel.ref(List.class)));
... |
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
synchronized (redoService.getRegisteredInstances()) {
List<Instance> retainInstance = getRetainInstance(serviceName, groupName, instances);
... | @Test
void testBatchDeregisterServiceWithEmptyInstances() throws NacosException {
assertThrows(NacosException.class, () -> {
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST);
});
} |
public boolean putMessage(MessageExtBrokerInner messageInner) {
PutMessageResult putMessageResult = store.putMessage(messageInner);
if (putMessageResult != null
&& putMessageResult.getPutMessageStatus() == PutMessageStatus.PUT_OK) {
return true;
} else {
LOGGE... | @Test
public void testPutMessage() {
when(messageStore.putMessage(any(MessageExtBrokerInner.class)))
.thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
Boolean success = transactionBridge.putMessage(createMessageBrokerInne... |
@Override
public boolean localMember() {
return localMember;
} | @Test
public void testConstructor_withLocalMember_isFalse() {
MemberImpl member = new MemberImpl(address, MemberVersion.of("3.8.0"), false);
assertBasicMemberImplFields(member);
assertFalse(member.localMember());
} |
public PlanNodeStatsEstimate subtractSubsetStats(PlanNodeStatsEstimate superset, PlanNodeStatsEstimate subset)
{
if (superset.isOutputRowCountUnknown() || subset.isOutputRowCountUnknown()) {
return PlanNodeStatsEstimate.unknown();
}
double supersetRowCount = superset.getOutputRo... | @Test
public void testSubtractRowCount()
{
PlanNodeStatsEstimate unknownStats = statistics(NaN, NaN, NaN, NaN, StatisticRange.empty());
PlanNodeStatsEstimate first = statistics(40, NaN, NaN, NaN, StatisticRange.empty());
PlanNodeStatsEstimate second = statistics(10, NaN, NaN, NaN, Statis... |
@Override
public int getClassId() {
return PredicateDataSerializerHook.NOTEQUAL_PREDICATE;
} | @Test
public void getId_isConstant() {
NotEqualPredicate predicate = new NotEqualPredicate("bar", "foo");
int id = predicate.getClassId();
// make sure the ID has not been changed by accident
assertEquals(9, id);
} |
@Override
public void onProjectBranchesChanged(Set<Project> projects, Set<String> impactedBranches) {
checkNotNull(projects, "projects can't be null");
if (projects.isEmpty()) {
return;
}
Arrays.stream(listeners)
.forEach(safelyCallListener(listener -> listener.onProjectBranchesChanged(pr... | @Test
@UseDataProvider("oneOrManyProjects")
public void onProjectBranchesChanged_does_not_fail_if_there_is_no_listener(Set<Project> projects) {
assertThatNoException().isThrownBy(()-> underTestNoListeners.onProjectBranchesChanged(projects, emptySet()));
} |
@Override
public void createView(CreateViewStmt stmt) throws DdlException {
String dbName = stmt.getDbName();
String viewName = stmt.getTable();
Database db = getDb(stmt.getDbName());
if (db == null) {
ErrorReport.reportDdlException(ErrorCode.ERR_BAD_DB_ERROR, dbName);
... | @Test
public void testCreateView(@Mocked RESTCatalog restCatalog, @Mocked BaseView baseView,
@Mocked ImmutableSQLViewRepresentation representation) throws Exception {
UtFrameUtils.createMinStarRocksCluster();
AnalyzeTestUtil.init();
IcebergRESTCatalog icebergRE... |
@Override
public BarSeries aggregate(BarSeries series, String aggregatedSeriesName) {
final List<Bar> aggregatedBars = barAggregator.aggregate(series.getBarData());
return new BaseBarSeries(aggregatedSeriesName, aggregatedBars);
} | @Test
public void testAggregateWithNewName() {
final List<Bar> bars = new LinkedList<>();
final ZonedDateTime time = ZonedDateTime.of(2019, 6, 12, 4, 1, 0, 0, ZoneId.systemDefault());
final Bar bar0 = new MockBar(time, 1d, 2d, 3d, 4d, 5d, 6d, 7, numFunction);
final Bar bar1 = new Mo... |
protected Map<String, String[]> generateParameterMap(MultiValuedTreeMap<String, String> qs, ContainerConfig config) {
Map<String, String[]> output;
Map<String, List<String>> formEncodedParams = getFormUrlEncodedParametersMap();
if (qs == null) {
// Just transform the List<String> v... | @Test
void parameterMapWithMultipleValues_generateParameterMap_validQuery() {
AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(multipleParams, mockContext, null, config);
Map<String, String[]> paramMap = null;
try {
paramMap = request.generateParameterMap(requ... |
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 testParseDynamicVoterWithoutId2() {
assertEquals("Invalid @ at beginning of dynamic voter string.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("@localhost:8020:K90IZ-0DRNazJ49kCZ1EMQ")).
getMessage());
} |
public <UpdateT> List<UpdateT> extractUpdates(
boolean delta, CounterUpdateExtractor<UpdateT> extractors) {
return extractUpdatesImpl(delta, false, extractors);
} | @Test
public void testExtractUpdates() {
CounterSet deltaSet = new CounterSet();
CounterSet cumulativeSet = new CounterSet();
CounterUpdateExtractor<?> updateExtractor = Mockito.mock(CounterUpdateExtractor.class);
Counter<Long, Long> delta1 = deltaSet.longSum(name1);
Counter<Long, Long> cumulati... |
protected void validatePartitionedTopicName(String tenant, String namespace, String encodedTopic) {
// first, it has to be a validate topic name
validateTopicName(tenant, namespace, encodedTopic);
// second, "-partition-" is not allowed
if (encodedTopic.contains(TopicName.PARTITIONED_TOP... | @Test
public void testValidatePartitionedTopicNameInvalid() {
String tenant = "test-tenant";
String namespace = "test-namespace";
String topic = Codec.encode("test-topic-partition-0");
AdminResource resource = mockResource();
try {
resource.validatePartitionedTop... |
@Override
public String readSource() throws Exception {
CompletableFuture<GetResponse> responseFuture = client.getKVClient().get(ByteSequence.from(key, charset));
List<KeyValue> kvs = responseFuture.get().getKvs();
return kvs.size() == 0 ? null : kvs.get(0).getValue().toString(charset);
... | @Test
public void testReadSource() throws Exception {
EtcdDataSource dataSource = new EtcdDataSource("foo", value -> value);
KV kvClient = Client.builder()
.endpoints(endPoints)
.build().getKVClient();
kvClient.put(ByteSequence.from("foo".getBytes()), ByteSeq... |
@Override
public boolean isInputConsumable(
SchedulingExecutionVertex executionVertex,
Set<ExecutionVertexID> verticesToSchedule,
Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) {
for (ConsumedPartitionGroup consumedPartitionGroup :
executionVe... | @Test
void testUpstreamNotScheduledHybridInput() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
final List<TestingSchedulingExecutionVertex> producers =
topology.addExecutionVertices().withParallelism(2).finish();
final List<TestingSchedulingE... |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_empty() {
assertThat(resolve(""), equalTo(""));
} |
@Override
public ManagedChannel shutdown() {
ArrayList<ManagedChannel> channels = new ArrayList<>();
synchronized (this) {
shutdownStarted = true;
channels.addAll(usedChannels);
channels.addAll(channelCache);
}
for (ManagedChannel channel : channels) {
channel.shutdown();
}... | @Test
public void testShutdown() throws Exception {
ManagedChannel mockChannel = mock(ManagedChannel.class);
when(channelSupplier.get()).thenReturn(mockChannel);
ClientCall<Object, Object> mockCall1 = mock(ClientCall.class);
ClientCall<Object, Object> mockCall2 = mock(ClientCall.class);
when(mockC... |
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException {
final List<MavenArtifact> result = new ArrayList<>();
try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
JsonParser ... | @Test
public void shouldProcessCorrectlyArtifactoryAnswer() throws IOException {
// Given
Dependency dependency = new Dependency();
dependency.setSha1sum("c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0f");
dependency.setSha256sum("512b4bf6927f4864acc419b8c5109c23361c30ed1f5798170248d33040de... |
@Override
public void put(final Bytes key,
final byte[] valueAndTimestamp) {
wrapped().put(key, valueAndTimestamp);
log(key, rawValue(valueAndTimestamp), valueAndTimestamp == null ? context.timestamp() : timestamp(valueAndTimestamp));
} | @Test
public void shouldPropagateDelete() {
store.put(hi, rawThere);
store.delete(hi);
assertThat(root.approximateNumEntries(), equalTo(0L));
assertThat(root.get(hi), nullValue());
} |
@Override
public void handleReply(Reply reply) {
if (failure.get() != null) {
return;
}
if (containsFatalErrors(reply.getErrors())) {
failure.compareAndSet(null, new IOException(formatErrors(reply)));
return;
}
long now = System.currentTime... | @Test
public void requireThatXML2JsonFeederWorks() throws Throwable {
ByteArrayOutputStream dump = new ByteArrayOutputStream();
assertFeed(new FeederParams().setDumpStream(dump),
"<vespafeed>" +
" <document documenttype='simple' documentid='id:simple:simple... |
@Override
public NacosGrpcProtocolNegotiator build() {
Properties properties = EnvUtil.getProperties();
RpcServerTlsConfig config = RpcServerTlsConfigFactory.getInstance().createClusterConfig(properties);
if (config.getEnableTls()) {
SslContext sslContext = DefaultTlsContextBuild... | @Test
void testBuildTlsEnabled() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".enableTls", "true");
properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".compatibility", "false");
properties.setProperty(RpcConstants.NACOS_PEER_RPC... |
public Tuple2<Long, Double> increase(String name, ImmutableMap<String, String> labels, Double value, long windowSize, long now) {
ID id = new ID(name, labels);
Queue<Tuple2<Long, Double>> window = windows.computeIfAbsent(id, unused -> new PriorityQueue<>());
synchronized (window) {
w... | @Test
public void testPT35S() {
double[] actuals = parameters().stream().mapToDouble(e -> {
Tuple2<Long, Double> increase = CounterWindow.INSTANCE.increase(
"test", ImmutableMap.<String, String>builder().build(), e._2,
Duration.parse("PT35S").getSeconds() * 1000, ... |
@Override
public NativeEntity<Output> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
Strin... | @Test
public void createNativeEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.OUTPUT_V1)
.data(objectMapper.convertValue(OutputEntity.create(
ValueReference.of("STDOUT"),
... |
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
long datetime = readDatetimeV2FromPayload(payload);
return 0L == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDatetime(columnDef, datetime, payload);
} | @Test
void assertReadWithoutFraction5() {
columnDef.setColumnMeta(5);
when(payload.readInt1()).thenReturn(0xfe, 0xf3, 0xff, 0x7e, 0xfb);
when(payload.getByteBuf()).thenReturn(byteBuf);
when(byteBuf.readUnsignedMedium()).thenReturn(999990);
LocalDateTime expected = LocalDateTi... |
public PathPrefixAuth() {
} | @Test
public void testPathPrefixAuth() {
String s = "[{\"clientId\":\"my-client\",\"clientSecret\":\"my-secret\",\"tokenUrl\":\"www.example.com/token\"}]";
List<PathPrefixAuth> pathPrefixAuths = null;
try {
pathPrefixAuths = Config.getInstance().getMapper().readValue(s, new TypeR... |
public static boolean in(Polygon p, EdgeIteratorState edge) {
BBox edgeBBox = GHUtility.createBBox(edge);
BBox polyBBOX = p.getBounds();
if (!polyBBOX.intersects(edgeBBox))
return false;
if (p.isRectangle() && polyBBOX.contains(edgeBBox))
return true;
retu... | @Test
public void testInRectangle() {
Polygon square = new Polygon(new double[]{0, 0, 20, 20}, new double[]{0, 20, 20, 0});
assertTrue(square.isRectangle());
BaseGraph g = new BaseGraph.Builder(1).create();
// (1,1) (2,2) (3,3)
// Polygon fully contains the edge and its BBo... |
public static String decode(byte[] data) {
return data == null ? null : new String(data, RpcConstants.DEFAULT_CHARSET);
} | @Test
public void decode() {
Assert.assertNull(StringSerializer.decode(null));
Assert.assertEquals("", StringSerializer.decode(new byte[0]));
Assert.assertEquals("11", StringSerializer.decode(StringSerializer.encode("11")));
} |
public static String wrap(String input, Formatter formatter) throws FormatterException {
return StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, input, formatter);
} | @Test
public void testAwkwardLineEndWrapping() throws Exception {
String input =
lines(
"class T {",
// This is a wide line, but has to be split in code because of 100-char limit.
" String s = someMethodWithQuiteALongNameThatWillGetUsUpCloseToTheColumnLimit() "
... |
@DeleteMapping(params = "delType=ids")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
public RestResult<Boolean> deleteConfigs(HttpServletRequest request, @RequestParam(value = "ids") List<Long> ids) {
String clientIp = RequestUtil.getRemoteIp(request);
String srcUser = Request... | @Test
void testDeleteConfigs() throws Exception {
List<ConfigInfo> resultInfos = new ArrayList<>();
String dataId = "dataId1123";
String group = "group34567";
String tenant = "tenant45678";
resultInfos.add(new ConfigInfo(dataId, group, tenant));
Mockito.when(... |
@Override
public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
LogicalOlapScanOperator logicalOlapScanOperator = (LogicalOlapScanOperator) input.getOp();
LogicalOlapScanOperator prunedOlapScanOperator = null;
if (logicalOlapScanOperator.getSelectedPartitionId... | @Test
public void transform2(@Mocked OlapTable olapTable, @Mocked RangePartitionInfo partitionInfo) {
FeConstants.runningUnitTest = true;
Partition part1 = new Partition(1, "p1", null, null);
Partition part2 = new Partition(2, "p2", null, null);
Partition part3 = new Partition(3, "p3... |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testNoResultsIfInitializing() {
buildDependencies();
// Intentionally call assign (vs. assignAndSeek) so that we don't set the position. The SubscriptionState
// will consider the partition as in the SubscriptionState.FetchStates.INITIALIZED state.
assign(topicAPar... |
@Override
protected @UnknownKeyFor @NonNull @Initialized SchemaTransform from(
JdbcWriteSchemaTransformConfiguration configuration) {
configuration.validate();
return new JdbcWriteSchemaTransform(configuration);
} | @Test
public void testWriteToTableWithJdbcTypeSpecified() throws SQLException {
JdbcWriteSchemaTransformProvider provider = null;
for (SchemaTransformProvider p : ServiceLoader.load(SchemaTransformProvider.class)) {
if (p instanceof JdbcWriteSchemaTransformProvider) {
provider = (JdbcWriteSchema... |
@Udf(schema = "ARRAY<STRUCT<K STRING, V INT>>")
public List<Struct> entriesInt(
@UdfParameter(description = "The map to create entries from") final Map<String, Integer> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
return entr... | @Test
public void shouldReturnNullListForNullMapInt() {
assertNull(entriesUdf.entriesInt(null, false));
} |
@Override
public Optional<String> getReturnTo(HttpRequest request) {
return getParameter(request, RETURN_TO_PARAMETER)
.flatMap(OAuth2AuthenticationParametersImpl::sanitizeRedirectUrl);
} | @Test
public void get_return_to_is_empty_when_no_value() {
when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie(AUTHENTICATION_COOKIE_NAME, "{}")});
Optional<String> redirection = underTest.getReturnTo(request);
assertThat(redirection).isEmpty();
} |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the fe... | @Test
void testApplyTransforms_simple_hosshoi_kar()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(56, 102, 91);
// when
List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("আমি"));
// then
assertEquals(glyphsAfterGsub, result);
... |
public static Set<Metric> mapFromDataProvider(TelemetryDataProvider<?> provider) {
switch (provider.getDimension()) {
case INSTALLATION -> {
return mapInstallationMetric(provider);
} case PROJECT -> {
return mapProjectMetric(provider);
} case USER -> {
return mapUserMetric(... | @Test
void mapFromDataProvider_whenAdhocInstallationProviderWithValue_shouldMapToMetric() {
TestTelemetryAdhocBean provider = new TestTelemetryAdhocBean(Dimension.INSTALLATION, true); // Force the value to be returned
Set<Metric> metrics = TelemetryMetricsMapper.mapFromDataProvider(provider);
List<Instal... |
public static String getValidFilePath(String inputPath) {
return getValidFilePath(inputPath, false);
} | @Test
public void getValidFilePath_writeToBlockedPath_throwsIllegalArgumentException() {
try {
SecurityUtils.getValidFilePath("/usr/lib/test.txt");
} catch (IllegalArgumentException e) {
return;
}
fail("Did not throw exception");
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilder() {
ByteArray hash = new ByteArray(1);
Block block = Block.builder()
.setResourceId("resource")
.setBlockHash(hash)
.setIndexInFile(1)
.setLines(2, 3)
.setUnit(4, 5)
.build();
assertThat(block.getResourceId(), is("resource"));
... |
@Override
public MapperResult getTenantIdList(MapperContext context) {
String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId()
+ "' GROUP BY tenant_id LIMIT " + context.getStartRow() + "," + context.getPageSize();
return new Mappe... | @Test
void testGetTenantIdList() {
MapperResult mapperResult = configInfoMapperByMySql.getTenantIdList(context);
assertEquals(mapperResult.getSql(), "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId()
+ "' GROUP BY tenant_id LIMIT " + star... |
boolean sendRecords() {
int processed = 0;
recordBatch(toSend.size());
final SourceRecordWriteCounter counter =
toSend.isEmpty() ? null : new SourceRecordWriteCounter(toSend.size(), sourceTaskMetricsGroup);
for (final SourceRecord preTransformRecord : toSend) {
... | @Test
public void testHeadersWithCustomConverter() throws Exception {
StringConverter stringConverter = new StringConverter();
SampleConverterWithHeaders testConverter = new SampleConverterWithHeaders();
createWorkerTask(stringConverter, testConverter, stringConverter, RetryWithToleranceOpe... |
public static void checkTenant(String tenant) throws NacosException {
if (StringUtils.isBlank(tenant) || !ParamUtils.isValid(tenant)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, TENANT_INVALID_MSG);
}
} | @Test
void testCheckTenantFail() throws NacosException {
Throwable exception = assertThrows(NacosException.class, () -> {
String tenant = "";
ParamUtils.checkTenant(tenant);
});
assertTrue(exception.getMessage().contains("tenant invalid"));
} |
public static String getDefaultHost(@Nullable String strInterface,
@Nullable String nameserver,
boolean tryfallbackResolution)
throws UnknownHostException {
if (strInterface == null || "default".equals(strInterface)) {
return cach... | @Test
public void testDefaultDnsServer() throws Exception {
String host = DNS.getDefaultHost(getLoopbackInterface(), DEFAULT);
Assertions.assertThat(host)
.isEqualTo(DNS.getDefaultHost(getLoopbackInterface()));
} |
public int getBlobServerPort() {
final int blobServerPort = KubernetesUtils.parsePort(flinkConfig, BlobServerOptions.PORT);
checkArgument(blobServerPort > 0, "%s should not be 0.", BlobServerOptions.PORT.key());
return blobServerPort;
} | @Test
void testGetBlobServerPortException1() {
flinkConfig.set(BlobServerOptions.PORT, "1000-2000");
String errMsg =
BlobServerOptions.PORT.key()
+ " should be specified to a fixed port. Do not support a range of ports.";
assertThatThrownBy(
... |
public static String input() {
return scanner().nextLine();
} | @Test
@Disabled
public void inputTest() {
Console.log("Please input something: ");
String input = Console.input();
Console.log(input);
} |
private WorkflowRun getRun() {
return PipelineRunImpl.findRun(runExternalizableId);
} | @Test
public void getRun_FirstFound() throws Exception {
try (MockedStatic<QueueUtil> queueUtilMockedStatic = Mockito.mockStatic(QueueUtil.class)) {
Mockito.when(QueueUtil.getRun(job, 1)).thenReturn(run);
WorkflowRun workflowRun = PipelineNodeImpl.getRun(job, 1);
assertE... |
public static ImmutableSet<HttpUrl> allSubPaths(String url) {
return allSubPaths(HttpUrl.parse(url));
} | @Test
public void allSubPaths_whenMultipleSubPathsWithParamsAndFragments_returnsExpectedUrl() {
assertThat(allSubPaths("http://localhost/a/b/c/?param=value¶m2=value2#abc"))
.containsExactly(
HttpUrl.parse("http://localhost/"),
HttpUrl.parse("http://localhost/a/"),
H... |
public static String getApplication(Invocation invocation, String defaultValue) {
if (invocation == null || invocation.getAttachments() == null) {
throw new IllegalArgumentException("Bad invocation instance");
}
return invocation.getAttachment(SENTINEL_DUBBO_APPLICATION_KEY, defaultV... | @Test(expected = IllegalArgumentException.class)
public void testGetApplicationNoAttachments() {
Invocation invocation = mock(Invocation.class);
when(invocation.getAttachments()).thenReturn(null);
when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
.... |
public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure<AppendEntriesResponse> closure) {
final Replicator r = (Replicator) id.lock();
if (r == null) {
RpcUtils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id));
retu... | @Test
public void testSendHeartbeat() {
final Replicator r = getReplicator();
this.id.unlock();
assertNull(r.getHeartbeatInFly());
final RpcRequests.AppendEntriesRequest request = createEmptyEntriesRequest(true);
Mockito.when(
this.rpcService.appendEntries(eq(thi... |
public static List<String> computeNameParts(String loggerName) {
List<String> partList = new ArrayList<String>();
int fromIndex = 0;
while (true) {
int index = getSeparatorIndexOf(loggerName, fromIndex);
if (index == -1) {
partList.add(loggerName.substrin... | @Test
public void dotAtLastPositionShouldReturnAListWithAnEmptyStringAsLastElement() {
List<String> witnessList = new ArrayList<String>();
witnessList.add("com");
witnessList.add("foo");
witnessList.add("");
List<String> partList = LoggerNameUtil.computeNameParts("com.foo.")... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_DifferentOrder() {
expectFailureWhenTestingThat(array(2.2f, 3.3f)).isEqualTo(array(3.3f, 2.2f));
} |
public Span nextSpan(TraceContextOrSamplingFlags extracted) {
if (extracted == null) throw new NullPointerException("extracted == null");
TraceContext context = extracted.context();
if (context != null) return newChild(context);
TraceIdContext traceIdContext = extracted.traceIdContext();
if (traceI... | @Test void localRootId_nextSpan_flags_sampled() {
TraceContextOrSamplingFlags flags = TraceContextOrSamplingFlags.SAMPLED;
localRootId(flags, flags, ctx -> tracer.nextSpan(ctx));
} |
@Override
public Long getValue() {
return longAdder.longValue();
} | @Test
public void getValue() {
assertThat(longCounter.getValue()).isEqualTo(INITIAL_VALUE);
} |
public String parse(Function<String, String> propertyMapping) {
init();
boolean inPrepare = false;
char[] expression = new char[128];
int expressionPos = 0;
while (next()) {
if (isPrepare()) {
inPrepare = true;
} else if (inPrepare && isP... | @Test
public void test() {
String result = TemplateParser.parse("test-${name}-${name}", Collections.singletonMap("name", "test"));
Assert.assertEquals(result, "test-test-test");
} |
public static <KLeftT, KRightT> KTableHolder<KLeftT> build(
final KTableHolder<KLeftT> left,
final KTableHolder<KRightT> right,
final ForeignKeyTableTableJoin<KLeftT, KRightT> join,
final RuntimeBuildContext buildContext
) {
final LogicalSchema leftSchema = left.getSchema();
final Logi... | @Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void shouldDoInnerJoinOnSubKey() {
// Given:
givenInnerJoin(leftMultiKey, L_KEY_2);
// When:
final KTableHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
final ArgumentCaptor<KsqlKeyExtractor> ksqlKeyExtractor
... |
public void putUserProperty(final String name, final String value) {
if (MessageConst.STRING_HASH_SET.contains(name)) {
throw new RuntimeException(String.format(
"The Property<%s> is used by system, input another please", name));
}
if (value == null || value.trim().i... | @Test(expected = IllegalArgumentException.class)
public void putUserNullNamePropertyWithException() throws Exception {
Message m = new Message();
m.putUserProperty(null, "val1");
} |
public void terminate(
WorkflowSummary workflowSummary,
StepRuntimeSummary runtimeSummary,
StepInstance.Status status) {
try {
StepRuntime.Result result =
getStepRuntime(runtimeSummary.getType())
.terminate(workflowSummary, cloneSummary(runtimeSummary));
Checks.... | @Test
public void testTerminate() {
StepRuntimeSummary summary =
StepRuntimeSummary.builder()
.type(StepType.NOOP)
.stepRetry(StepInstance.StepRetry.from(Defaults.DEFAULT_RETRY_POLICY))
.build();
runtimeManager.terminate(workflowSummary, summary, StepInstance.Status... |
public static TypeBuilder<Schema> builder() {
return new TypeBuilder<>(new SchemaCompletion(), new NameContext());
} | @Test
void nullObjectProp() {
assertThrows(AvroRuntimeException.class, () -> {
SchemaBuilder.builder().intBuilder().prop("nullProp", (Object) null).endInt();
});
} |
public IterableSubject asList() {
return checkNoNeedToDisplayBothValues("asList()").that(Chars.asList(checkNotNull(actual)));
} | @Test
public void asList() {
assertThat(array('a', 'q', 'z')).asList().containsAtLeast('a', 'z');
} |
protected static long extractTimestampAttribute(
String timestampAttribute, @Nullable Map<String, String> attributes) {
Preconditions.checkState(!timestampAttribute.isEmpty());
String value = attributes == null ? null : attributes.get(timestampAttribute);
checkArgument(
value != null,
... | @Test
public void timestampAttributeSetWithMissingAttributeThrowsError() {
thrown.expect(RuntimeException.class);
thrown.expectMessage("PubSub message is missing a value for timestamp attribute myAttribute");
Map<String, String> map = ImmutableMap.of("otherLabel", "whatever");
PubsubClient.extractTime... |
static void validateNewAcl(AclBinding binding) {
switch (binding.pattern().resourceType()) {
case UNKNOWN:
case ANY:
throw new InvalidRequestException("Invalid resourceType " +
binding.pattern().resourceType());
default:
bre... | @Test
public void testValidateNewAcl() {
AclControlManager.validateNewAcl(new AclBinding(
new ResourcePattern(TOPIC, "*", LITERAL),
new AccessControlEntry("User:*", "*", ALTER, ALLOW)));
assertEquals("Invalid patternType UNKNOWN",
assertThrows(InvalidRequestExcept... |
public static SchemaPath schemaPathFromId(String projectId, String schemaId) {
return new SchemaPath(projectId, schemaId);
} | @Test
public void schemaPathFromIdPathWellFormed() {
SchemaPath path = PubsubClient.schemaPathFromId("projectId", "schemaId");
assertEquals("projects/projectId/schemas/schemaId", path.getPath());
assertEquals("schemaId", path.getId());
} |
static String computeDetailsAsString(SearchRequest searchRequest) {
StringBuilder message = new StringBuilder();
message.append(String.format("ES search request '%s'", searchRequest));
if (searchRequest.indices().length > 0) {
message.append(String.format(ON_INDICES_MESSAGE, Arrays.toString(searchRequ... | @Test
public void should_format_IndexRequest() {
IndexRequest indexRequest = new IndexRequest()
.index("index-1")
.id("id-1");
assertThat(EsRequestDetails.computeDetailsAsString(indexRequest))
.isEqualTo("ES index request for key 'id-1' on index 'index-1'");
} |
public ExecBinding getBinding() {
return binding;
} | @Test
@DirtiesContext
public void testCreateEndpointCustomBinding() throws Exception {
ExecEndpoint e = createExecEndpoint("exec:test?binding=#customBinding");
assertSame(customBinding, e.getBinding(),
"Expected is the custom customBinding reference from the application context")... |
@VisibleForTesting
String upload(Configuration config, String artifactUriStr)
throws IOException, URISyntaxException {
final URI artifactUri = PackagedProgramUtils.resolveURI(artifactUriStr);
if (!"local".equals(artifactUri.getScheme())) {
return artifactUriStr;
}
... | @Test
void testRemoteUri() throws Exception {
config.removeConfig(KubernetesConfigOptions.LOCAL_UPLOAD_TARGET);
String remoteUri = "s3://my-bucket/my-artifact.jar";
String finalUri = artifactUploader.upload(config, remoteUri);
assertThat(finalUri).isEqualTo(remoteUri);
} |
@Override
public void open() throws Exception {
super.open();
collector = new TimestampedCollector<>(output);
context = new ContextImpl(userFunction);
internalTimerService =
getInternalTimerService(CLEANUP_TIMER_NAME, StringSerializer.INSTANCE, this);
} | @TestTemplate
void testReturnsCorrectTimestamp() throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new IntervalJoinOperator<>(
-1,
1,
true,
true,... |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
// Automatically detect the character encoding
try (AutoDetectReader reader = new AutoDetectReader(CloseShieldInpu... | @Test
public void testUsingCharsetInContentTypeHeader() throws Exception {
// Could be ISO 8859-1 or ISO 8859-15 or ...
// u00e1 is latin small letter a with acute
final String test2 = "the name is \u00e1ndre";
Metadata metadata = new Metadata();
parser.parse(new ByteArrayIn... |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentImportExecutor,
TokensAndUrlAuthData authData,
PhotosContainerResource resource)
throws Exception {
// Ensure credential is populated
getOrCreateCredential(authData);
monitor.debug(
() -> Stri... | @Test
public void testImportItemPermissionDenied() throws Exception {
List<PhotoAlbum> albums =
ImmutableList.of(new PhotoAlbum("id1", "album1.", "This is a fake albumb"));
PhotosContainerResource data = new PhotosContainerResource(albums, null);
Call call = mock(Call.class);
doReturn(call).... |
public boolean load() {
String fileName = null;
try {
fileName = this.configFilePath();
String jsonString = MixAll.file2String(fileName);
if (null == jsonString || jsonString.length() == 0) {
return this.loadBak();
} else {
... | @Test
public void testLoad() throws Exception {
ConfigManager testConfigManager = buildTestConfigManager();
File file = createAndWriteFile(testConfigManager.configFilePath());
assertTrue(testConfigManager.load());
file.delete();
File fileBak = createAndWriteFile(testConfigMan... |
public ConfigurationProperty getProperty(final String key) {
return stream().filter(item -> item.getConfigurationKey().getName().equals(key)).findFirst().orElse(null);
} | @Test
void shouldGetNullIfPropertyNotFoundForGivenKey() {
Configuration config = new Configuration();
assertThat(config.getProperty("key2")).isNull();
} |
@Override
public String formatDouble(Locale locale, Double value) {
NumberFormat format = DecimalFormat.getNumberInstance(locale);
format.setMinimumFractionDigits(1);
format.setMaximumFractionDigits(1);
return format.format(value);
} | @Test
public void format_double() {
assertThat(underTest.formatDouble(Locale.FRENCH, 10.56)).isEqualTo("10,6");
assertThat(underTest.formatDouble(Locale.FRENCH, 10d)).isEqualTo("10,0");
} |
public static FormattingTuple format(String messagePattern, Object arg) {
return arrayFormat(messagePattern, new Object[]{arg});
} | @Test
public void verifyOneParameterIsHandledCorrectly() {
String result = MessageFormatter.format("Value is {}.", 3).getMessage();
assertEquals("Value is 3.", result);
result = MessageFormatter.format("Value is {", 3).getMessage();
assertEquals("Value is {", result);
resul... |
public Collection<PlanCoordinator> coordinators() {
return Collections.unmodifiableCollection(mCoordinators.values());
} | @Test
public void testAddAndPurge() throws Exception {
assertEquals("tracker should be empty", 0, mTracker.coordinators().size());
fillJobTracker(CAPACITY);
try {
addJob(100);
fail("Should have failed to add a job over capacity");
} catch (ResourceExhaustedException e) {
// Empty on ... |
public static boolean tryFillGap(
final UnsafeBuffer logMetaDataBuffer,
final UnsafeBuffer termBuffer,
final int termId,
final int gapOffset,
final int gapLength)
{
int offset = (gapOffset + gapLength) - FRAME_ALIGNMENT;
while (offset >= gapOffset)
{
... | @Test
void shouldFillGapAfterExistingFrame()
{
final int gapOffset = 128;
final int gapLength = 64;
dataFlyweight
.sessionId(SESSION_ID)
.termId(TERM_ID)
.streamId(STREAM_ID)
.flags(UNFRAGMENTED)
.frameLength(gapOffset);
... |
public PaginationContext createPaginationContext(final LimitSegment limitSegment, final List<Object> params) {
return new PaginationContext(limitSegment.getOffset().orElse(null), limitSegment.getRowCount().orElse(null), params);
} | @Test
void assertPaginationContextCreatedProperlyWhenOffsetAndRowCountAreBothNull() {
PaginationContext paginationContext = new LimitPaginationContextEngine().createPaginationContext(new LimitSegment(0, 10, null, null), Collections.emptyList());
assertFalse(paginationContext.isHasPagination());
... |
public static boolean isRetryOrDlqTopic(String topic) {
if (StringUtils.isBlank(topic)) {
return false;
}
return topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX) || topic.startsWith(MixAll.DLQ_GROUP_TOPIC_PREFIX);
} | @Test
public void testIsRetryOrDlqTopicWithDlqTopic() {
String topic = MixAll.DLQ_GROUP_TOPIC_PREFIX + "TestTopic";
boolean result = BrokerMetricsManager.isRetryOrDlqTopic(topic);
assertThat(result).isTrue();
} |
public static FixedWindows of(Duration size) {
return new FixedWindows(size, Duration.ZERO);
} | @Test
public void testSimpleFixedWindow() throws Exception {
Map<IntervalWindow, Set<String>> expected = new HashMap<>();
expected.put(new IntervalWindow(new Instant(0), new Instant(10)), set(1, 2, 5, 9));
expected.put(new IntervalWindow(new Instant(10), new Instant(20)), set(10, 11));
expected.put(ne... |
@Override
public UrlPattern doGetPattern() {
return UrlPattern.builder()
.includes(includeUrls)
.excludes(excludeUrls)
.build();
} | @Test
public void match_undeclared_web_services_starting_with_api() {
initWebServiceEngine(newWsUrl("api/issues", "search"));
assertThat(underTest.doGetPattern().matches("/api/resources/index")).isTrue();
assertThat(underTest.doGetPattern().matches("/api/user_properties")).isTrue();
} |
public void generateAcknowledgementPayload(
MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode)
throws MllpAcknowledgementGenerationException {
generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null);
} | @Test
public void testGenerateAcknowledgementPayloadTimestamp() throws Exception {
MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
hl7util.generateAcknowledgementPayload(mllpSocketBuffer, TEST_MESSAGE.getBytes(), "AA");
String actualMsh7Field = mllpSocketBu... |
public PutObjectResult putObject(String key, String localFilePath) {
PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
new File(localFilePath));
return cosClient.putObject(putObjectRequest);
} | @Test
void putObject() {
cosManager.putObject("test", "test.json");
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldCreateMigrationsStream() {
// When:
final int status = command.command(config, cfg -> client);
// Then:
assertThat(status, is(0));
verify(client).executeStatement(EXPECTED_CS_STATEMENT);
} |
public static void smooth(PointList geometry, double maxWindowSize) {
if (geometry.size() <= 2) {
// geometry consists only of tower nodes, there are no pillar nodes to be smoothed in between
return;
}
// calculate the distance between all points once here to avoid repea... | @Test
public void testTwoPoints() {
// consists of only two tower nodes and no pillar nodes
// elevation must stay unchanged
PointList pl = new PointList(2, true);
pl.add(0, 0, -1);
pl.add(1, 1, 100);
EdgeElevationSmoothingMovingAverage.smooth(pl, 150.0);
asse... |
@Override
public long read() {
return gaugeSource.read();
} | @Test
public void whenCreatedForDynamicLongMetricWithProvidedValue() {
SomeObject someObject = new SomeObject();
someObject.longField = 42;
metricsRegistry.registerDynamicMetricsProvider((descriptor, context) -> context
.collect(descriptor.withPrefix("foo"), "longField", INFO... |
@Override
@NotNull
public BTreeMutable getMutableCopy() {
final BTreeMutable result = new BTreeMutable(this);
result.addExpiredLoggable(rootLoggable);
return result;
} | @Test
public void testPutOverwriteTreeWithoutDuplicates() {
// add existing key to tree that supports duplicates
tm = new BTreeEmpty(log, createTestSplittingPolicy(), false, 1).getMutableCopy();
for (int i = 0; i < 100; i++) {
getTreeMutable().put(kv(i, "v" + i));
}
... |
@Override
public boolean ensureCapacity(int numAdditionalBuffers) {
checkIsInitialized();
final int numRequestedByGuaranteedReclaimableOwners =
tieredMemorySpecs.values().stream()
.filter(TieredStorageMemorySpec::isGuaranteedReclaimable)
... | @Test
void testEnsureCapacity() throws IOException {
final int numBuffers = 5;
final int guaranteedReclaimableBuffers = 3;
BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
TieredStorageMemoryManagerImpl storageMemoryManager =
createStorage... |
public List<QueryMetadata> sql(final String sql) {
return sql(sql, Collections.emptyMap());
} | @Test
public void shouldThrowIfParseFails() {
// Given:
when(ksqlEngine.parse(any()))
.thenThrow(new KsqlException("Bad tings happen"));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> ksqlContext.sql("Some SQL", SOME_PROPERTIES)
);
// Then:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.