focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public TransactionSendResult sendMessageInTransaction(Message msg,
Object arg) throws MQClientException {
throw new RuntimeException("sendMessageInTransaction not implement, please use TransactionMQProducer class");
} | @Test(expected = RuntimeException.class)
public void assertSendMessageInTransaction() throws MQClientException {
TransactionSendResult result = producer.sendMessageInTransaction(message, 1);
assertNull(result);
} |
@NonNull
@Override
public ConnectionFileName toPvfsFileName( @NonNull FileName providerFileName, @NonNull T details )
throws KettleException {
// Determine the part of provider file name following the connection "root".
// Use the transformer to generate the connection root provider uri.
// Both uri... | @Test
public void testToPvfsFileNameHandlesConnectionsWithBuckets() throws Exception {
// Example: S3
when( details1.hasBuckets() ).thenReturn( true );
String connectionRootProviderUriPrefix = "scheme1://";
String restPath = "/rest/path";
FileName providerFileName = mockFileNameWithUri( FileNam... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
try {
callback.delete(file);
// Delete the file or folder at a given path. If... | @Test(expected = NotfoundException.class)
public void testDeleteNotFound() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new DropboxDeleteFeature(session).delete(Collections.sin... |
@Override
public List<List<Integer>> split(List<Integer> glyphIds)
{
String originalGlyphsAsText = convertGlyphIdsToString(glyphIds);
List<String> tokens = compoundCharacterTokenizer.tokenize(originalGlyphsAsText);
List<List<Integer>> modifiedGlyphs = new ArrayList<>(tokens.size());
... | @Test
void testSplit_3()
{
// given
Set<List<Integer>> matchers = new HashSet<>(
Arrays.asList(Arrays.asList(67, 112, 96), Arrays.asList(74, 112, 76)));
GlyphArraySplitter testClass = new GlyphArraySplitterRegexImpl(matchers);
List<Integer> glyphIds = Arrays.asLi... |
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
Map<String, String> mdcContextMap = getMdcContextMap();
return super.schedule(ContextPropagator.decorateRunnable(contextPropagators, () -> {
try {
setMDCContext(mdcContextM... | @Test
public void testScheduleRunnablePropagatesContext() {
TestThreadLocalContextHolder.put("ValueShouldCrossThreadBoundary");
final ScheduledFuture<?> schedule = schedulerService.schedule(() -> {
TestThreadLocalContextHolder.get().orElseThrow(() -> new RuntimeException("Found No Contex... |
@Override
public StringBuilder toXML(XmlEnvironment enclosingXmlEnvironment) {
// This is only the potential length, since the actual length depends on the given XmlEnvironment.
int potentialLength = length();
StringBuilder res = new StringBuilder(potentialLength);
appendXmlTo(csq -... | @Test
public void equalInnerNamespaceTest() {
StandardExtensionElement innerOne = StandardExtensionElement.builder("inner", "inner-namespace").build();
StandardExtensionElement innerTwo = StandardExtensionElement.builder("inner", "inner-namespace").build();
StandardExtensionElement outer = ... |
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) {
if ( lists == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "lists", "cannot be null"));
}
final Set<Object> resultSet = new LinkedHashSet<>();
for ( final Obj... | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(unionFunction.invoke(null), InvalidParametersEvent.class);
} |
public void completeDefaults(Props props) {
// init string properties
for (Map.Entry<Object, Object> entry : defaults().entrySet()) {
props.setDefault(entry.getKey().toString(), entry.getValue().toString());
}
boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), false);
if ... | @Test
public void completeDefaults_does_not_set_the_transport_port_of_elasticsearch_if_value_is_zero_in_search_node_in_cluster() {
Properties p = new Properties();
p.setProperty("sonar.cluster.enabled", "true");
p.setProperty("sonar.es.port", "0");
Props props = new Props(p);
processProperties.co... |
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final Object options, final PasswordCallback callback) throws BackgroundException {
final Permission permission = new Permission();
// To make a file public you will need to assign the role reader to the type anyone
... | @Test
public void toDownloadUrl() throws Exception {
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path test = new DriveTouchFeature(session, fileid).touch(
new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Type.fil... |
public static String entityUuidOf(String id) {
if (id.startsWith(ID_PREFIX)) {
return id.substring(ID_PREFIX.length());
}
return id;
} | @Test
public void projectUuidOf_returns_argument_if_does_not_starts_with_id_prefix() {
String id = randomAlphabetic(1 + new Random().nextInt(10));
assertThat(AuthorizationDoc.entityUuidOf(id)).isEqualTo(id);
assertThat(AuthorizationDoc.entityUuidOf("")).isEmpty();
} |
public LogicalSchema getIntermediateSchema() {
return intermediateSchema;
} | @Test
public void shouldBuildPullQueryIntermediateSchemaSelectValueNonWindowed() {
// Given:
selects = ImmutableList.of(new SingleColumn(COL0_REF, Optional.of(ALIAS)));
when(keyFormat.isWindowed()).thenReturn(false);
when(analysis.getSelectColumnNames()).thenReturn(ImmutableSet.of(ALIAS));
// Whe... |
public static <K> KTableHolder<K> build(
final KTableHolder<K> table,
final TableFilter<K> step,
final RuntimeBuildContext buildContext) {
return build(table, step, buildContext, SqlPredicate::new);
} | @Test
public void shouldUseCorrectNameForProcessingLogger() {
// When:
step.build(planBuilder, planInfo);
// Then:
verify(buildContext).getProcessingLogger(queryContext);
} |
public static KTableHolder<GenericKey> build(
final KGroupedStreamHolder groupedStream,
final StreamAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedStream,
aggregate,
buildContext,
... | @Test
public void shouldBuildMaterializedWithCorrectSerdesForUnwindowedAggregate() {
// Given:
givenUnwindowedAggregate();
// When:
aggregate.build(planBuilder, planInfo);
// Then:
verify(materializedFactory).create(same(keySerde), same(valueSerde), any());
} |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull6() {
// Arrange
final int type = 6;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Load", actual);
} |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_uiModeNight_night() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("night", config);
assertThat(config.uiMode).isEqualTo(UI_MODE_NIGHT_YES);
} |
public static GenericRecord dataMapToGenericRecord(DataMap map, RecordDataSchema dataSchema) throws DataTranslationException
{
Schema avroSchema = SchemaTranslator.dataToAvroSchema(dataSchema);
return dataMapToGenericRecord(map, dataSchema, avroSchema, null);
} | @Test
public void testInfinityAndNan() throws IOException {
String schemaText =
"{\n" +
" \"type\" : \"record\",\n" +
" \"name\" : \"Foo\",\n" +
" \"fields\" : [\n" +
" { \"name\" : \"doubleRequired\", \"type\" : \"double\" },\n" +
" { \"name\" : ... |
public void onClose()
{
if (asyncTaskExecutor instanceof ExecutorService)
{
try
{
final ExecutorService executor = (ExecutorService)asyncTaskExecutor;
executor.shutdownNow();
if (!executor.awaitTermination(EXECUTOR_SHUTDOWN_TIME... | @Test
void onCloseShouldCallForceOnTheCncByteBuffer(@TempDir final Path dir)
{
final MappedByteBuffer cncByteBuffer = spy(IoUtil.mapNewFile(dir.resolve("test.cnc").toFile(), 1024));
final DriverConductor conductor = new DriverConductor(ctx.clone().cncByteBuffer(cncByteBuffer));
conducto... |
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credenti... | @Test
public void getAddressesNoTasks() {
// given
given(awsEcsApi.listTaskPrivateAddresses(CLUSTER, CREDENTIALS)).willReturn(emptyList());
// when
Map<String, String> result = awsEcsClient.getAddresses();
// then
assertTrue(result.isEmpty());
} |
public NonClosedTracking<RAW, BASE> trackNonClosed(Input<RAW> rawInput, Input<BASE> baseInput) {
NonClosedTracking<RAW, BASE> tracking = NonClosedTracking.of(rawInput, baseInput);
// 1. match by rule, line, line hash and message
match(tracking, LineAndLineHashAndMessage::new);
// 2. match issues with ... | @Test
public void similar_issues_except_message_match() {
FakeInput baseInput = new FakeInput("H1");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg1");
FakeInput rawInput = new FakeInput("H1");
Issue raw = rawInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg2");
Tracking<Is... |
public void returnProduct(Product product) {
LOGGER.info(
String.format(
"%s want to return %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
if (purchases.contains(product)) {
try {
customerDao.deleteProduct(product, this);
purch... | @Test
void shouldRemoveProductFromPurchases() {
customer.setPurchases(new ArrayList<>(Arrays.asList(product)));
customer.returnProduct(product);
assertEquals(new ArrayList<>(), customer.getPurchases());
assertEquals(Money.of(USD, 200), customer.getMoney());
customer.return... |
public static String getType(String fileStreamHexHead) {
if(StrUtil.isBlank(fileStreamHexHead)){
return null;
}
if (MapUtil.isNotEmpty(FILE_TYPE_MAP)) {
for (final Entry<String, String> fileTypeEntry : FILE_TYPE_MAP.entrySet()) {
if (StrUtil.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())... | @Test
@Disabled
public void webpTest(){
// https://gitee.com/dromara/hutool/issues/I5BGTF
final File file = FileUtil.file("d:/test/a.webp");
final BufferedInputStream inputStream = FileUtil.getInputStream(file);
final String type = FileTypeUtil.getType(inputStream);
Console.log(type);
} |
public static AuditManagerS3A createAndStartAuditManager(
Configuration conf,
IOStatisticsStore iostatistics) {
AuditManagerS3A auditManager;
if (conf.getBoolean(AUDIT_ENABLED, AUDIT_ENABLED_DEFAULT)) {
auditManager = new ActiveAuditManagerS3A(
requireNonNull(iostatistics));
} el... | @Test
public void testRequestHandlerLoading() throws Throwable {
Configuration conf = noopAuditConfig();
conf.setClassLoader(this.getClass().getClassLoader());
conf.set(AUDIT_EXECUTION_INTERCEPTORS,
SimpleAWSExecutionInterceptor.CLASS);
AuditManagerS3A manager = AuditIntegration.createAndStart... |
@Override
public Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey,
SubscriberPermissionsOnProject subscriberPermissionsOnProject) {
verifyProjectKey(projectKey);
try (DbSession dbSession = dbClient.openSession(false)) {
Set<EmailSubscriberDto> emailSubscribe... | @Test
public void findSubscribedEmailRecipients_with_logins_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomA... |
@Override
public String getDataSource() {
return DataSourceConstant.DERBY;
} | @Test
void testGetDataSource() {
String dataSource = tenantCapacityMapperByDerby.getDataSource();
assertEquals(DataSourceConstant.DERBY, dataSource);
} |
@Override
public synchronized void cleanupAll() throws KafkaResourceManagerException {
LOG.info("Attempting to cleanup Kafka manager.");
boolean producedError = false;
// First, delete kafka topics if it was not given as a static argument
try {
if (!usingStaticTopic) {
kafkaClient.dele... | @Test
public void testCleanupAllShouldThrowErrorWhenKafkaClientFailsToDeleteTopic()
throws ExecutionException, InterruptedException {
when(kafkaClient.deleteTopics(anyCollection()).all().get())
.thenThrow(new ExecutionException(new RuntimeException("delete topic future fails")));
assertThrows(K... |
@Override
public ContainersInfo getContainers(HttpServletRequest req,
HttpServletResponse res, String appId, String appAttemptId) {
// Check that the appId/appAttemptId format is accurate
try {
RouterServerUtil.validateApplicationId(appId);
RouterServerUtil.validateApplicationAttemptId(appA... | @Test
public void testGetContainersNotExists() throws Exception {
ApplicationId appId = ApplicationId.newInstance(Time.now(), 1);
LambdaTestUtils.intercept(IllegalArgumentException.class,
"Parameter error, the appAttemptId is empty or null.",
() -> interceptor.getContainers(null, null, appId.t... |
public static FileRewriteCoordinator get() {
return INSTANCE;
} | @Test
public void testCommitMultipleRewrites() throws NoSuchTableException, IOException {
sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName);
Dataset<Row> df = newDF(1000);
// add first two files
df.coalesce(1).writeTo(tableName).append();
df.coalesce(1).writeTo(tableName).app... |
public static String getRemoteAddrFromRequest(Request request, Set<IpSubnet> trustedSubnets) {
final String remoteAddr = request.getRemoteAddr();
final String XForwardedFor = request.getHeader("X-Forwarded-For");
if (XForwardedFor != null) {
for (IpSubnet s : trustedSubnets) {
... | @Test
public void getRemoteAddrFromRequestWorksWithIPv6IfSubnetsContainsOnlyIPv6() throws Exception {
final Request request = mock(Request.class);
when(request.getRemoteAddr()).thenReturn("2001:DB8::42");
when(request.getHeader("X-Forwarded-For")).thenReturn("2001:DB8::1:2:3:4:5:6");
... |
Getter getGetter(Object targetObject, String attributeName, boolean failOnMissingReflectiveAttribute) {
Getter getter = getterCache.getGetter(targetObject.getClass(), attributeName);
if (getter == null) {
getter = instantiateGetter(targetObject, attributeName, failOnMissingReflectiveAttribut... | @Test
public void when_getGetterByReflection_then_getterInCache() {
// GIVEN
Extractors extractors = createExtractors(null);
// WHEN
Getter getterFirstInvocation = extractors.getGetter(bond, "car.power", true);
Getter getterSecondInvocation = extractors.getGetter(bond, "car.... |
@Override
public List<RuleNode> findRuleNodesByTenantIdAndType(TenantId tenantId, String type, String configurationSearch) {
return DaoUtil.convertDataList(ruleNodeRepository.findRuleNodesByTenantIdAndType(tenantId.getId(), type, configurationSearch));
} | @Test
public void testFindRuleNodesByTenantIdAndType() {
List<RuleNode> ruleNodes1 = ruleNodeDao.findRuleNodesByTenantIdAndType(tenantId1, "A", PREFIX_FOR_RULE_NODE_NAME);
assertEquals(20, ruleNodes1.size());
List<RuleNode> ruleNodes2 = ruleNodeDao.findRuleNodesByTenantIdAndType(tenantId2, ... |
public static HazelcastInstance newHazelcastInstance(Config config) {
if (config == null) {
config = Config.load();
}
return newHazelcastInstance(
config,
config.getInstanceName(),
new DefaultNodeContext()
);
} | @Test
public void test_NewInstance_configLoaded() {
hazelcastInstance = HazelcastInstanceFactory.newHazelcastInstance(null);
assertNotNull(hazelcastInstance.getConfig());
} |
public static QueryDescription forQueryMetadata(
final QueryMetadata queryMetadata,
final Map<KsqlHostInfoEntity, KsqlQueryStatus> ksqlHostQueryStatus
) {
if (queryMetadata instanceof PersistentQueryMetadata) {
final PersistentQueryMetadata persistentQuery = (PersistentQueryMetadata) queryMetada... | @Test
public void shouldReportPersistentQueriesStatus() {
assertThat(persistentQueryDescription.getState(), is(Optional.of("RUNNING")));
final Map<KsqlHostInfoEntity, KsqlQueryStatus> updatedStatusMap = new HashMap<>(STATUS_MAP);
updatedStatusMap.put(new KsqlHostInfoEntity("anotherhost", 8080), KsqlQuery... |
public static SerializableFunction<byte[], Row> getProtoBytesToRowFunction(
String fileDescriptorPath, String messageName) {
ProtoSchemaInfo dynamicProtoDomain = getProtoDomain(fileDescriptorPath, messageName);
ProtoDomain protoDomain = dynamicProtoDomain.getProtoDomain();
@SuppressWarnings("unchecke... | @Test
public void testProtoBytesToRowFunctionReturnsRowSuccess() {
// Create a proto bytes to row function
SerializableFunction<byte[], Row> protoBytesToRowFunction =
ProtoByteUtils.getProtoBytesToRowFunction(DESCRIPTOR_PATH, MESSAGE_NAME);
byte[] byteArray = {
8, -46, 9, 18, 3, 68, 111, 10... |
@Override
public <VR> KStream<K, VR> mapValues(final ValueMapper<? super V, ? extends VR> valueMapper) {
return mapValues(withKey(valueMapper));
} | @Test
public void shouldNotAllowNullMapperOnMapValuesWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.mapValues((ValueMapper<Object, Object>) null, Named.as("valueMapper")));
assertThat(exception.getMessage(), equ... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void to_map_of_primitive_to_list_of_unknown__throws_exception() {
DataTable table = parse("",
" | Annie M. G. | 1995-03-21 | 1911-03-20 |",
" | Roald | 1990-09-13 | 1916-09-13 |",
" | Astrid | 1907-10-14 | 1907-11-14 |");
CucumberDataTableExcepti... |
@Override
public Optional<HouseTable> findById(HouseTablePrimaryKey houseTablePrimaryKey) {
return getHtsRetryTemplate(
Arrays.asList(
HouseTableRepositoryStateUnkownException.class, IllegalStateException.class))
.execute(
context ->
apiInstance
... | @Test
public void testFindByIdWithErrors() {
HashMap<Integer, Class> map = new HashMap<>();
map.put(404, HouseTableNotFoundException.class);
map.put(409, HouseTableConcurrentUpdateException.class);
map.put(400, HouseTableCallerException.class);
for (HashMap.Entry<Integer, Class> entry : map.entry... |
@SuppressWarnings("unchecked")
public QueryMetadataHolder handleStatement(
final ServiceContext serviceContext,
final Map<String, Object> configOverrides,
final Map<String, Object> requestProperties,
final PreparedStatement<?> statement,
final Optional<Boolean> isInternalRequest,
f... | @Test
public void shouldRunScalablePushQuery_error() {
// Given:
when(ksqlEngine.executeScalablePushQuery(any(), any(), any(), any(), any(), any(), any(),
any()))
.thenThrow(new RuntimeException("Error executing!"));
// When:
Exception e = assertThrows(RuntimeException.class,
... |
public static void main(String[] args) {
// Getting the bar series
BarSeries series = CsvTradesLoader.loadBitstampSeries();
// Building the short selling trading strategy
Strategy strategy = buildShortSellingMomentumStrategy(series);
// Setting the trading cost models
d... | @Test
public void test() {
TradeCost.main(null);
} |
public static Object convertValue(String className, Object cleanValue, ClassLoader classLoader) {
// "null" string is converted to null
cleanValue = "null".equals(cleanValue) ? null : cleanValue;
if (!isPrimitive(className) && cleanValue == null) {
return null;
}
Cl... | @Test
public void convertValueFailUnsupportedTest() {
assertThatThrownBy(() -> convertValue(RuleScenarioRunnerHelperTest.class.getCanonicalName(), "Test", classLoader))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageEndingWith("Please use an MVEL expression to use i... |
public static Read<String> readStrings() {
return Read.newBuilder(
(PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8))
.setCoder(StringUtf8Coder.of())
.build();
} | @Test
public void testNullTopic() {
String subscription = "projects/project/subscriptions/subscription";
PubsubIO.Read<String> read =
PubsubIO.readStrings().fromSubscription(StaticValueProvider.of(subscription));
assertNull(read.getTopicProvider());
assertNotNull(read.getSubscriptionProvider()... |
@Override
protected DefaultDispatcherResourceManagerComponentFactory
createDispatcherResourceManagerComponentFactory(Configuration configuration)
throws IOException {
return DefaultDispatcherResourceManagerComponentFactory.createJobComponentFactory(
YarnResour... | @Test
void testCreateDispatcherResourceManagerComponentFactoryFailIfUsrLibDirDoesNotExist() {
final Configuration configuration = new Configuration();
configuration.set(
YarnConfigOptions.CLASSPATH_INCLUDE_USER_JAR,
YarnConfigOptions.UserJarInclusion.DISABLED);
... |
public String getMetricsName(Message in, String defaultValue) {
return getStringHeader(in, MetricsConstants.HEADER_METRIC_NAME, defaultValue);
} | @Test
public void testGetMetricsNameNotSet() {
when(in.getHeader(HEADER_METRIC_NAME, String.class)).thenReturn(null);
assertThat(okProducer.getMetricsName(in, "name"), is("name"));
inOrder.verify(in, times(1)).getHeader(HEADER_METRIC_NAME, String.class);
inOrder.verifyNoMoreInteracti... |
public static Builder builder() {
return new Builder();
} | @Test
public void testRoundTripSerDe() throws JsonProcessingException {
String fullJson = "{\"namespaces\":[[\"accounting\"],[\"tax\"]],\"next-page-token\":null}";
ListNamespacesResponse fullValue = ListNamespacesResponse.builder().addAll(NAMESPACES).build();
assertRoundTripSerializesEquallyFrom(fullJson,... |
public void setConfigParams(Dictionary<?, ?> properties) {
boolean restartRequired = setOpenFlowPorts(properties);
restartRequired |= setWorkerThreads(properties);
restartRequired |= setTlsParameters(properties);
if (restartRequired) {
restart();
}
} | @Test
public void testConfiguration() {
Dictionary<String, String> properties = new Hashtable<>();
properties.put("openflowPorts", "1,2,3,4,5");
properties.put("workerThreads", "5");
controller.setConfigParams(properties);
IntStream.rangeClosed(1, 5)
.forEach... |
public DataSchemaParser.ParseResult parseSources(String[] rawSources) throws IOException
{
Set<String> fileExtensions = _parserByFileExtension.keySet();
Map<String, List<String>> byExtension = new HashMap<>(fileExtensions.size());
for (String fileExtension : fileExtensions)
{
byExtension.put(fil... | @Test
public void testCustomResolverSchemaDirectory() throws Exception
{
String tempDirectoryPath = _tempDir.getAbsolutePath();
String jarFile = tempDirectoryPath + FS + "test.jar";
String schemaDir = TEST_RESOURCES_DIR + FS + "extensionSchemas";
SchemaDirectory customSchemaDirectory = () -> "custom... |
@Bean
public CircuitBreakerRegistry circuitBreakerRegistry(
EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry,
RegistryEventConsumer<CircuitBreaker> circuitBreakerRegistryEventConsumer,
@Qualifier("compositeCircuitBreakerCustomizer") CompositeCustomizer<CircuitBreakerConfigCus... | @Test
public void testCreateCircuitBreakerRegistryWithSharedConfigs() {
InstanceProperties defaultProperties = new InstanceProperties();
defaultProperties.setSlidingWindowSize(1000);
defaultProperties.setPermittedNumberOfCallsInHalfOpenState(100);
InstanceProperties sharedProperties ... |
@Override
public boolean match(Message msg, StreamRule rule) {
Object rawField = msg.getField(rule.getField());
if (rawField == null) {
return rule.getInverted();
}
if (rawField instanceof String) {
String field = (String) rawField;
Boolean resul... | @Test
public void testRandomNumberFieldNonMatch() throws Exception {
String fieldName = "sampleField";
Integer randomNumber = 4;
StreamRule rule = getSampleRule();
rule.setField(fieldName);
rule.setType(StreamRuleType.PRESENCE);
rule.setInverted(false);
Messa... |
void writeSample(String metricName, Number value, String... labelsAndValuesArray) {
SimpleTextOutputStream stream = initGaugeType(metricName);
stream.write(metricName).write('{');
for (int i = 0; i < labelsAndValuesArray.length; i += 2) {
String labelValue = labelsAndValuesArray[i + ... | @Test
public void canWriteSampleWithoutLabels() {
underTest.writeSample("my-metric", 123);
String actual = writeToString();
assertTrue(actual.startsWith("# TYPE my-metric gauge"), "Gauge type line missing");
assertTrue(actual.contains("my-metric{} 123"), "Metric line missing");
... |
@VisibleForTesting
public static void addUserAgentEnvironments(List<String> info) {
info.add(String.format(OS_FORMAT, OSUtils.OS_NAME));
if (EnvironmentUtils.isDocker()) {
info.add(DOCKER_KEY);
}
if (EnvironmentUtils.isKubernetes()) {
info.add(KUBERNETES_KEY);
}
if (EnvironmentUtil... | @Test
public void userAgentEnvironmentStringEmpty() {
List<String> info = new ArrayList<>();
Mockito.when(EC2MetadataUtils.getUserData())
.thenThrow(new SdkClientException("Unable to contact EC2 metadata service."));
UpdateCheckUtils.addUserAgentEnvironments(info);
Assert.assertEquals(1, info.... |
static String getOrValidInstanceLabelValue(String instance) {
if (instance == null) {
return "";
}
int i = Math.min(instance.length(), 63);
while (i > 0) {
char lastChar = instance.charAt(i - 1);
if (lastChar == '.' || lastChar == '-' || lastChar ==... | @Test
public void testValidInstanceNamesAsLabelValues() {
assertThat(Labels.getOrValidInstanceLabelValue(null), is(""));
assertThat(Labels.getOrValidInstanceLabelValue(""), is(""));
assertThat(Labels.getOrValidInstanceLabelValue("valid-label-value"), is("valid-label-value"));
asser... |
public static LinkExtractorParser getParser(String parserClassName)
throws LinkExtractorParseException {
// Is there a cached parser?
LinkExtractorParser parser = PARSERS.get(parserClassName);
if (parser != null) {
LOG.debug("Fetched {}", parserClassName);
re... | @Test
public void testReusableCache() throws Exception {
assertSame(BaseParser.getParser(ReusableParser.class.getCanonicalName()), BaseParser.getParser(ReusableParser.class.getCanonicalName()));
} |
void processExpiredBrokerHeartbeat(BrokerHeartbeatRequestData request) {
int brokerId = request.brokerId();
clusterControl.checkBrokerEpoch(brokerId, request.brokerEpoch());
clusterControl.heartbeatManager().touch(brokerId,
clusterControl.brokerRegistrations().get(brokerId).fence... | @Test
public void testProcessExpiredBrokerHeartbeat() {
MockTime mockTime = new MockTime(0, 0, 0);
ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().
setMockTime(mockTime).
build();
ctx.registerBrokers(0, 1, 2);
ctx.unfenc... |
public static long cityHash64(byte[] data, long seed) {
return CityHash.hash64(data, seed);
} | @Test
public void cityHash64Test(){
String s="Google发布的Hash计算算法:CityHash64 与 CityHash128";
final long hash = HashUtil.cityHash64(StrUtil.utf8Bytes(s));
assertEquals(0x1d408f2bbf967e2aL, hash);
} |
public boolean containsPK(List<String> cols) {
if (cols == null) {
return false;
}
List<String> pk = getPrimaryKeyOnlyName();
if (pk.isEmpty()) {
return false;
}
//at least contain one pk
if (cols.containsAll(pk)) {
return tr... | @Test
public void testContainsPKWithNullList() {
assertFalse(tableMeta.containsPK(null));
} |
@Override
public ResponseHeader execute() throws SQLException {
check(sqlStatement, connectionSession.getConnectionContext().getGrantee());
if (isDropCurrentDatabase(sqlStatement.getDatabaseName())) {
checkSupportedDropCurrentDatabase(connectionSession);
connectionSession.set... | @Test
void assertExecuteDropWithoutCurrentDatabase() throws SQLException {
when(sqlStatement.getDatabaseName()).thenReturn("foo_db");
ResponseHeader responseHeader = handler.execute();
verify(connectionSession, times(0)).setCurrentDatabaseName(null);
assertThat(responseHeader, instan... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_SHIFT_DOWN_performedAfterKnownNewReplicaOwnerKickedOutOfReplicas() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
new PartitionReplica(new Address("localhost", 5702)... |
@Override
public DdlCommand create(
final String sqlExpression,
final DdlStatement ddlStatement,
final SessionConfig config
) {
return FACTORIES
.getOrDefault(ddlStatement.getClass(), (statement, cf, ci) -> {
throw new KsqlException(
"Unable to find ddl command ... | @Test
public void shouldCreateCommandForCreateSourceStream() {
// Given:
final CreateStream statement = new CreateStream(SOME_NAME,
TableElements.of(
tableElement("COL1", new Type(SqlTypes.BIGINT)),
tableElement("COL2", new Type(SqlTypes.STRING))),
false, true, withProp... |
public PeriodStats plus(PeriodStats toAdd) {
PeriodStats result = new PeriodStats();
result.messagesSent += this.messagesSent;
result.messageSendErrors += this.messageSendErrors;
result.bytesSent += this.bytesSent;
result.messagesReceived += this.messagesReceived;
result... | @Test
void zeroPlus() {
PeriodStats one = new PeriodStats();
PeriodStats two = new PeriodStats();
two.messagesSent = 10;
two.messageSendErrors = 20;
two.bytesSent = 30;
two.messagesReceived = 40;
two.bytesReceived = 50;
two.totalMessagesSent = 60;
... |
@Override
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
if (metric == null) {
throw new NullPointerException("metric == null");
}
return metric;
} | @Test
public void registeringATimerTriggersNoNotification() {
assertThat(registry.register("thing", timer)).isEqualTo(timer);
verify(listener, never()).onTimerAdded("thing", timer);
} |
@Override
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
Object[] r = null;
r = getRow();
if ( r == null ) { // no more rows to be expected from the previous step(s)
setOutputDone();
return false;
}
if ( data.firstRow ) {
// T... | @Test
public void testProcessRow_success() throws Exception {
doReturn( new Object[1] ).when( constantSpy ).getRow();
doReturn( new RowMeta() ).when( constantSpy ).getInputRowMeta();
doReturn( new Object[1] ).when( rowMetaAndData ).getData();
boolean success = constantSpy.processRow( constantMeta, c... |
public static String sha512Hex(final String data) {
return Optional.ofNullable(data).filter(StringUtils::isNoneEmpty).map(item -> {
try {
return org.apache.commons.codec.digest.DigestUtils.sha512Hex(data);
} catch (Exception e) {
throw new ShenyuException(... | @Test
public void testSha512Hex() {
assertThat(DigestUtils.sha512Hex("123456"),
is("ba3253876aed6bc22d4a6ff53d8406c6ad864195ed144ab5c87621b6c233b548baeae6956df346ec8c17f5ea10f35ee3cbc514797ed7ddd3145464e2a0bab413"));
} |
@Override
public BulkOperationResponse executeBulkOperation(final BulkOperationRequest bulkOperationRequest, final C userContext, final AuditParams params) {
if (bulkOperationRequest.entityIds() == null || bulkOperationRequest.entityIds().isEmpty()) {
throw new BadRequestException(NO_ENTITY_IDS_... | @Test
void exceptionInAuditLogStoringDoesNotInfluenceResponse() throws Exception {
mockUserContext();
doThrow(new MongoException("MongoDB audit_log collection became anti-collection when bombed by Bozon particles")).when(auditEventSender).success(any(), anyString(), any());
final BulkOperati... |
@Override
public void notify(Metrics metrics) {
WithMetadata withMetadata = (WithMetadata) metrics;
MetricsMetaInfo meta = withMetadata.getMeta();
int scope = meta.getScope();
if (!DefaultScopeDefine.inServiceCatalog(scope) && !DefaultScopeDefine.inServiceInstanceCatalog(scope)
... | @Test
public void dontNotify() {
MetricsMetaInfo metadata = mock(MetricsMetaInfo.class);
when(metadata.getScope()).thenReturn(DefaultScopeDefine.SERVICE);
MockMetrics mockMetrics = mock(MockMetrics.class);
when(mockMetrics.getMeta()).thenReturn(metadata);
notifyHandler.not... |
public static StatementExecutorResponse validate(
final ConfiguredStatement<CreateConnector> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final CreateConnector createConnector = statement.getState... | @Test
public void shouldThrowOnValidateIfConnectorExists() {
// Given:
givenConnectorExists();
// When:
final KsqlRestException e = assertThrows(
KsqlRestException.class,
() -> ConnectExecutor.validate(CREATE_CONNECTOR_CONFIGURED, mock(SessionProperties.class), null, serviceContext));... |
@VisibleForTesting
int execute(String[] args) {
return commander.execute(args);
} | @Test(dataProvider = "desiredExpireTime")
public void commandCreateToken_WhenCreatingATokenWithExpiryTime_ShouldHaveTheDesiredExpireTime(String expireTime, int expireAsSec) throws Exception {
PrintStream oldStream = System.out;
try {
//Arrange
ByteArrayOutputStream baoStream ... |
public static OperationAuditor createAndInitAuditor(
Configuration conf,
String key,
OperationAuditorOptions options) throws IOException {
final Class<? extends OperationAuditor> auditClassname
= conf.getClass(
key,
LoggingAuditor.class,
OperationAuditor.class);
... | @Test
public void testCreateNonexistentAuditor() throws Throwable {
final Configuration conf = new Configuration();
OperationAuditorOptions options =
OperationAuditorOptions.builder()
.withConfiguration(conf)
.withIoStatisticsStore(ioStatistics);
conf.set(AUDIT_SERVICE_CLAS... |
@Override
public boolean addTopicConfig(final String topicName, final Map<String, ?> overrides) {
final ConfigResource resource = new ConfigResource(ConfigResource.Type.TOPIC, topicName);
final Map<String, String> stringConfigs = toStringConfigs(overrides);
try {
final Map<String, String> existing... | @Test
public void shouldSetStringTopicConfig() {
// Given:
givenTopicConfigs(
"peter",
overriddenConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "12345"),
defaultConfigEntry(TopicConfig.COMPRESSION_TYPE_CONFIG, "snappy")
);
final Map<String, ?> configOverrides = ImmutableMap.of(
... |
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
QueuePath childQueuePath) {
setTemplateEntriesForChild(conf, childQueuePath, false);
} | @Test
public void testTemplatePrecedence() {
conf.set(getTemplateKey(TEST_QUEUE_AB, "capacity"), "6w");
conf.set(getTemplateKey(TEST_QUEUE_A_WILDCARD, "capacity"), "4w");
conf.set(getTemplateKey(TEST_QUEUE_TWO_LEVEL_WILDCARDS, "capacity"), "2w");
AutoCreatedQueueTemplate template =
new AutoCr... |
@Override
public void shutdown() {
writeBehindService.stop();
connectionManager.shutdown();
} | @Test
public void testShutdown() {
RedissonClient r = createInstance();
Assertions.assertFalse(r.isShuttingDown());
Assertions.assertFalse(r.isShutdown());
r.shutdown();
Assertions.assertTrue(r.isShuttingDown());
Assertions.assertTrue(r.isShutdown());
} |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processSymbols(lineBuilder);
} catch (RangeOffsetConverter.RangeOffsetConverterException e) {
readError = new ReadError(Data.SYMBOLS, lineBuilder.getLine());
LOG.w... | @Test
public void read_symbols_when_reference_line_is_before_declaration_line() {
SymbolsLineReader symbolsLineReader = newReader(newSymbol(
newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_3, OFFSET_4, RANGE_LABEL_1),
newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_1, OFFSET_2, RANGE_LAB... |
public long contentSize()
{
long size = 0;
for (ZFrame f : frames) {
size += f.size();
}
return size;
} | @Test
public void testContentSize()
{
ZMsg msg = new ZMsg();
msg.add(new byte[0]);
assertThat(msg.contentSize(), is(0L));
msg.add(new byte[1]);
assertThat(msg.contentSize(), is(1L));
} |
public static String getFullGcsPath(String... pathParts) {
checkArgument(pathParts.length != 0, "Must provide at least one path part");
checkArgument(
stream(pathParts).noneMatch(Strings::isNullOrEmpty), "No path part can be null or empty");
return String.format("gs://%s", String.join("/", pathPart... | @Test
public void testGetFullGcsPathOneNullValue() {
assertThrows(
IllegalArgumentException.class,
() -> ArtifactUtils.getFullGcsPath("bucket", null, "dir2", "file"));
} |
public int getNewReservationFailedRetrieved() {
return numGetNewReservationFailedRetrieved.value();
} | @Test
public void testGetNewReservationRetrievedFailed() {
long totalBadBefore = metrics.getNewReservationFailedRetrieved();
badSubCluster.getNewReservationFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getNewReservationFailedRetrieved());
} |
public final Span joinSpan(TraceContext context) {
if (context == null) throw new NullPointerException("context == null");
if (!supportsJoin) return newChild(context);
// set shared flag if not already done
int flags = InternalPropagation.instance.flags(context);
if (!context.shared()) {
flag... | @Test void joinSpan_decorates() {
propagationFactory = baggageFactory;
TraceContext incoming = TraceContext.newBuilder().traceId(1L).spanId(2L).sampled(true)
.shared(true).build();
TraceContext joined = tracer.joinSpan(incoming).context();
assertThat(joined).isNotSameAs(incoming);
assertThat(... |
@Operation(summary = "queryAllWorkerGroupsPaging", description = "QUERY_WORKER_GROUP_PAGING_NOTES")
@Parameters({
@Parameter(name = "pageNo", description = "PAGE_NO", required = true, schema = @Schema(implementation = int.class, example = "1")),
@Parameter(name = "pageSize", description = "P... | @Test
public void testQueryAllWorkerGroupsPaging() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("pageNo", "2");
paramsMap.add("searchVal", "cxc");
paramsMap.add("pageSize", "2");
MvcResult mvcResult = mockMvc.perform(... |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldNotAllowConfigWithEmptyEnvironmentsBlock() {
String content = configWithEnvironments(
"<environments>\n"
+ "</environments>", CONFIG_SCHEMA_VERSION);
assertThatThrownBy(() -> xmlLoader.loadConfigHolder(content))
.as("XSD should no... |
void remove(int brokerId) {
BrokerHeartbeatState broker = brokers.remove(brokerId);
if (broker != null) {
untrack(broker);
}
} | @Test
public void testMetadataOffsetComparator() {
TreeSet<BrokerHeartbeatState> set =
new TreeSet<>(BrokerHeartbeatManager.MetadataOffsetComparator.INSTANCE);
BrokerHeartbeatState broker1 = new BrokerHeartbeatState(1);
BrokerHeartbeatState broker2 = new BrokerHeartbeatState(2);
... |
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction exchangeFunction) {
HttpHeaders readOnlyHttpHeaders = request.headers();
RequestTag requestTag = ThreadLocalUtils.getRequestTag();
if (requestTag == null) {
ThreadLocalUtils.setRequestData(new Re... | @Test
public void testFilterWithoutRequestTag() {
// when requestTag is null
ClientResponse response = function.filter(request, exchangeFunction).block();
Assert.assertNotNull(response);
HttpHeaders httpHeaders = response.headers().asHttpHeaders();
Assert.assertEquals(1, http... |
public static CloudConfiguration buildCloudConfigurationForStorage(Map<String, String> properties) {
return buildCloudConfigurationForStorage(properties, false);
} | @Test
public void testAliyunCloudConfiguration() {
Map<String, String> map = new HashMap<String, String>() {
{
put(CloudConfigurationConstants.ALIYUN_OSS_ACCESS_KEY, "XX");
put(CloudConfigurationConstants.ALIYUN_OSS_SECRET_KEY, "YY");
put(CloudConf... |
public Map<String, String> scheduleMinionTasks(@Nullable String taskType, @Nullable String tableNameWithType)
throws IOException, HttpException {
HttpPost httpPost = createHttpPostRequest(
MinionRequestURLBuilder.baseUrl(_controllerUrl).forTaskSchedule(taskType, tableNameWithType));
try (Closeable... | @Test
public void testTaskSchedule()
throws IOException, HttpException {
HttpServer httpServer = startServer(14202, "/tasks/schedule",
createHandler(200, "{\"SegmentGenerationAndPushTask\":\"Task_SegmentGenerationAndPushTask_1607470525615\"}",
0));
MinionClient minionClient = new Min... |
@Override
public SCMPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
SCMPropertyConfiguration scmConfiguration = extension.getSCMConfiguration(descriptor.id());
SCMView scmView = extension.getSCMView(descriptor.id());
PluggableInstanceSettings pluginSettingsAndView = getPluginSettin... | @Test
public void shouldThrowAnExceptionIfScmConfigReturnedByPluginIsNull() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
when(extension.getSCMConfiguration("plugin1")).thenReturn(null);
assertThatThrownBy(() -> new SCMPluginInfoBuilder(extension).plug... |
public static UnicastMappingInstruction unicastWeight(int weight) {
return new UnicastMappingInstruction.WeightMappingInstruction(
UnicastType.WEIGHT, weight);
} | @Test
public void testUnicastWeightMethod() {
final MappingInstruction instruction = MappingInstructions.unicastWeight(2);
final UnicastMappingInstruction.WeightMappingInstruction weightInstruction =
checkAndConvert(instruction,
UnicastMappingInstructi... |
public static String serializeRecordToJson(Record<GenericObject> record) {
checkNotNull(record, "record can't be null");
final org.apache.pulsar.client.api.Message<GenericObject> recordMessage = getMessage(record);
JsonObject result = new JsonObject();
result.addProperty(PAYLOAD_FIELD, ... | @Test
public void testJsonSerialization() {
final String[] keyNames = {"key1", "key2"};
final String key1Value = "test1";
final String key2Value = "test2";
final byte[][] keyValues = {key1Value.getBytes(), key2Value.getBytes()};
final String param = "param";
final St... |
@Override
public boolean load() {
boolean result = super.load();
result = result && this.parseDelayLevel();
result = result && this.correctDelayOffset();
return result;
} | @Test
public void testLoad() {
ConcurrentMap<Integer, Long> offsetTable = scheduleMessageService.getOffsetTable();
//offsetTable.put(0, 1L);
offsetTable.put(1, 3L);
offsetTable.put(2, 5L);
scheduleMessageService.persist();
ScheduleMessageService controlInstance = new... |
@Override
public void receiveSmsStatus(String channelCode, String text) throws Throwable {
// 获得渠道对应的 SmsClient 客户端
SmsClient smsClient = smsChannelService.getSmsClient(channelCode);
Assert.notNull(smsClient, "短信客户端({}) 不存在", channelCode);
// 解析内容
List<SmsReceiveRespDTO> rece... | @Test
public void testReceiveSmsStatus() throws Throwable {
// 准备参数
String channelCode = randomString();
String text = randomString();
// mock SmsClientFactory 的方法
SmsClient smsClient = spy(SmsClient.class);
when(smsChannelService.getSmsClient(eq(channelCode))).thenRe... |
@SuppressWarnings("unchecked") // safe covariant cast
static <T extends @Nullable Object> Correspondence<T, T> equality() {
return (Equality<T>) Equality.INSTANCE;
} | @Test
public void testEquality_viaIterableSubjectContains_failure() {
expectFailure
.whenTesting()
.that(ImmutableList.of(1.01, 2.02, 3.03))
.comparingElementsUsing(equality())
.contains(2.0);
// N.B. No "testing whether" fact:
assertFailureKeys("expected to contain", "but ... |
public Optional<BoolQueryBuilder> getPostFilters() {
return toBoolQuery(postFilters, (e, v) -> true);
} | @Test
public void getPostFilters_returns_empty_when_no_declared_sticky_topAggregation() {
AllFilters allFilters = randomNonEmptyAllFilters();
Set<TopAggregationDefinition<?>> atLeastOneNonStickyTopAggs = randomNonEmptyTopAggregations(() -> false);
RequestFiltersComputer underTest = new RequestFiltersCompu... |
@SuppressWarnings({"unchecked", "UnstableApiUsage"})
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement) {
if (!(statement.getStatement() instanceof DropStatement)) {
return statement;
}
final DropStatement dropStatement = (DropState... | @Test
public void shouldThrowOnDeleteTopicIfSourceIsReadOnly() {
// Given:
when(source.isSource()).thenReturn(true);
// When:
final Exception e = assertThrows(
RuntimeException.class,
() -> deleteInjector.inject(DROP_WITH_DELETE_TOPIC)
);
// Then:
assertThat(e.getMessage(... |
public static Date jsToDate( Object value, String classType ) throws KettleValueException {
double dbl;
if ( !classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
if ( classType.equalsIgnoreCase( "org.mozilla.javascript.NativeDate" ) ) {
dbl = Context.toNumber( value );
} else if ( classType.equal... | @Test
public void jsToDate_String() throws Exception {
assertEquals( new Date( 1 ), JavaScriptUtils.jsToDate( "1.0", String.class.getName() ) );
} |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testAlwaysTrue() {
Evaluator evaluator = new Evaluator(STRUCT, alwaysTrue());
assertThat(evaluator.eval(TestHelpers.Row.of())).as("always true").isTrue();
} |
public static String lowerUnderscoreToLowerCamelCase(String lowerUnderscore) {
StringBuilder builder = new StringBuilder();
int length = lowerUnderscore.length();
int index;
int fromIndex = 0;
while ((index = lowerUnderscore.indexOf('_', fromIndex)) != -1) {
builder.append(lowerUnderscore, fr... | @Test
public void testLowerUnderscoreToLowerCamelCase() {
assertEquals(StringUtils.lowerUnderscoreToLowerCamelCase("some_variable"), "someVariable");
assertEquals(
StringUtils.lowerUnderscoreToLowerCamelCase("some_long_variable"), "someLongVariable");
assertEquals(
StringUtils.lowerUndersc... |
static int toInteger(final JsonNode object) {
if (object instanceof NumericNode) {
return object.intValue();
}
if (object instanceof TextNode) {
try {
return Integer.parseInt(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionException(... | @Test(expected = IllegalArgumentException.class)
public void shouldFailWhenConvertingIncompatibleLong() {
JsonSerdeUtils.toInteger(JsonNodeFactory.instance.booleanNode(true));
} |
public MetadataReportBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(this.parameters, appendParameters);
return getThis();
} | @Test
void appendParameters() {
Map<String, String> source = new HashMap<>();
source.put("default.num", "one");
source.put("num", "ONE");
MetadataReportBuilder builder = new MetadataReportBuilder();
builder.appendParameters(source);
Map<String, String> parameters = ... |
List<ParsedTerm> identifyUnknownFields(final Set<String> availableFields, final List<ParsedTerm> terms) {
final Map<String, List<ParsedTerm>> groupedByField = terms.stream()
.filter(t -> !t.isDefaultField())
.filter(term -> !SEARCHABLE_ES_FIELDS.contains(term.getRealFieldName()))... | @Test
void testDoesNotIdentifySpecialIdFieldAsUnknown() {
final List<ParsedTerm> unknownFields = toTest.identifyUnknownFields(
Set.of("some_normal_field"),
List.of(ParsedTerm.create("_id", "buba"))
);
assertTrue(unknownFields.isEmpty());
} |
public static int getLevelOfNode(int nodeOrder) {
return QuickMath.log2(nodeOrder + 1);
} | @Test
public void testGetLevelOfNode() {
assertEquals(0, MerkleTreeUtil.getLevelOfNode(0));
assertEquals(1, MerkleTreeUtil.getLevelOfNode(1));
assertEquals(1, MerkleTreeUtil.getLevelOfNode(2));
assertEquals(2, MerkleTreeUtil.getLevelOfNode(3));
assertEquals(2, MerkleTreeUtil.... |
@Override
protected HttpApiSpecificInfo doParse(final ApiBean.ApiDefinition apiDefinition) {
RequestMapping requestMapping = apiDefinition.getAnnotation(RequestMapping.class);
String produce = requestMapping.produces().length == 0 ? ShenyuClientConstants.MEDIA_TYPE_ALL_VALUE : String.join(",", req... | @Test
public void testDoParse() throws Exception {
ApiBean apiBean = createSimpleApiBean();
AbstractApiDocRegistrar.HttpApiSpecificInfo httpApiSpecificInfo =
httpApiDocRegistrar.doParse(apiBean.getApiDefinitions().get(0));
List<ApiHttpMethodEnum> apiHttpMeth... |
public void replaceAction(@NonNull Action a) {
addOrReplaceAction(a);
} | @Test
public void replaceAction_null() {
assertThrows(IllegalArgumentException.class, () -> thing.replaceAction(null));
} |
@Override
public int getOrder() {
return PluginEnum.MOTAN.getCode();
} | @Test
public void testGetOrder() {
Assertions.assertEquals(motanPlugin.getOrder(), 310);
} |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromSnapshotIdWithEmptyTable() {
ScanContext scanContextWithInvalidSnapshotId =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_ID)
.startSnapshotId(1L)
.build();
ContinuousSplitPlannerImpl... |
@Override
public void configure(Map<String, ?> configs) {
PushHttpMetricsReporterConfig config = new PushHttpMetricsReporterConfig(CONFIG_DEF, configs);
try {
url = new URL(config.getString(METRICS_URL_CONFIG));
} catch (MalformedURLException e) {
throw new ConfigExce... | @Test
public void testConfigureMissingPeriod() {
Map<String, String> config = new HashMap<>();
config.put(PushHttpMetricsReporter.METRICS_URL_CONFIG, URL.toString());
assertThrows(ConfigException.class, () -> reporter.configure(config));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.