focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static List<TimeSlot> split(TimeSlot timeSlot, SegmentInMinutes unit) {
TimeSlot normalizedSlot = normalizeToSegmentBoundaries(timeSlot, unit);
return new SlotToSegments().apply(normalizedSlot, unit);
} | @Test
void slotsAreNormalizedBeforeSplitting() {
//given
Instant start = Instant.parse("2023-09-09T00:10:00Z");
Instant end = Instant.parse("2023-09-09T00:59:00Z");
TimeSlot timeSlot = new TimeSlot(start, end);
SegmentInMinutes oneHour = SegmentInMinutes.of(60, FIFTEEN_MINUTE... |
@Override
public List<Intent> compile(PathIntent intent, List<Intent> installable) {
List<FlowRule> rules = new LinkedList<>();
List<DeviceId> devices = new LinkedList<>();
compile(this, intent, rules, devices);
return ImmutableList.of(new FlowRuleIntent(appId,
... | @Test
public void testCompile() {
sut.activate();
List<Intent> compiled = sut.compile(intent, Collections.emptyList());
assertThat(compiled, hasSize(1));
assertThat("key is inherited",
compiled.stream().map(Intent::key).collect(Collectors.toList()),
... |
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 testRetryInterruptible() throws Throwable {
final UnreliableInterface unreliable = (UnreliableInterface)
RetryProxy.create(UnreliableInterface.class, unreliableImpl,
retryUpToMaximumTimeWithFixedSleep(10, 10, TimeUnit.SECONDS));
final CountDownLatch latch = new Count... |
@Nullable
public static PipelineBreakerResult executePipelineBreakers(OpChainSchedulerService scheduler,
MailboxService mailboxService, WorkerMetadata workerMetadata, StagePlan stagePlan,
Map<String, String> opChainMetadata, long requestId, long deadlineMs) {
PipelineBreakerContext pipelineBreakerCont... | @Test
public void shouldReturnBlocksUponNormalOperation() {
MailboxReceiveNode mailboxReceiveNode = getPBReceiveNode(1);
StagePlan stagePlan = new StagePlan(mailboxReceiveNode, _stageMetadata);
// when
when(_mailboxService.getReceivingMailbox(MAILBOX_ID_1)).thenReturn(_mailbox1);
Object[] row1 = ... |
public static QueryQueueOptions createFromEnv() {
if (!Config.enable_query_queue_v2) {
return new QueryQueueOptions(false, V2.DEFAULT);
}
V2 v2 = new V2(Config.query_queue_v2_concurrency_level,
BackendResourceStat.getInstance().getNumBes(),
BackendRes... | @Test
public void testCreateFromEnv() {
{
Config.enable_query_queue_v2 = false;
QueryQueueOptions opts = QueryQueueOptions.createFromEnv();
assertThat(opts.isEnableQueryQueueV2()).isFalse();
}
{
final int numCores = 16;
final long... |
public static Builder builder(Credentials credentials) {
return new Builder(credentials);
} | @Test
public void testCreateWithCredentials() {
Credentials credentials = mock(Credentials.class);
FlexTemplateClient.builder(credentials).build();
// Lack of exception is all we really can test
} |
@Override
public OAuth2AccessTokenDO getAccessToken(String accessToken) {
// 优先从 Redis 中获取
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken);
if (accessTokenDO != null) {
return accessTokenDO;
}
// 获取不到,从 MySQL 中获取
accessToken... | @Test
public void testCheckAccessToken_success() {
// mock 数据(访问令牌)
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class)
.setExpiresTime(LocalDateTime.now().plusDays(1));
oauth2AccessTokenMapper.insert(accessTokenDO);
// 准备参数
String access... |
@Override
public MapperResult findConfigInfoLike4PageFetchRows(MapperContext context) {
final String tenant = (String) context.getWhereParameter(FieldConstant.TENANT_ID);
final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID);
final String group = (String) context.ge... | @Test
void testFindConfigInfoLike4PageFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageFetchRows(context);
assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key,type FROM config_info "
+ "... |
@Override
// Camel calls this method if the endpoint isSynchronous(), as the
// KafkaEndpoint creates a SynchronousDelegateProducer for it
public void process(Exchange exchange) throws Exception {
// is the message body a list or something that contains multiple values
Message message = exch... | @Test
public void processRequiresTopicInConfiguration() throws Exception {
endpoint.getConfiguration().setTopic("configTopic");
Mockito.when(exchange.getIn()).thenReturn(in);
Mockito.when(exchange.getMessage()).thenReturn(in);
in.setHeader(KafkaConstants.PARTITION_KEY, 4);
in... |
public static TimeWindows ofSizeWithNoGrace(final Duration size) throws IllegalArgumentException {
return ofSizeAndGrace(size, ofMillis(NO_GRACE_PERIOD));
} | @Test
public void windowSizeMustNotBeNegative() {
assertThrows(IllegalArgumentException.class, () -> TimeWindows.ofSizeWithNoGrace(ofMillis(-1)));
} |
@Override
public Boolean authenticate(final Host bookmark, final LoginCallback callback, final CancelCallback cancel) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Login using challenge response authentication for %s", bookmark));
}
final Atomic... | @Test(expected = LoginFailureException.class)
@Ignore
public void testAuthenticate() throws Exception {
assertFalse(new SFTPChallengeResponseAuthentication(session.getClient()).authenticate(session.getHost(), new DisabledLoginCallback(), new DisabledCancelCallback()));
} |
public ImmutableSet<String> loadAllMessageStreams(final StreamPermissions streamPermissions) {
return allStreamsProvider.get()
// Unless explicitly queried, exclude event and failure indices by default
// Having these indices in every search, makes sorting almost impossible
... | @Test
public void filtersDefaultStreams() {
final PermittedStreams sut = new PermittedStreams(() -> Streams.concat(NON_MESSAGE_STREAM_IDS.stream(), java.util.stream.Stream.of("i'm ok")));
ImmutableSet<String> result = sut.loadAllMessageStreams(id -> true);
assertThat(result).containsExactly(... |
@Override
protected SDSApiClient connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
authorizationService = new OAuth2RequestInter... | @Test(expected = ConnectionRefusedException.class)
public void testProxyNoConnect() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new SDSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getC... |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldUseSourceTopicForCreateExistingTopic() {
// Given:
givenStatement("CREATE STREAM x (FOO VARCHAR) WITH(value_format='avro', kafka_topic='source', partitions=2);");
// When:
injector.inject(statement, builder);
// Then:
verify(builder).withSource(argThat(supplierThatGet... |
@Override
public TimelineEntity getContainerEntity(ContainerId containerId,
String fields, Map<String, String> filters) throws IOException {
ApplicationId appId = containerId.getApplicationAttemptId().
getApplicationId();
String path = PATH_JOINER.join("clusters", clusterId, "apps",
appI... | @Test
void testGetContainer() throws Exception {
ContainerId containerId =
ContainerId.fromString("container_1234_0001_01_000001");
TimelineEntity entity = client.getContainerEntity(containerId,
null, null);
assertEquals("mockContainer1", entity.getId());
} |
@Override
public String toString() {
return "DEFAULT";
} | @Test
public void testToString() {
String expected = "DEFAULT";
assertEquals(expected.trim(), SqlDefaultExpr.get().toString().trim());
} |
@Override
public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException {
} | @Test
void testUpdateInstance() {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
Assertions.assertDoesNotThrow(() -> {
delegate.updateInstance(serviceName, groupName, instance);
});
} |
public static ObjectNode json(Highlights highlights) {
ObjectNode payload = objectNode();
ArrayNode devices = arrayNode();
ArrayNode hosts = arrayNode();
ArrayNode links = arrayNode();
payload.set(DEVICES, devices);
payload.set(HOSTS, hosts);
payload.set(LINKS, ... | @Test
public void badgedDevice() {
Highlights h = new Highlights();
DeviceHighlight dh = new DeviceHighlight(DEV1);
dh.setBadge(NodeBadge.number(7));
h.add(dh);
dh = new DeviceHighlight(DEV2);
dh.setBadge(NodeBadge.glyph(Status.WARN, GID, SOME_MSG));
h.add(dh... |
@Override
public FlinkPod decorateFlinkPod(FlinkPod flinkPod) {
final Container basicMainContainer =
new ContainerBuilder(flinkPod.getMainContainer())
.addAllToEnv(getSecretEnvs())
.build();
return new FlinkPod.Builder(flinkPod).withMa... | @Test
void testWhetherPodOrContainerIsDecorated() {
final FlinkPod resultFlinkPod = envSecretsDecorator.decorateFlinkPod(baseFlinkPod);
List<EnvVar> envVarList = resultFlinkPod.getMainContainer().getEnv();
assertThat(envVarList).extracting(EnvVar::getName).containsExactly(ENV_NAME);
} |
static Builder newBuilder() {
return new AutoValue_SplunkEventWriter.Builder();
} | @Test
public void eventWriterMissingToken() {
Exception thrown =
assertThrows(
NullPointerException.class,
() -> SplunkEventWriter.newBuilder().withUrl("http://test-url").build());
assertTrue(thrown.getMessage().contains("token needs to be provided"));
} |
public ExitStatus(Options options) {
this.options = options;
} | @Test
void with_failed_passed_scenarios() {
createRuntime();
bus.send(testCaseFinishedWithStatus(Status.FAILED));
bus.send(testCaseFinishedWithStatus(Status.PASSED));
assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1)));
} |
public static void scheduleLongPolling(Runnable runnable, long initialDelay, long delay, TimeUnit unit) {
LONG_POLLING_EXECUTOR.scheduleWithFixedDelay(runnable, initialDelay, delay, unit);
} | @Test
void testScheduleLongPollingV1() throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger();
Runnable runnable = atomicInteger::incrementAndGet;
ConfigExecutor.scheduleLongPolling(runnable, 0, 10, TimeUnit.MILLISECONDS);
... |
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
configPrefix = (configPrefix != null) ? configPrefix + "." : "";
config = getConfiguration(configPrefix, filterConfig);
String authHandlerName = config.ge... | @Test
public void testInit() throws Exception {
// custom secret as inline
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
M... |
public ApplicationBuilder owner(String owner) {
this.owner = owner;
return getThis();
} | @Test
void owner() {
ApplicationBuilder builder = new ApplicationBuilder();
builder.owner("owner");
Assertions.assertEquals("owner", builder.build().getOwner());
} |
public void enter(Wizard wizard) {
LOGGER.info("{} enters the tower.", wizard);
} | @Test
void testEnter() {
final var wizards = List.of(
new Wizard("Gandalf"),
new Wizard("Dumbledore"),
new Wizard("Oz"),
new Wizard("Merlin")
);
var tower = new IvoryTower();
wizards.forEach(tower::enter);
assertTrue(appender.logContains("Gandalf enters the tower.... |
public static Write<PubsubMessage> writeMessages() {
return Write.newBuilder()
.setTopicProvider(null)
.setTopicFunction(null)
.setDynamicDestinations(false)
.build();
} | @Test
public void testWriteMalformedMessagesWithErrorHandler() throws Exception {
OutgoingMessage msg =
OutgoingMessage.of(
com.google.pubsub.v1.PubsubMessage.newBuilder()
.setData(ByteString.copyFromUtf8("foo"))
.build(),
0,
null,
... |
@Override
public void check(final SQLStatement sqlStatement) {
ShardingSpherePreconditions.checkState(judgeEngine.isSupported(sqlStatement), () -> new ClusterStateException(getType(), sqlStatement));
} | @Test
void assertExecuteWithSupportedSQL() {
new ReadOnlyProxyState().check(mock(SelectStatement.class));
} |
public ClientSession toClientSession()
{
return new ClientSession(
parseServer(server),
user,
source,
Optional.empty(),
parseClientTags(clientTags),
clientInfo,
catalog,
schema,
... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Multiple entries with same key: test.token.foo=bar and test.token.foo=foo")
public void testDuplicateExtraCredentialKey()
{
Console console = singleCommand(Console.class).parse("--extra-credential", "test.token... |
public static BufferedImage rotateImage(final BufferedImage image, final double theta)
{
AffineTransform transform = new AffineTransform();
transform.rotate(theta, image.getWidth() / 2.0, image.getHeight() / 2.0);
AffineTransformOp transformOp = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
... | @Test
public void rotateImage()
{
// TODO: Test more than 90° rotations
// Evenly-sized images (2x2)
assertTrue(bufferedImagesEqual(BLACK_PIXEL_TOP_RIGHT, ImageUtil.rotateImage(BLACK_PIXEL_TOP_LEFT, Math.PI / 2)));
assertTrue(bufferedImagesEqual(BLACK_PIXEL_BOTTOM_RIGHT, ImageUtil.rotateImage(BLACK_PIXEL_TOP... |
public static WindowBytesStoreSupplier persistentWindowStore(final String name,
final Duration retentionPeriod,
final Duration windowSize,
... | @Test
public void shouldCreateRocksDbWindowStore() {
final WindowStore store = Stores.persistentWindowStore("store", ofMillis(1L), ofMillis(1L), false).get();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
assertThat(store, instanceOf(RocksDBWindowStore.class));
as... |
public static NacosLogging getInstance() {
return NacosLoggingInstance.INSTANCE;
} | @Test
void testGetInstance() {
NacosLogging instance = NacosLogging.getInstance();
assertNotNull(instance);
} |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldThrowWhenJoinSelectWithoutSubjectReadPermissionsDenied() {
// Given:
givenSubjectAccessDenied(AVRO_TOPIC + "-value", AclOperation.READ);
final Statement statement = givenStatement(String.format(
"SELECT * FROM %s A JOIN %s B ON A.F1 = B.F1;", KAFKA_STREAM_TOPIC, AVRO_STREAM... |
@Override public Metadata headers() {
return headers;
} | @Test void headers() {
assertThat(response.headers()).isSameAs(headers);
} |
protected boolean nodeValueIsAllowed(Object value) {
return ALLOWED_TYPES.stream().anyMatch(objectPredicate -> objectPredicate.test(value));
} | @Test
void nodeValueIsAllowed_False() {
Object value = Boolean.TRUE;
assertThat(rangeFunction.nodeValueIsAllowed(value))
.withFailMessage(String.format("%s", value)).isFalse();
value = Collections.emptyMap();
assertThat(rangeFunction.nodeValueIsAllowed(value))
... |
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeySpecException,
InvalidAlgorithmParameterException,... | @Test
public void testPkcs1AesEncryptedRsaEmptyPassword() throws Exception {
assertThrows(IOException.class, new Executable() {
@Override
public void execute() throws Throwable {
SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_aes_encrypted.key")
... |
public long getUnknown_18() {
return unknown_18;
} | @Test
public void testGetUnknown_18() {
assertEquals(TestParameters.VP_UNKNOWN_18, chmLzxcControlData.getUnknown_18());
} |
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) {
return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs));
} | @Test
public void testGroupingKeyTypeWithAddingBackSamePartitionFieldInV1Table() {
TestTables.TestTable table =
TestTables.create(tableDir, "test", SCHEMA, BY_CATEGORY_DATA_SPEC, V1_FORMAT_VERSION);
table.updateSpec().removeField("data").commit();
table.updateSpec().addField("data").commit();
... |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldLoadPartialConfigWithEnvironment() throws Exception {
String partialConfigWithPipeline = configWithEnvironments(
"""
<environments>
<environment name='uat'>
<pipelines>
... |
@Override
public int leaveGroupEpoch() {
return groupInstanceId.isPresent() ?
ConsumerGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH :
ConsumerGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH;
} | @Test
public void testLeaveGroupEpoch() {
// Static member should leave the group with epoch -2.
ConsumerMembershipManager membershipManager = createMemberInStableState("instance1");
mockLeaveGroup();
membershipManager.leaveGroup();
verify(subscriptionState).unsubscribe();
... |
public PageListResponse<IndexSetFieldTypeSummary> getIndexSetFieldTypeSummary(final Set<String> streamIds,
final String fieldName,
final Predicate<String> i... | @Test
void testFillsSummaryDataProperly() {
Predicate<String> indexSetPermissionPredicate = indexSetID -> indexSetID.contains("canSee");
doReturn(Set.of("canSee", "cannotSee")).when(streamService).indexSetIdsByIds(Set.of("stream_id"));
doReturn(List.of("Stream1", "Stream2")).when(streamServ... |
public EndpointConfig setSocketKeepIntervalSeconds(int socketKeepIntervalSeconds) {
Preconditions.checkPositive("socketKeepIntervalSeconds", socketKeepIntervalSeconds);
Preconditions.checkTrue(socketKeepIntervalSeconds < MAX_SOCKET_KEEP_INTERVAL_SECONDS,
"socketKeepIntervalSeconds value ... | @Test
public void testKeepIntervalSecondsValidation() {
EndpointConfig endpointConfig = new EndpointConfig();
Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.setSocketKeepIntervalSeconds(0));
Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.se... |
@Override
public void start(BundleContext bundleContext) throws Exception {
Bundle bundle = bundleContext.getBundle();
pluginRegistryService = bundleContext.getService(bundleContext.getServiceReference(PluginRegistryService.class));
bundleSymbolicName = bundle.getSymbolicName();
plu... | @Test
public void shouldSetupTheLoggerWithTheLoggingServiceAndPluginId() throws Exception {
setupClassesInBundle();
activator.start(context);
Logger logger = Logger.getLoggerFor(DefaultGoPluginActivatorTest.class);
logger.info("INFO");
verify(loggingService).info(PLUGIN_ID... |
@Operation(
summary = "Search for the given search keys in the key transparency log",
description = """
Enforced unauthenticated endpoint. Returns a response if all search keys exist in the key transparency log.
"""
)
@ApiResponse(responseCode = "200", description = "All search key l... | @Test
void searchAuthenticated() {
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/key-transparency/search")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = req... |
public B connections(Integer connections) {
this.connections = connections;
return getThis();
} | @Test
void connections() {
InterfaceBuilder builder = new InterfaceBuilder();
builder.connections(1);
Assertions.assertEquals(1, builder.build().getConnections().intValue());
} |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void shouldPrintExplainQueryWithError() {
final long timestamp = 1596644936314L;
// Given:
final QueryDescriptionEntity queryEntity = new QueryDescriptionEntity(
"statement",
new QueryDescription(
new QueryId("id"),
"statement",
Optional.em... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_empty_table__empty_table() {
DataTable table = emptyDataTable();
assertSame(table, converter.convert(table, DataTable.class));
} |
@Override
public void execute(final ConnectionSession connectionSession) throws SQLException {
Map<String, String> sessionVariables = extractSessionVariables();
validateSessionVariables(sessionVariables.keySet());
new CharsetSetExecutor(databaseType, connectionSession).set(sessionVariables);... | @Test
void assertSetVariableWithIncorrectScope() {
VariableAssignSegment variableAssignSegment = new VariableAssignSegment();
variableAssignSegment.setVariable(new VariableSegment(0, 0, "max_connections"));
variableAssignSegment.setAssignValue("");
SetStatement setStatement = new MyS... |
@Override
public Optional<DispatchEvent> build(final DataChangedEvent event) {
if (Strings.isNullOrEmpty(event.getValue())) {
return Optional.empty();
}
Optional<QualifiedDataSource> qualifiedDataSource = QualifiedDataSourceNode.extractQualifiedDataSource(event.getKey());
... | @Test
void assertCreateEnabledQualifiedDataSourceChangedEvent() {
Optional<DispatchEvent> actual = new QualifiedDataSourceDispatchEventBuilder().build(
new DataChangedEvent("/nodes/qualified_data_sources/replica_query_db.readwrite_ds.replica_ds_0", "state: ENABLED\n", Type.ADDED));
a... |
void writeLogs(OutputStream out, Instant from, Instant to, long maxLines, Optional<String> hostname) {
double fromSeconds = from.getEpochSecond() + from.getNano() / 1e9;
double toSeconds = to.getEpochSecond() + to.getNano() / 1e9;
long linesWritten = 0;
BufferedWriter writer = new Buffer... | @Test
void logsForSingeNodeIsRetrieved() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), 100, Optional.of("node2.com"));
... |
@Override
public int getOrder() {
return PluginEnum.REDIRECT.getCode();
} | @Test
public void testGetOrder() {
final int result = redirectPlugin.getOrder();
assertThat(PluginEnum.REDIRECT.getCode(), Matchers.is(result));
} |
public static String getKey(String dataId, String group) {
StringBuilder sb = new StringBuilder();
urlEncode(dataId, sb);
sb.append('+');
urlEncode(group, sb);
return sb.toString();
} | @Test
void testGetKeyByThreeParams() {
// Act
final String actual = GroupKey2.getKey(",", ",", "3");
// Assert result
assertEquals(",+,+3", actual);
} |
@Override
public FileMergingCheckpointStateOutputStream createCheckpointStateOutputStream(
SubtaskKey subtaskKey, long checkpointId, CheckpointedStateScope scope) {
return new FileMergingCheckpointStateOutputStream(
writeBufferSize,
new FileMergingCheckpointState... | @Test
public void testConcurrentWriting() throws Exception {
long checkpointId = 1;
int numThreads = 12;
int perStreamWriteNum = 128;
Set<Future<SegmentFileStateHandle>> futures = new HashSet<>();
try (FileMergingSnapshotManager fmsm = createFileMergingSnapshotManager(checkp... |
public boolean isSupported(final SQLStatement sqlStatement) {
for (Class<? extends SQLStatement> each : supportedSQLStatements) {
if (each.isAssignableFrom(sqlStatement.getClass())) {
return true;
}
}
for (Class<? extends SQLStatement> each : unsupportedSQ... | @Test
void assertIsSupportedWithInSupportedList() {
assertTrue(new SQLSupportedJudgeEngine(Collections.singleton(SelectStatement.class), Collections.emptyList()).isSupported(mock(SelectStatement.class)));
} |
@Override
public BackgroundException map(final IOException e) {
final StringBuilder buffer = new StringBuilder();
this.append(buffer, e.getMessage());
if(e instanceof FTPConnectionClosedException) {
return new ConnectionRefusedException(buffer.toString(), e);
}
if... | @Test
public void testFile() {
assertTrue(new FTPExceptionMappingService().map(new FTPException(550, "")) instanceof NotfoundException);
} |
protected Destination createDestination(String destName) throws JMSException {
String simpleName = getSimpleName(destName);
byte destinationType = getDestinationType(destName);
if (destinationType == ActiveMQDestination.QUEUE_TYPE) {
LOG.info("Creating queue: {}", destName);
... | @Test
public void testCreateDestination() throws JMSException {
assertDestinationNameType("dest", TOPIC_TYPE,
asAmqDest(jmsClient.createDestination("dest")));
} |
public synchronized GpuDeviceInformation parseXml(String xmlContent)
throws YarnException {
InputSource inputSource = new InputSource(new StringReader(xmlContent));
SAXSource source = new SAXSource(xmlReader, inputSource);
try {
return (GpuDeviceInformation) unmarshaller.unmarshal(source);
}... | @Test
public void testParse() throws IOException, YarnException {
File f = new File("src/test/resources/nvidia-smi-sample-output.xml");
String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8);
GpuDeviceInformationParser parser = new GpuDeviceInformationParser();
GpuDeviceInformation info = p... |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldGenerateName() {
// Given:
givenStatement("CREATE STREAM x AS SELECT * FROM SOURCE;");
// When:
injector.inject(statement, builder);
// Then:
verify(builder).withName("X");
} |
public static Locale createLocale( String localeCode ) {
if ( Utils.isEmpty( localeCode ) ) {
return null;
}
StringTokenizer parser = new StringTokenizer( localeCode, "_" );
if ( parser.countTokens() == 2 ) {
return new Locale( parser.nextToken(), parser.nextToken() );
}
if ( parser.... | @Test
public void createLocale_Null() throws Exception {
assertNull( EnvUtil.createLocale( null ) );
} |
static void scan(Class<?> aClass, BiConsumer<Method, Annotation> consumer) {
// prevent unnecessary checking of Object methods
if (Object.class.equals(aClass)) {
return;
}
if (!isInstantiable(aClass)) {
return;
}
for (Method method : safelyGetMeth... | @Test
void scan_ignores_non_instantiable_class() {
MethodScanner.scan(NonStaticInnerClass.class, backend);
assertThat(scanResult, empty());
} |
public static TypeInformation<?> readTypeInfo(String typeString) {
final List<Token> tokens = tokenize(typeString);
final TokenConverter converter = new TokenConverter(typeString, tokens);
return converter.convert();
} | @Test
void testWriteComplexTypes() {
testReadAndWrite("ROW<f0 DECIMAL, f1 TINYINT>", Types.ROW(Types.BIG_DEC, Types.BYTE));
testReadAndWrite(
"ROW<hello DECIMAL, world TINYINT>",
Types.ROW_NAMED(new String[] {"hello", "world"}, Types.BIG_DEC, Types.BYTE));
t... |
static Schema sortKeySchema(Schema schema, SortOrder sortOrder) {
List<SortField> sortFields = sortOrder.fields();
int size = sortFields.size();
List<Types.NestedField> transformedFields = Lists.newArrayListWithCapacity(size);
for (int i = 0; i < size; ++i) {
int sourceFieldId = sortFields.get(i).... | @Test
public void testResultSchema() {
Schema schema =
new Schema(
Types.NestedField.required(1, "id", Types.StringType.get()),
Types.NestedField.required(2, "ratio", Types.DoubleType.get()),
Types.NestedField.optional(
3,
"user",
... |
public static String segmentIdHex(String segIdStr) {
int segId = Integer.parseInt(segIdStr);
return String.format("%06x", segId).toLowerCase();
} | @Test
public void testSegmentIdHex() {
assertEquals("000001", segmentIdHex("1"));
assertEquals("00000a", segmentIdHex("10"));
assertEquals("ffffff", segmentIdHex("16777215"));
} |
public static GroupInstruction createGroup(final GroupId groupId) {
checkNotNull(groupId, "GroupId cannot be null");
return new GroupInstruction(groupId);
} | @Test
public void testCreateGroupMethod() {
final Instruction instruction = Instructions.createGroup(groupId1);
final Instructions.GroupInstruction groupInstruction =
checkAndConvert(instruction,
Instruction.Type.GROUP,
... |
@Override
public void moveCenter(double moveHorizontal, double moveVertical) {
this.moveCenterAndZoom(moveHorizontal, moveVertical, (byte) 0, true);
} | @Test
public void moveCenterTest() {
MapViewPosition mapViewPosition = new MapViewPosition(new FixedTileSizeDisplayModel(256));
mapViewPosition.moveCenter(
MercatorProjection.getMapSize((byte) 0, new FixedTileSizeDisplayModel(256).getTileSize()) / -360d, 0);
MapPosition mapP... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatLikePredicate() {
final LikePredicate predicate = new LikePredicate(new StringLiteral("string"), new StringLiteral("*"), Optional.empty());
assertThat(ExpressionFormatter.formatExpression(predicate), equalTo("('string' LIKE '*')"));
} |
public static ResourceType determineResourceType(final String resourceName) {
for ( Map.Entry<String, ResourceType> entry : CACHE.entrySet() ) {
if (resourceName.endsWith(entry.getKey())) {
if (entry.getValue().equals(ResourceType.DRT)) {
LOG.warn("DRT (Drools Rul... | @Test
public void testDetermineResourceType() {
assertThat(ResourceType.determineResourceType("test.drl.xls")).isEqualTo(ResourceType.DTABLE);
assertThat(ResourceType.determineResourceType("test.xls")).isNull();
} |
public void validate(CreateReviewAnswerRequest request) {
Question question = questionRepository.findById(request.questionId())
.orElseThrow(() -> new SubmittedQuestionNotFoundException(request.questionId()));
validateNotIncludingOptions(request);
validateQuestionRequired(questio... | @Test
void 필수_텍스트형_질문에_응답을_하지_않으면_예외가_발생한다() {
// given
Question savedQuestion
= questionRepository.save(new Question(true, QuestionType.TEXT, "질문", "가이드라인", 1));
CreateReviewAnswerRequest request = new CreateReviewAnswerRequest(savedQuestion.getId(), null, null);
//... |
@Override
public Enumeration<URL> getResources(String name) throws IOException {
List<URL> resources = new ArrayList<>();
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resources '{}'", name);
for (ClassLoadingStrategy.Source... | @Test
void parentFirstGetResourcesNonExisting() throws IOException {
assertFalse(parentFirstPluginClassLoader.getResources("META-INF/non-existing-file").hasMoreElements());
} |
@Override
public List<String> getServerList() {
return serverList.isEmpty() ? serversFromEndpoint : serverList;
} | @Test
void testConstructWithAddrTryToRefresh()
throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849");
serverLi... |
public static Environment of(@NonNull Properties props) {
var environment = new Environment();
environment.props = props;
return environment;
} | @Test
public void testOf() {
Environment environment = Environment.of("application.properties");
Optional<String> version = Objects.requireNonNull(environment).get("app.version");
String lang = environment.get("app.lang", "cn");
assertEquals("0.0.2", version.orElse(""));
ass... |
@Override
public DynamicTableSource createDynamicTableSource(Context context) {
Configuration conf = FlinkOptions.fromMap(context.getCatalogTable().getOptions());
StoragePath path = new StoragePath(conf.getOptional(FlinkOptions.PATH).orElseThrow(() ->
new ValidationException("Option [path] should not ... | @Test
void testSetupHoodieKeyOptionsForSource() {
this.conf.setString(FlinkOptions.RECORD_KEY_FIELD, "dummyField");
this.conf.setString(FlinkOptions.KEYGEN_CLASS_NAME, "dummyKeyGenClass");
// definition with simple primary key and partition path
ResolvedSchema schema1 = SchemaBuilder.instance()
... |
@Override
public void rotate(IndexSet indexSet) {
indexRotator.rotate(indexSet, this::shouldRotate);
} | @Test
public void shouldRotateThrowsISEIfIndexSetIdIsNull() {
when(indexSet.getConfig()).thenReturn(indexSetConfig);
when(indexSetConfig.id()).thenReturn(null);
when(indexSet.getNewestIndex()).thenReturn(IGNORED);
expectedException.expect(IllegalStateException.class);
expect... |
public int getSubmitReservationFailedRetrieved() {
return numSubmitReservationFailedRetrieved.value();
} | @Test
public void testGetSubmitReservationRetrievedFailed() {
long totalBadBefore = metrics.getSubmitReservationFailedRetrieved();
badSubCluster.getSubmitReservationFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getSubmitReservationFailedRetrieved());
} |
@Override
public Repositories listRepositories(String appUrl, AccessToken accessToken, String organization, @Nullable String query, int page, int pageSize) {
checkPageArgs(page, pageSize);
String searchQuery = "fork:true+org:" + organization;
if (query != null) {
searchQuery = query.replace(" ", "+"... | @Test
public void listRepositories_fail_if_pageSize_out_of_bounds() {
UserAccessToken token = new UserAccessToken("token");
assertThatThrownBy(() -> underTest.listRepositories(appUrl, token, "test", null, 1, 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'pageSize' must be a value ... |
public TryDefinition doFinally() {
popBlock();
FinallyDefinition answer = new FinallyDefinition();
addOutput(answer);
pushBlock(answer);
return this;
} | @Test
public void doFinallyTest() {
TryDefinition tryDefinition = new TryDefinition();
CatchDefinition catchDefinition = new CatchDefinition();
FinallyDefinition finallyDefinition = new FinallyDefinition();
tryDefinition.addOutput(new ToDefinition("mock:1"));
catchDefinition.... |
@Udf
public <T> Map<String, T> union(
@UdfParameter(description = "first map to union") final Map<String, T> map1,
@UdfParameter(description = "second map to union") final Map<String, T> map2) {
final List<Map<String, T>> nonNullInputs =
Stream.of(map1, map2)
.filter(Objects::nonNull)... | @Test
public void shouldUnionMapWithNulls() {
final Map<String, String> input1 = Maps.newHashMap();
input1.put("one", "apple");
input1.put("two", "banana");
input1.put("three", "cherry");
final Map<String, String> input2 = Maps.newHashMap();
input2.put("foo", "bar");
input2.put(null, null... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetTriFunctionVariadic() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("triFunctionType", TriFunction.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getVarArgsSchemaFromType(type);
assertThat(schema, instanceOf(La... |
@Override
public TapiNepRef getNepRef(TapiNepRef nepRef) throws NoSuchElementException {
updateCache();
TapiNepRef ret = null;
try {
ret = tapiNepRefList.stream()
.filter(nepRef::equals)
.findFirst().get();
} catch (NoSuchElementExc... | @Test(expected = NoSuchElementException.class)
public void testGetNepRefWithSipIdWhenEmpty() {
tapiResolver.getNepRef(sipId);
} |
Set<String> getRetry() {
return retry;
} | @Test
public void determineRetryWhenSetToMultiple() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("exhausted,generic");
assertEquals(new HashSet<>(Arrays.asList("exhausted", "generic")), helper.getRetry());
} |
public static String join(Iterable<?> iterable, String separator) {
return join( iterable, separator, null );
} | @Test
public void testJoin() {
assertThat( Strings.join( new ArrayList<String>(), "-" ) ).isEqualTo( "" );
assertThat( Strings.join( Arrays.asList( "Hello", "World" ), "-" ) ).isEqualTo( "Hello-World" );
assertThat( Strings.join( Arrays.asList( "Hello" ), "-" ) ).isEqualTo( "Hello" );
} |
public CompletableFuture<LookupResult> createLookupResult(String candidateBroker, boolean authoritativeRedirect,
final String advertisedListenerName) {
CompletableFuture<LookupResult> lookupFuture = new CompletableFuture<>();
try {
... | @Test
public void testLoadReportDeserialize() throws Exception {
final String candidateBroker1 = "localhost:8000";
String broker1Url = "pulsar://localhost:6650";
final String candidateBroker2 = "localhost:3000";
String broker2Url = "pulsar://localhost:6660";
LoadReport lr = ... |
@GetMapping(value = "/node/self/health")
@Secured(action = ActionTypes.READ, resource = "nacos/admin", signType = SignType.CONSOLE)
public Result<String> selfHealth() {
return Result.success(nacosClusterOperationService.selfHealth());
} | @Test
void testSelfHealth() {
String selfHealth = "UP";
when(nacosClusterOperationService.selfHealth()).thenReturn(selfHealth);
Result<String> result = nacosClusterControllerV2.selfHealth();
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(se... |
protected void processFileContents(List<String> fileLines, String filePath, Engine engine) throws AnalysisException {
fileLines.stream()
.map(fileLine -> fileLine.split("(,|=>)"))
.map(requires -> {
//LOGGER.debug("perl scanning file:" + fileLine);
... | @Test
public void testProcessDefaultZero() throws AnalysisException {
Dependency d = new Dependency();
List<String> dependencyLines = Arrays.asList(new String[]{
"requires 'JSON'",});
PerlCpanfileAnalyzer instance = new PerlCpanfileAnalyzer();
Engine engine = new Engine(g... |
@Override
public OAuth2CodeDO createAuthorizationCode(Long userId, Integer userType, String clientId,
List<String> scopes, String redirectUri, String state) {
OAuth2CodeDO codeDO = new OAuth2CodeDO().setCode(generateCode())
.setUserId(userId).s... | @Test
public void testCreateAuthorizationCode() {
// 准备参数
Long userId = randomLongId();
Integer userType = RandomUtil.randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
List<String> scopes = Lists.newArrayList("read", "write");
String redir... |
public ConnectionFileName createChildName( String name, FileType type ) {
String childAbsPath = getConnectionFileNameUtils().ensureTrailingSeparator( getPath() ) + name;
return new ConnectionFileName( connection, childAbsPath, type );
} | @Test
public void testCreateChildNameOfSubFolderReturnsFileNameWithCorrectPath() {
ConnectionFileName parentFileName = new ConnectionFileName( "connection", "/folder", FileType.FOLDER );
assertEquals( "pvfs://connection/folder", parentFileName.getURI() );
ConnectionFileName childFileName = parentFileNam... |
public boolean greaterThanOrEqualTo(final int major, final int minor, final int series) {
if (this.major < major) {
return false;
}
if (this.major > major) {
return true;
}
if (this.minor < minor) {
return false;
}
if (this.mino... | @Test
void assertGreaterThan() {
MySQLServerVersion actual = new MySQLServerVersion("5.7.12");
assertTrue(actual.greaterThanOrEqualTo(4, 0, 0));
assertTrue(actual.greaterThanOrEqualTo(5, 6, 0));
assertTrue(actual.greaterThanOrEqualTo(5, 7, 11));
} |
@VisibleForTesting
int getNumAllocatedSlotsOfGroup(long groupId) {
return allocatedGroupIdToSlotCount.getOrDefault(groupId, 0);
} | @Test
public void testReleaseSlot() throws InterruptedException {
DefaultSlotSelectionStrategy strategy =
new DefaultSlotSelectionStrategy(() -> false, (groupId) -> false);
SlotTracker slotTracker = new SlotTracker(ImmutableList.of(strategy));
LogicalSlot slot1 = generateSlo... |
@Override
public boolean mayHaveMergesPending(String bucketSpace, int contentNodeIndex) {
if (!stats.hasUpdatesFromAllDistributors()) {
return true;
}
ContentNodeStats nodeStats = stats.getStats().getNodeStats(contentNodeIndex);
if (nodeStats != null) {
Conten... | @Test
void valid_bucket_space_stats_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 1));
} |
void recoverTransitionRead(DataNode datanode, NamespaceInfo nsInfo,
Collection<StorageLocation> dataDirs, StartupOption startOpt) throws IOException {
if (addStorageLocations(datanode, nsInfo, dataDirs, startOpt).isEmpty()) {
throw new IOException("All specified directories have failed to load.");
}... | @Test
public void testRecoverTransitionReadFailure() throws IOException {
final int numLocations = 3;
List<StorageLocation> locations =
createStorageLocations(numLocations, true);
try {
storage.recoverTransitionRead(mockDN, nsInfo, locations, START_OPT);
fail("An IOException should thr... |
List<CounterRequestContext> getOrderedRootCurrentContexts() {
final List<CounterRequestContext> contextList = new ArrayList<>(
rootCurrentContextsByThreadId.size());
for (final CounterRequestContext rootCurrentContext : rootCurrentContextsByThreadId
.values()) {
contextList.add(rootCurrentContext.clone()... | @Test
public void testGetOrderedRootCurrentContexts() {
counter.unbindContext();
final String requestName = "root context";
final int nbRootContexts = 100; // 100 pour couvrir tous les cas du compartor de tri
bindRootContexts(requestName, counter, nbRootContexts);
// addRequest pour rentrer dans le if de la... |
@Override
public Endpoint<Http2LocalFlowController> local() {
return localEndpoint;
} | @Test
public void clientLocalIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception {
incrementAndGetStreamShouldRespectOverflow(client.local(), MAX_VALUE);
} |
public static boolean parseBoolean(final String value) {
return booleanStringMatches(value, true);
} | @Test
public void shouldParseTrueAsTrue() {
assertThat(SqlBooleans.parseBoolean("tRue"), is(true));
assertThat(SqlBooleans.parseBoolean("trU"), is(true));
assertThat(SqlBooleans.parseBoolean("tr"), is(true));
assertThat(SqlBooleans.parseBoolean("T"), is(true));
assertThat(SqlBooleans.parseBoolean(... |
@SuppressWarnings("unchecked")
// visible for testing
public StitchRequestBody createStitchRequestBody(final Message inMessage) {
if (inMessage.getBody() instanceof StitchRequestBody) {
return createStitchRequestBodyFromStitchRequestBody(inMessage.getBody(StitchRequestBody.class), inMessage)... | @Test
void testIfCreateIfMapSet() {
final StitchConfiguration configuration = new StitchConfiguration();
final Map<String, Object> properties = new LinkedHashMap<>();
properties.put("id", Collections.singletonMap("type", "integer"));
properties.put("name", Collections.singletonMap("... |
@Override
public void accept(Props props) {
if (isClusterEnabled(props)) {
checkClusterProperties(props);
}
} | @Test
public void accept_throws_MessageException_if_a_cluster_forbidden_property_is_defined_in_a_cluster_search_node() {
TestAppSettings settings = new TestAppSettings(of(
CLUSTER_ENABLED.getKey(), "true",
CLUSTER_NODE_TYPE.getKey(), "search",
"sonar.search.host", "localhost"));
Props props ... |
@Override
public String baseUrl() {
return "/";
} | @Test
public void baseUrl_is_always_slash() {
assertThat(underTest.baseUrl()).isEqualTo("/");
} |
@Override
public void validateTransientQuery(
final SessionConfig config,
final ExecutionPlan executionPlan,
final Collection<QueryMetadata> runningQueries
) {
validateCacheBytesUsage(
runningQueries.stream()
.filter(q -> q instanceof TransientQueryMetadata)
.co... | @Test
public void shouldLimitBufferCacheLimitForTransientQueries() {
// Given:
final SessionConfig config = configWithLimitsTransient(5, OptionalLong.of(30));
// When/Then:
assertThrows(
KsqlException.class,
() -> queryValidator.validateTransientQuery(config, plan, queries)
);
} |
public static <T> PCollections<T> pCollections() {
return new PCollections<>();
} | @Test
public void testIncompatibleWindowFnPropagationFailure() {
p.enableAbandonedNodeEnforcement(false);
PCollection<String> input1 =
p.apply("CreateInput1", Create.of("Input1"))
.apply("Window1", Window.into(FixedWindows.of(Duration.standardMinutes(1))));
PCollection<String> input2 ... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
return doSharding(availableTargetNames, Range.singleton(sh... | @Test
void assertRangeDoShardingByHours() {
int stepAmount = 2;
IntervalShardingAlgorithm algorithm = createAlgorithm("HH:mm:ss.SSS", "02:00:00.000",
"13:00:00.000", "HHmm", stepAmount, "Hours");
Collection<String> availableTablesForJDBCTimeDataSources = new LinkedList<>();
... |
public void disableAutoProvisioning(String configId) {
setProvisioningMode(configId, "JIT");
} | @Test
public void disableAutoProvisioning_shouldNotFail() {
assertThatNoException().isThrownBy(() -> gitlabConfigurationService.disableAutoProvisioning("configId"));
} |
public void close() {
inFlightUnloadRequest.forEach((bundle, future) -> {
if (!future.isDone()) {
String msg = String.format("Unloading bundle: %s, but the unload manager already closed.", bundle);
log.warn(msg);
future.completeExceptionally(new Illega... | @Test
public void testClose() throws IllegalAccessException {
UnloadCounter counter = new UnloadCounter();
UnloadManager manager = new UnloadManager(counter, "mockBrokerId");
var unloadDecision =
new UnloadDecision(new Unload("broker-1", "bundle-1"), Success, Admin);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.