focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static boolean hasSchemePattern( String path ) {
return hasSchemePattern( path, PROVIDER_PATTERN_SCHEME );
} | @Test
public void testHasSchemeWithSpaces() {
String vfsFilename = "/tmp/This is a text file4551613284841905296.txt";
String vfsFilenameWithScheme = "hdfs://tmp/This is a text file4551613284841905296.txt";
boolean testVfsFilename = KettleVFS.hasSchemePattern( vfsFilename, PROVIDER_PATTERN_SCHEME );
a... |
public InetSocketAddress getRpcServerAddress() {
return this.rpcAddress;
} | @Test
public void testRouterRpcWithNoSubclusters() throws IOException {
Router router = new Router();
router.init(new RouterConfigBuilder(conf).rpc().build());
router.start();
InetSocketAddress serverAddress = router.getRpcServerAddress();
DFSClient dfsClient = new DFSClient(serverAddress, conf)... |
public static Range<PartitionKey> createRange(String lowerBound, String upperBound, Column partitionColumn)
throws AnalysisException {
if (lowerBound == null && upperBound == null) {
return null;
}
PartitionValue lowerValue = new PartitionValue(lowerBound);
Partit... | @Test
public void testMappingRangeList() throws AnalysisException {
Map<String, Range<PartitionKey>> baseRangeMap = Maps.newHashMap();
Map<String, Range<PartitionKey>> result;
baseRangeMap.put("p202001", createRange("2020-01-01", "2020-02-01"));
baseRangeMap.put("p202002", createRang... |
protected void refreshDomain() {
Set<String> keySet = new HashSet<>();
for (Map.Entry<String, List<ConsumerConfig>> entry : notifyListeners.entrySet()) {
String directUrl = entry.getKey();
String[] providerStrs = StringUtils.splitWithCommaOrSemicolon(directUrl);
keySe... | @Test
public void testRefreshDomain() {
ConsumerConfig<Object> consumerConfig = new ConsumerConfig<>();
String directUrl1 = "bolt://alipay.com";
String directUrl2 = "bolt://taobao.com";
String directUrl = directUrl1 + ";" + directUrl2;
consumerConfig.setDirectUrl(directUrl);
... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testReward()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your reward is: <col=ff0000>1</col> x <col=ff0000>Kebab</col>.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
verify(configManager, never()).setRSProfileConfiguration(anyString(), anyString(), anyInt(... |
public static ThrowableType getThrowableType(Throwable cause) {
final ThrowableAnnotation annotation =
cause.getClass().getAnnotation(ThrowableAnnotation.class);
return annotation == null ? ThrowableType.RecoverableError : annotation.value();
} | @Test
void testThrowableType_EnvironmentError() {
assertThat(ThrowableClassifier.getThrowableType(new TestEnvironmentErrorException()))
.isEqualTo(ThrowableType.EnvironmentError);
} |
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
QueuePath childQueuePath) {
setTemplateEntriesForChild(conf, childQueuePath, false);
} | @Test
public void testIgnoredTemplateWhenQueuePathIsInvalid() {
QueuePath invalidPath = new QueuePath("a");
conf.set(getTemplateKey(invalidPath, "capacity"), "6w");
AutoCreatedQueueTemplate template =
new AutoCreatedQueueTemplate(conf, invalidPath);
template.setTemplateEntriesForChild(conf, TE... |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldCloseIterator_rangeBothBounds() {
// Given:
final StateQueryResult result = new StateQueryResult();
final QueryResult queryResult = QueryResult.forResult(keyValueIterator);
queryResult.setPosition(POSITION);
result.addResult(PARTITION, queryResult);
when(kafkaStreams.qu... |
public <T extends AwsSyncClientBuilder> void applyHttpClientConfigurations(T builder) {
if (Strings.isNullOrEmpty(httpClientType)) {
httpClientType = CLIENT_TYPE_DEFAULT;
}
switch (httpClientType) {
case CLIENT_TYPE_URLCONNECTION:
UrlConnectionHttpClientConfigurations urlConnectionHttpC... | @Test
public void testUrlHttpClientConfiguration() {
Map<String, String> properties = Maps.newHashMap();
properties.put(HttpClientProperties.CLIENT_TYPE, "urlconnection");
HttpClientProperties httpProperties = new HttpClientProperties(properties);
S3ClientBuilder mockS3ClientBuilder = Mockito.mock(S3C... |
public static DistCpOptions parse(String[] args)
throws IllegalArgumentException {
CommandLineParser parser = new CustomParser();
CommandLine command;
try {
command = parser.parse(cliOptions, args, true);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to pars... | @Test
public void testTargetPath() {
DistCpOptions options = OptionsParser.parse(new String[] {
"-f",
"hdfs://localhost:8020/source/first",
"hdfs://localhost:8020/target/"});
Assert.assertEquals(options.getTargetPath(), new Path("hdfs://localhost:8020/target/"));
} |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
cachedNanoClock.update(nowNs);
dutyCycleTracker.measureAndUpdate(nowNs);
int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT);
final int bytesReceived = dataTransportPolle... | @Test
void shouldHandleNonZeroTermOffsetCorrectly()
{
final int initialTermOffset = align(TERM_BUFFER_LENGTH / 16, FrameDescriptor.FRAME_ALIGNMENT);
final int alignedDataFrameLength =
align(DataHeaderFlyweight.HEADER_LENGTH + FAKE_PAYLOAD.length, FrameDescriptor.FRAME_ALIGNMENT);
... |
@Override
public boolean canHandleReturnType(Class returnType) {
return (Flux.class.isAssignableFrom(returnType)) || (Mono.class
.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(reactorRetryAspectExt.canHandleReturnType(Mono.class)).isTrue();
assertThat(reactorRetryAspectExt.canHandleReturnType(Flux.class)).isTrue();
} |
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
JsonNode jsonValue;
// This handles a tombstone message
if (value == null) {
return SchemaAndValue.NULL;
}
try {
jsonValue = deserializer.deserialize(topic, value);
}... | @Test
public void decimalToConnectWithDefaultValue() {
BigDecimal reference = new BigDecimal(new BigInteger("156"), 2);
Schema schema = Decimal.builder(2).defaultValue(reference).build();
String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"org.apache.kafka.connect.data.Decimal\", ... |
public static FieldScope ignoringFieldDescriptors(
FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) {
return FieldScopeImpl.createIgnoringFieldDescriptors(asList(firstFieldDescriptor, rest));
} | @Test
public void testIgnoreFieldOfSubMessage() {
// Ignore o_int of sub message fields.
Message message = parse("o_int: 1 o_sub_test_message: { o_int: 2 r_string: \"foo\" }");
Message diffMessage1 = parse("o_int: 2 o_sub_test_message: { o_int: 2 r_string: \"foo\" }");
Message diffMessage2 = parse("o_... |
public static KStreamHolder<GenericKey> build(
final KStreamHolder<?> stream,
final StreamSelectKeyV1 selectKey,
final RuntimeBuildContext buildContext
) {
final LogicalSchema sourceSchema = stream.getSchema();
final CompiledExpression expression = buildExpressionEvaluator(
selectKe... | @Test
public void shouldFilterOutNullValues() {
// When:
selectKey.build(planBuilder, planInfo);
// Then:
verify(kstream).filter(predicateCaptor.capture());
final Predicate<GenericKey, GenericRow> predicate = getPredicate();
assertThat(predicate.test(SOURCE_KEY, null), is(false));
} |
public static boolean deleteQuietly(@Nullable File file) {
if (file == null) {
return false;
}
return deleteQuietly(file.toPath());
} | @Test
public void deleteQuietly_does_not_fail_if_argument_is_null() {
FileUtils.deleteQuietly((File) null);
FileUtils.deleteQuietly((Path) null);
} |
@VisibleForTesting
static String generateLogUrl(String pattern, String jobId, String taskManagerId) {
String generatedUrl = pattern.replaceAll("<jobid>", jobId);
if (null != taskManagerId) {
generatedUrl = generatedUrl.replaceAll("<tmid>", taskManagerId);
}
return generat... | @Test
void testGenerateJobManagerLogUrl() {
final String pattern = "http://localhost/<jobid>/log";
final String jobId = "jobid";
final String generatedUrl = GeneratedLogUrlHandler.generateLogUrl(pattern, jobId, null);
assertThat(generatedUrl).isEqualTo(pattern.replace("<jobid>", jo... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testUnpartitionedYears() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
YearsFunction.TimestampToYearsFunction function = new YearsFunction.TimestampToYearsFunction();
UserDefinedScalarFunc udf = toUDF(function, expr... |
@Override
public boolean processData(DistroData distroData) {
switch (distroData.getType()) {
case ADD:
case CHANGE:
ClientSyncData clientSyncData = ApplicationUtils.getBean(Serializer.class)
.deserialize(distroData.getContent(), ClientSyncData... | @Test
void testProcessDataForChangeClient() {
distroData.setType(DataOperation.CHANGE);
assertEquals(0L, client.getRevision());
assertEquals(0, client.getAllPublishedService().size());
distroClientDataProcessor.processData(distroData);
verify(clientManager).syncClientConnecte... |
public static void setLocalDirStickyBit(String dir) {
try {
// Support for sticky bit is platform specific. Check if the path starts with "/" and if so,
// assume that the host supports the chmod command.
if (dir.startsWith(AlluxioURI.SEPARATOR)) {
// TODO(peis): This is very slow. Conside... | @Test
public void setLocalDirStickyBit() throws IOException {
File tempFolder = mTestFolder.newFolder("dirToModify");
// Only test this functionality of the absolute path of the temporary directory starts with "/",
// which implies the host should support "chmod".
if (tempFolder.getAbsolutePath().star... |
public static MetricName getMetricName(
String group,
String typeName,
String name
) {
return getMetricName(
group,
typeName,
name,
null
);
} | @Test
public void testTaggedMetricName() {
LinkedHashMap<String, String> tags = new LinkedHashMap<>();
tags.put("foo", "bar");
tags.put("bar", "baz");
tags.put("baz", "raz.taz");
MetricName metricName = KafkaYammerMetrics.getMetricName(
"kafka.metrics",
... |
@Override
public void handleTenantMenu(TenantMenuHandler handler) {
// 如果禁用,则不执行逻辑
if (isTenantDisable()) {
return;
}
// 获得租户,然后获得菜单
TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId());
Set<Long> menuIds;
if (isSystemTenant(tenan... | @Test // 普通租户的情况
public void testHandleTenantMenu_normal() {
// 准备参数
TenantMenuHandler handler = mock(TenantMenuHandler.class);
// mock 未禁用
when(tenantProperties.getEnable()).thenReturn(true);
// mock 租户
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackage... |
public void processOnce() throws IOException {
// set status of query to OK.
ctx.getState().reset();
executor = null;
// reset sequence id of MySQL protocol
final MysqlChannel channel = ctx.getMysqlChannel();
channel.setSequenceId(0);
// read packet from channel
... | @Test
public void testChangeUser() throws IOException {
ConnectContext ctx = initMockContext(mockChannel(changeUserPacket), GlobalStateMgr.getCurrentState());
ConnectProcessor processor = new ConnectProcessor(ctx);
processor.processOnce();
Assert.assertEquals(MysqlCommand.COM_CHANGE... |
private List<ColumnStatistics> toColumnStatistics(HiveWriterVersion hiveWriterVersion, List<DwrfProto.ColumnStatistics> columnStatistics, boolean isRowGroup)
{
if (columnStatistics == null) {
return ImmutableList.of();
}
return columnStatistics.stream()
.map(stat... | @Test(dataProvider = "columnStatisticsSupplier")
public void testToColumnStatisticsRoundtrip(ColumnStatistics input, ColumnStatistics output, DwrfMetadataReader dwrfMetadataReader)
{
DwrfProto.ColumnStatistics dwrfColumnStatistics = DwrfMetadataWriter.toColumnStatistics(input);
ColumnStatistics ... |
@Transactional
public void updateCustomChecklist(User user, CustomChecklistUpdateRequest request) {
List<Integer> questionIds = request.questionIds();
validateCustomChecklistQuestionsIsNotEmpty(questionIds);
validateCustomChecklistQuestionsDuplication(questionIds);
customChecklistQu... | @DisplayName("커스텀 체크리스트 업데이트 실패 : 질문 id가 유효하지 않을 때")
@Test
void updateCustomChecklist_invalidQuestionId_exception() {
// given
CustomChecklistUpdateRequest request = CUSTOM_CHECKLIST_UPDATE_REQUEST_INVALID;
// when & then
assertThatThrownBy(() -> checklistService.updateCustomChe... |
@Activate
public void activate(ComponentContext context) {
cfgService.registerProperties(getClass());
modified(context);
Security.addProvider(new BouncyCastleProvider());
clusterCommunicator.<NetconfProxyMessage>addSubscriber(
SEND_REQUEST_SUBJECT_STRING,
... | @Test
public void testActivate() {
assertEquals("Incorrect NetConf connect timeout, should be default",
5, ctrl.netconfConnectTimeout);
assertEquals("Incorrect NetConf reply timeout, should be default",
5, ctrl.netconfReplyTimeout);
ctrl.activate(nul... |
public static Resource getResource(File workingDir, String path) {
if (path.startsWith(Resource.CLASSPATH_COLON)) {
path = removePrefix(path);
File file = classPathToFile(path);
if (file != null) {
return new FileResource(file, true, path);
}
... | @Test
void testGetClassPathFileByPath() {
Resource resource = ResourceUtils.getResource(wd, "classpath:com/intuit/karate/resource/test1.txt");
assertTrue(resource.isFile());
assertTrue(resource.isClassPath());
assertEquals("com/intuit/karate/resource/test1.txt", resource.getRelativeP... |
public PipelineNode.PTransformNode getProducer(PipelineNode.PCollectionNode pcollection) {
return (PipelineNode.PTransformNode)
Iterables.getOnlyElement(pipelineNetwork.predecessors(pcollection));
} | @Test
public void getProducer() {
Pipeline p = Pipeline.create();
PCollection<Long> longs = p.apply("BoundedRead", Read.from(CountingSource.upTo(100L)));
PCollectionList.of(longs).and(longs).and(longs).apply("flatten", Flatten.pCollections());
Components components = PipelineTranslation.toProto(p).ge... |
public static Caffeine<Object, Object> from(CaffeineSpec spec) {
Caffeine<Object, Object> builder = spec.toBuilder();
builder.strictParsing = false;
return builder;
} | @Test
public void fromString_null() {
assertThrows(NullPointerException.class, () -> Caffeine.from((String) null));
} |
public String getDiscriminatingValue(ILoggingEvent event) {
// http://jira.qos.ch/browse/LBCLASSIC-213
Map<String, String> mdcMap = event.getMDCPropertyMap();
if (mdcMap == null) {
return defaultValue;
}
String mdcValue = mdcMap.get(key);
if (mdcValue == null) {
return defaultValue;
... | @Test
public void nullMDC() {
event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
assertTrue(event.getMDCPropertyMap().isEmpty());
String discriminatorValue = discriminator.getDiscriminatingValue(event);
assertEquals(DEFAULT_VAL, discriminatorValue);
} |
@Override
public int compare(EvictableEntryView e1, EvictableEntryView e2) {
long time1 = Math.max(e1.getCreationTime(), e1.getLastAccessTime());
long time2 = Math.max(e2.getCreationTime(), e2.getLastAccessTime());
return Long.compare(time1, time2);
} | @Test
public void lru_comparator_does_not_prematurely_select_newly_created_entries() {
// 0. Entries to sort
List<TestEntryView> givenEntries = new LinkedList<>();
givenEntries.add(new TestEntryView(1, 1, 0));
givenEntries.add(new TestEntryView(2, 2, 3));
givenEntries.add(new... |
static void applySchemaUpdates(Table table, SchemaUpdate.Consumer updates) {
if (updates == null || updates.empty()) {
// no updates to apply
return;
}
Tasks.range(1)
.retry(IcebergSinkConfig.SCHEMA_UPDATE_RETRIES)
.run(notUsed -> commitSchemaUpdates(table, updates));
} | @Test
public void testApplySchemaUpdatesNoUpdates() {
Table table = mock(Table.class);
when(table.schema()).thenReturn(SIMPLE_SCHEMA);
SchemaUtils.applySchemaUpdates(table, null);
verify(table, times(0)).refresh();
verify(table, times(0)).updateSchema();
SchemaUtils.applySchemaUpdates(table,... |
@Override
public Long createFileConfig(FileConfigSaveReqVO createReqVO) {
FileConfigDO fileConfig = FileConfigConvert.INSTANCE.convert(createReqVO)
.setConfig(parseClientConfig(createReqVO.getStorage(), createReqVO.getConfig()))
.setMaster(false); // 默认非 master
fileCo... | @Test
public void testCreateFileConfig_success() {
// 准备参数
Map<String, Object> config = MapUtil.<String, Object>builder().put("basePath", "/yunai")
.put("domain", "https://www.iocoder.cn").build();
FileConfigSaveReqVO reqVO = randomPojo(FileConfigSaveReqVO.class,
... |
public Trans loadTransFromFilesystem( String initialDir, String filename, String jarFilename, Serializable base64Zip ) throws Exception {
Trans trans = null;
File zip;
if ( base64Zip != null && ( zip = decodeBase64ToZipFile( base64Zip, true ) ) != null ) {
// update filename to a meaningful, 'ETL-fi... | @Test
public void testMetastoreFromFilesystemAddedIn() throws Exception {
String fullPath = getClass().getResource( SAMPLE_KTR ).getPath();
Trans trans = mockedPanCommandExecutor.loadTransFromFilesystem( "", fullPath, "", "" );
assertNotNull( trans );
assertNotNull( trans.getMetaStore() );
} |
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (managerPrefix != null ? managerPrefix.hashCode() : 0);
result = 31 * result + (uriString != null ? uriString.hashCode() : 0);
... | @Test
public void testHashCode() {
CacheConfig cacheConfig = new CacheConfig();
assertTrue(cacheConfig.hashCode() != 0);
} |
@Override
public long getAnalysisDate() {
checkState(analysisDate.isInitialized(), "Analysis date has not been set");
return this.analysisDate.getProperty();
} | @Test
public void getAnalysisDate_throws_ISE_when_holder_is_not_initialized() {
assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getAnalysisDate())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis date has not been set");
} |
public void wakeOrSkipNextWait() {
// Take early lock to avoid race-conditions. Lock is also taken in wake() (lock is re-entrant)
synchronized (lock) {
final boolean awoken = wake();
if (!awoken) {
LOG.debug("Waiter not waiting, instructing to skip next wait.");
this.skipNextWait = t... | @Test
public void should_not_wait_if_instructed_to_skip_next()
throws ExecutionException, InterruptedException {
Waiter waiter = new Waiter(Duration.ofMillis(1000));
waiter.wakeOrSkipNextWait(); // set skip
Future<Long> waitTime = executor.submit(new WaitForWaiter(waiter));
assertTrue(waitTime.... |
@Override
public boolean isDataNodeAvailable(long dataNodeId) {
// DataNode and ComputeNode is exchangeable in SHARED_DATA mode
return availableID2ComputeNode.containsKey(dataNodeId);
} | @Test
public void testIsDataNodeAvailable() {
HostBlacklist blockList = SimpleScheduler.getHostBlacklist();
blockList.hostBlacklist.clear();
SystemInfoService sysInfo = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo();
List<Long> availList = prepareNodeAliveAndBlock(sy... |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
@Category(NeedsRunner.class)
public void testMapInMemorySideInput() {
final PCollectionView<Map<String, Integer>> view =
pipeline
.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3)))
.apply(View.<String, Integer>asMap().inMemory());
PCollection<KV<String... |
BackgroundJobRunner getBackgroundJobRunner(Job job) {
assertJobExists(job.getJobDetails());
return backgroundJobRunners.stream()
.filter(jobRunner -> jobRunner.supports(job))
.findFirst()
.orElseThrow(() -> problematicConfigurationException("Could not find... | @Test
void getBackgroundJobRunnerForNonIoCStaticJobWithoutInstance() {
jobActivator.clear();
final Job job = anEnqueuedJob()
.withJobDetails(StaticTestService::doWorkInStaticMethodWithoutParameter)
.build();
assertThat(backgroundJobServer.getBackgroundJobRunn... |
public static int pixelYToTileY(double pixelY, byte zoomLevel, int tileSize) {
return (int) Math.min(Math.max(pixelY / tileSize, 0), Math.pow(2, zoomLevel) - 1);
} | @Test
public void pixelYToTileYTest() {
for (int tileSize : TILE_SIZES) {
for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) {
Assert.assertEquals(0, MercatorProjection.pixelYToTileY(0, zoomLevel, tileSize));
Assert.assertEquals(0, Mer... |
public void acceptRow(final List<?> key, final GenericRow value) {
try {
if (passedLimit()) {
return;
}
final KeyValue<List<?>, GenericRow> row = keyValue(key, value);
final KeyValueMetadata<List<?>, GenericRow> keyValueMetadata = new KeyValueMetadata<>(row);
while (!closed) ... | @Test
public void shouldQueue() {
// When:
queue.acceptRow(KEY_ONE, VAL_ONE);
queue.acceptRow(KEY_TWO, VAL_TWO);
// Then:
assertThat(drainValues(), contains(keyValue(KEY_ONE, VAL_ONE), keyValue(KEY_TWO, VAL_TWO)));
} |
public String getActions() {
return actions;
} | @Test
public void testGetActions() {
Permission permission = new Permission("classname", "name", "actions");
assertEquals("actions", permission.getActions());
} |
@Override
public long position() throws IOException {
checkOpen();
long pos;
synchronized (this) {
boolean completed = false;
try {
begin(); // don't call beginBlocking() because this method doesn't block
if (!isOpen()) {
return 0; // AsynchronousCloseException will... | @Test
public void testPosition() throws IOException {
FileChannel channel = channel(regularFile(10), READ);
assertEquals(0, channel.position());
assertSame(channel, channel.position(100));
assertEquals(100, channel.position());
} |
@OnMessage
public void onMessage(final String message, final Session session) {
if (!Objects.equals(message, DataEventTypeEnum.MYSELF.name())
&& !Objects.equals(message, DataEventTypeEnum.RUNNING_MODE.name())) {
return;
}
if (Objects.equals(message, DataE... | @Test
public void testOnMessage() {
ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class);
SpringBeanUtils.getInstance().setApplicationContext(context);
when(SpringBeanUtils.getInstance().getBean(SyncDataService.class)).thenReturn(syncDataService);
when(... |
@Override
Map<KeyValueSegment, WriteBatch> getWriteBatches(final Collection<ConsumerRecord<byte[], byte[]>> records) {
final Map<KeyValueSegment, WriteBatch> writeBatchMap = new HashMap<>();
for (final ConsumerRecord<byte[], byte[]> record : records) {
final long timestamp = WindowKeySch... | @Test
public void shouldCreateEmptyWriteBatches() {
final Collection<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>();
final Map<KeyValueSegment, WriteBatch> writeBatchMap = bytesStore.getWriteBatches(records);
assertEquals(0, writeBatchMap.size());
} |
@Override
protected MeterProvider defaultProvider() {
return defaultProvider;
} | @Test
public void testAddBatchFromMeterProgrammable() {
initMeterStore();
List<MeterOperation> operations = ImmutableList.of(new MeterOperation(mProgrammable, MeterOperation.Type.ADD));
manager.defaultProvider().performMeterOperation(PROGRAMMABLE_DID, new MeterOperations(operations));
... |
public DataTable subTable(int fromRow, int fromColumn) {
return subTable(fromRow, fromColumn, height(), width());
} | @Test
void subTable_throws_for_invalid_from_to_column() {
DataTable table = createSimpleTable();
assertThrows(IllegalArgumentException.class, () -> table.subTable(0, 2, 1, 1));
} |
@Override
public List<String> splitAndEvaluate() {
try (ReflectContext context = new ReflectContext(JAVA_CLASSPATH)) {
if (Strings.isNullOrEmpty(inlineExpression)) {
return Collections.emptyList();
}
return flatten(evaluate(context, GroovyUtils.split(handl... | @Test
void assertEvaluateForCalculate() {
List<String> expected = createInlineExpressionParser("t_${[\"new${1+2}\",'old']}_order_${1..2}").splitAndEvaluate();
assertThat(expected.size(), is(4));
assertThat(expected, hasItems("t_new3_order_1", "t_new3_order_2", "t_old_order_1", "t_old_order_2... |
public static Date parseDateTime(String s) {
try {
return Date.from(OffsetDateTime.parse(s, formatter).toInstant());
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Fail to parse date: " + s, e);
}
} | @Test
public void fail_if_bad_format() {
try {
UtcDateUtils.parseDateTime("2014-01-14");
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Fail to parse date: 2014-01-14");
}
} |
@Override
public void upload(UploadTask uploadTask) throws IOException {
Throwable error = getErrorSafe();
if (error != null) {
LOG.debug("don't persist {} changesets, already failed", uploadTask.changeSets.size());
uploadTask.fail(error);
return;
}
... | @Test
void testUploadTimeout() throws Exception {
AtomicReference<List<SequenceNumber>> failed = new AtomicReference<>();
UploadTask upload =
new UploadTask(getChanges(4), unused -> {}, (sqn, error) -> failed.set(sqn));
ManuallyTriggeredScheduledExecutorService executorServic... |
@Override
public List<User> list(UserSearchCriteria s) {
// @formatter:off
return getSpi().list(getApiVersion(), s.getContext(), s.getPage(), s.getPerPage(), s.getSearch(), s.getExclude(),
s.getInclude(), s.getOffset(), s.getOrder(), s.getOrderBy(), s.getSlug(),
s.get... | @Test
public void testListUsers() {
final UserSearchCriteria criteria = new UserSearchCriteria();
criteria.setPage(1);
criteria.setPerPage(10);
final List<User> users = serviceUsers.list(criteria);
assertThat(users, is(not(emptyCollectionOf(User.class))));
assertThat(... |
static Map<String, Object> of(final Task task) {
return Map.of(
"id", task.getId(),
"type", task.getType()
);
} | @Test
void shouldGetEmptyVariables() {
Map<String, Object> variables = new RunVariables.DefaultBuilder().build(new RunContextLogger());
Assertions.assertEquals(Map.of("envs", Map.of(), "globals", Map.of()), variables);
} |
public static String fix(final String raw) {
if ( raw == null || "".equals( raw.trim() )) {
return raw;
}
MacroProcessor macroProcessor = new MacroProcessor();
macroProcessor.setMacros( macros );
return macroProcessor.parse( raw );
} | @Test
public void testMoreAssertCraziness() {
final String raw = "foobar(); (insert(new String(\"blah\").get()); bangBangYudoHono();)";
assertEqualsIgnoreWhitespace( "foobar(); (drools.insert(new String(\"blah\").get()); bangBangYudoHono();)",
KnowledgeHelperFix... |
static Entry<ScramMechanism, String> parsePerMechanismArgument(String input) {
input = input.trim();
int equalsIndex = input.indexOf('=');
if (equalsIndex < 0) {
throw new FormatterException("Failed to find equals sign in SCRAM " +
"argument '" + input + "'");
... | @Test
public void testParsePerMechanismArgumentWithUnsupportedScramMethod() {
assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.",
assertThrows(FormatterException.class,
() -> ScramParser.parsePerMechanismArgument(
"SCRAM-SHA-UNSUPPO... |
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) {
AnalyzerContext context = new AnalyzerContext();
int treeSize = aggregatePredicateStatistics(predicate, false, context);
int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.h... | @Test
void require_that_minfeature_rounds_up() {
Predicate p =
or(
feature("foo").inSet("bar"),
feature("foo").inSet("bar"),
feature("foo").inSet("bar"));
PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.ana... |
static String generateJdbcPassword() {
int numLower = 2;
int numUpper = 2;
int numSpecial = 2;
return generatePassword(
MIN_PASSWORD_LENGTH,
MAX_PASSWORD_LENGTH,
numLower,
numUpper,
numSpecial,
ALLOWED_SPECIAL_CHARS);
} | @Test
public void testGeneratePasswordMeetsRequirements() {
for (int i = 0; i < 10000; i++) {
String password = generateJdbcPassword();
int lower = 0;
int upper = 0;
int special = 0;
for (int j = 0; j < password.length(); j++) {
char c = password.charAt(j);
String s ... |
@VisibleForTesting
public NotifyTemplateDO validateNotifyTemplate(String templateCode) {
// 获得站内信模板。考虑到效率,从缓存中获取
NotifyTemplateDO template = notifyTemplateService.getNotifyTemplateByCodeFromCache(templateCode);
// 站内信模板不存在
if (template == null) {
throw exception(NOTICE_NO... | @Test
public void testCheckMailTemplateValid_notExists() {
// 准备参数
String templateCode = randomString();
// mock 方法
// 调用,并断言异常
assertServiceException(() -> notifySendService.validateNotifyTemplate(templateCode),
NOTICE_NOT_FOUND);
} |
public boolean shouldRestartConnector(ConnectorStatus status) {
return !onlyFailed || status.state() == AbstractStatus.State.FAILED;
} | @Test
public void restartOnlyFailedConnector() {
RestartRequest restartRequest = new RestartRequest(CONNECTOR_NAME, true, false);
assertTrue(restartRequest.shouldRestartConnector(createConnectorStatus(AbstractStatus.State.FAILED)));
assertFalse(restartRequest.shouldRestartConnector(createCon... |
boolean isVisible(String key, Optional<EntityDto> component) {
if (isAdmin(component)) {
return true;
}
return hasPermission(GlobalPermission.SCAN, UserRole.SCAN, component) || !isProtected(key);
} | @Test
public void isVisible() {
openMocks(this);
when(userSession.isSystemAdministrator()).thenReturn(isAdmin);
when(userSession.hasPermission(GlobalPermission.SCAN)).thenReturn(hasGlobalPermission);
when(userSession.hasEntityPermission(UserRole.SCAN, componentDto)).thenReturn(hasComponentPermission);... |
public void removeExpiration(
long now, long timeout, Collection<PartitionRequestListener> timeoutListeners) {
Iterator<Map.Entry<InputChannelID, PartitionRequestListener>> iterator =
listeners.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<InputCha... | @Test
void testRemoveExpiration() {
PartitionRequestListenerManager partitionRequestListenerManager =
new PartitionRequestListenerManager();
assertThat(partitionRequestListenerManager.isEmpty()).isTrue();
List<PartitionRequestListener> listenerList = new ArrayList<>();
... |
@Override
public boolean contains(Object o) {
if (o instanceof Integer) {
int value = (Integer) o;
return value >= from && value < to;
}
return false;
} | @Test
void testContains() {
RangeSet rangeSet = new RangeSet(5, 10);
assertTrue(rangeSet.contains(5));
assertTrue(rangeSet.contains(9));
assertFalse(rangeSet.contains(10));
assertFalse(rangeSet.contains(4));
} |
@Udf
public <T> List<T> distinct(
@UdfParameter(description = "Array of values to distinct") final List<T> input) {
if (input == null) {
return null;
}
final Set<T> distinctVals = Sets.newLinkedHashSetWithExpectedSize(input.size());
distinctVals.addAll(input);
return new ArrayList<>(di... | @Test
public void shouldConsiderNullAsDistinctValue() {
final List<Object> result = udf.distinct(Arrays.asList(1, 2, 1, null, 2, null, 3, 1));
assertThat(result, contains(1, 2, null, 3));
} |
public boolean isDisabled() {
return _disabled;
} | @Test
public void withDisabledTrue()
throws JsonProcessingException {
String confStr = "{\"disabled\": true}";
IndexConfig config = JsonUtils.stringToObject(confStr, IndexConfig.class);
assertTrue(config.isDisabled(), "Unexpected disabled");
} |
void archive(ScanResults scanResults) throws InvalidProtocolBufferException {
if (!Strings.isNullOrEmpty(options.localOutputFilename)) {
archive(rawFileArchiver, options.localOutputFilename, options.localOutputFormat, scanResults);
}
if (!Strings.isNullOrEmpty(options.gcsOutputFileUrl)) {
Googl... | @Test
public void archive_withNoStorageEnabled_storesNothing() throws InvalidProtocolBufferException {
options.localOutputFilename = "";
options.gcsOutputFileUrl = "";
scanResultsArchiver.archive(SCAN_RESULTS);
fakeRawFileArchiver.assertNoDataStored();
fakeGoogleCloudStorageArchivers.assertNoDat... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatMaxDoubleLiteral() {
assertThat(ExpressionFormatter.formatExpression(
new DoubleLiteral(Double.MAX_VALUE)),
equalTo("1.7976931348623157E308"));
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamsCantBeCompared() {
FunctionTestUtil.assertResultError( startsFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, 1, 2, Range.RangeBoundary.CLOSED ) ), InvalidPar... |
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
String json = reader.readLine();
log.debug("Converting response from influxDb: {}", json);
Map result = getResultObject... | @Test
public void deserializeWrongValue() throws Exception {
TypedInput input = new TypedByteArray(MIME_TYPE, "{\"foo\":\"bar\"}".getBytes());
assertThrows(
ConversionException.class, () -> influxDbResponseConverter.fromBody(input, List.class));
} |
@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 processSendsMessageWithOverrideTopicHeaderAndEndPoint() throws Exception {
endpoint.getConfiguration().setTopic("sometopic");
Mockito.when(exchange.getIn()).thenReturn(in);
Mockito.when(exchange.getMessage()).thenReturn(in);
in.setHeader(KafkaConstants.PARTITION_KE... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test
public void testSubstVarsRecursive() {
context.putProperty("v1", "if");
context.putProperty("v2", "${v3}");
context.putProperty("v3", "works");
String result = OptionHelper.substVars(text, context);
assertEquals(expected, result);
} |
@Override
public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception {
final List<String> loggerNames = getLoggerNames(parameters);
final Level loggerLevel = getLoggerLevel(parameters);
final Duration duration = getDuration(parameters);
for (Strin... | @Test
void configuresDefaultLevelForALogger() throws Exception {
// given
Level oneEffectiveBefore = logger1.getEffectiveLevel();
Level twoEffectiveBefore = logger2.getEffectiveLevel();
Map<String, List<String>> parameters = Map.of("logger", List.of("logger.one"));
// when
... |
public long addPublication(final String channel, final int streamId)
{
final long correlationId = toDriverCommandBuffer.nextCorrelationId();
final int length = PublicationMessageFlyweight.computeLength(channel.length());
final int index = toDriverCommandBuffer.tryClaim(ADD_PUBLICATION, lengt... | @Test
void threadSendsAddChannelMessage()
{
threadSendsChannelMessage(() -> conductor.addPublication(CHANNEL, STREAM_ID), ADD_PUBLICATION);
} |
@Override
public final boolean offer(int ordinal, @Nonnull Object item) {
if (ordinal == -1) {
return offerInternal(allEdges, item);
} else {
if (ordinal == bucketCount()) {
// ordinal beyond bucketCount will add to snapshot queue, which we don't allow through... | @Test
public void when_offer1FailsAndDifferentItemOffered_then_fail() {
do_when_offerDifferent_then_fail(e -> outbox.offer(e));
} |
public URL getInterNodeListener(
final Function<URL, Integer> portResolver
) {
return getInterNodeListener(portResolver, LOGGER);
} | @Test
public void shouldResolveInterNodeListenerToInternalListenerSetToIpv4Loopback() {
// Given:
final URL expected = url("https://127.0.0.2:12345");
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:90... |
public static NodeRef nodeFromPod(Pod pod) {
return new NodeRef(
pod.getMetadata().getName(),
ReconcilerUtils.getPodIndexFromPodName(pod.getMetadata().getName()),
ReconcilerUtils.getPoolNameFromPodName(clusterNameFromLabel(pod), pod.getMetadata().getName()),
... | @Test
public void testNodeRefFromPod() {
NodeRef node = ReconcilerUtils.nodeFromPod(new PodBuilder()
.withNewMetadata()
.withName("my-cluster-new-brokers-1")
.withLabels(Map.of(Labels.STRIMZI_CLUSTER_LABEL, "my-cluster"))
.endMetadata()... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldApplyCreateConnectorStatement() throws Exception {
// Given:
command = PARSER.parse("-v", "3");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
createMigrationFile(3, NAME, migrationsDir,CREATE_CONNECTOR );
givenCurrentMigrationVersion("1");
givenAppliedMigration(... |
public ClusterStateBundle.FeedBlock inferContentClusterFeedBlockOrNull(ContentCluster cluster) {
if (!feedBlockEnabled) {
return null;
}
var nodeInfos = cluster.getNodeInfos();
var exhaustions = enumerateNodeResourceExhaustionsAcrossAllNodes(nodeInfos);
if (exhaustion... | @Test
void retained_node_feed_block_cleared_once_hysteresis_threshold_is_passed() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.48)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBloc... |
@VisibleForTesting
static Function<List<String>, ProcessBuilder> defaultProcessBuilderFactory(
String dockerExecutable, ImmutableMap<String, String> dockerEnvironment) {
return dockerSubCommand -> {
List<String> dockerCommand = new ArrayList<>(1 + dockerSubCommand.size());
dockerCommand.add(dock... | @Test
public void testDefaultProcessorBuilderFactory_customEnvironment() {
ImmutableMap<String, String> environment = ImmutableMap.of("Key1", "Value1");
Map<String, String> expectedEnvironment = new HashMap<>(System.getenv());
expectedEnvironment.putAll(environment);
ProcessBuilder processBuilder =
... |
public void checkOpen() {
if (!open.get()) {
throw new ClosedFileSystemException();
}
} | @Test
public void testCheckOpen() throws IOException {
state.checkOpen(); // does not throw
state.close();
try {
state.checkOpen();
fail();
} catch (ClosedFileSystemException expected) {
}
} |
@JsonProperty
@Override
public String getId()
{
return id;
} | @Test
public void testCompatibility()
{
String goldenValue = "{\n" +
" \"id\" : \"20160128_214710_00012_rk68b\",\n" +
" \"infoUri\" : \"http://localhost:54855/query.html?20160128_214710_00012_rk68b\",\n" +
" \"columns\" : [ {\n" +
" \... |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test
@SuppressWarnings("deprecation")
public void testResourceContextParameterType()
{
String testParamKey = "testParam";
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class);
List<Parameter<?>> parameters = new ArrayList<>();
Parameter<ResourceContext> p... |
public boolean setNewAuthor(DefaultIssue issue, @Nullable String newAuthorLogin, IssueChangeContext context) {
if (isNullOrEmpty(newAuthorLogin)) {
return false;
}
checkState(issue.authorLogin() == null, "It's not possible to update the author with this method, please use setAuthorLogin()");
issue... | @Test
void not_set_new_author_if_new_author_is_null() {
boolean updated = underTest.setNewAuthor(issue, null, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
} |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Processing Guarantees cannot be altered")
public void testMergeDifferentProcessingGuarantees() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunct... |
@Override
public URL use(ApplicationId applicationId, String resourceKey)
throws YarnException {
Path resourcePath = null;
UseSharedCacheResourceRequest request = Records.newRecord(
UseSharedCacheResourceRequest.class);
request.setAppId(applicationId);
request.setResourceKey(resourceKey)... | @Test
public void testUseCacheHit() throws Exception {
Path file = new Path("viewfs://test/path");
URL useUrl = URL.fromPath(new Path("viewfs://test/path"));
UseSharedCacheResourceResponse response =
new UseSharedCacheResourceResponsePBImpl();
response.setPath(file.toString());
when(cProto... |
static MetricRegistry getOrCreateMetricRegistry(Registry camelRegistry, String registryName) {
LOG.debug("Looking up MetricRegistry from Camel Registry for name \"{}\"", registryName);
MetricRegistry result = getMetricRegistryFromCamelRegistry(camelRegistry, registryName);
if (result == null) {
... | @Test
public void testGetOrCreateMetricRegistryNotFoundInCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(MetricRegistry.class)).thenReturn(Collections.<MetricRegistry> emptySet());
MetricRegistry result =... |
<K, V> List<ConsumerRecord<K, V>> fetchRecords(FetchConfig fetchConfig,
Deserializers<K, V> deserializers,
int maxRecords) {
// Error when fetching the next record before deserialization.
if (corruptLas... | @Test
public void testNegativeFetchCount() {
long fetchOffset = 0;
int startingOffset = 0;
int numRecords = 10;
FetchResponseData.PartitionData partitionData = new FetchResponseData.PartitionData()
.setRecords(newRecords(startingOffset, numRecords, fetchOffset));
... |
public static Pair<Optional<Method>, Optional<TypedExpression>> resolveMethodWithEmptyCollectionArguments(
final MethodCallExpr methodExpression,
final MvelCompilerContext mvelCompilerContext,
final Optional<TypedExpression> scope,
List<TypedExpression> arguments,
... | @Test
public void resolveMethodWithEmptyCollectionArguments() {
final MethodCallExpr methodExpression = new MethodCallExpr("setAddresses", new ListCreationLiteralExpression(null, NodeList.nodeList()));
final List<TypedExpression> arguments = List.of(new ListExprT(new ListCreationLiteralExpression(nu... |
public static Properties loadProps(String filename) throws IOException {
return loadProps(filename, null);
} | @Test
public void testLoadProps() throws IOException {
File tempFile = TestUtils.tempFile();
try {
String testContent = "a=1\nb=2\n#a comment\n\nc=3\nd=";
Files.write(tempFile.toPath(), testContent.getBytes());
Properties props = Utils.loadProps(tempFile.getPath()... |
public Optional<Measure> toMeasure(@Nullable LiveMeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getDataAsString();
switch (metric.getType().getValueType()) {... | @Test
public void toMeasure_returns_long_part_of_value_in_dto_for_Long_Metric() {
Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setValue(1.5d), SOME_LONG_METRIC);
assertThat(measure).isPresent();
assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LONG);
assert... |
public RewriteGroupedCode rewrite(String context) {
BlockStatementGrouperVisitor visitor =
new BlockStatementGrouperVisitor(maxMethodLength, parameters);
visitor.visitStatement(topStatement, context);
final Map<String, List<String>> groupStrings = visitor.rewrite(rewriter);
... | @Test
public void testExtractIfInWhileGroups() {
String parameters = "a, b";
String givenBlock = readResource("groups/code/IfInWhile.txt");
String expectedBlock = readResource("groups/expected/IfInWhile.txt");
BlockStatementGrouper grouper = new BlockStatementGrouper(givenBlock, 10,... |
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName,
@Nullable Integer pageNumber, @Nullable Integer pageSize) {
String url = format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s",
gitlabUrl,
proj... | @Test
public void should_throw_IllegalArgumentException_when_invalide_json_in_401_response() {
MockResponse response = new MockResponse()
.setResponseCode(401)
.setBody("error in pat");
server.enqueue(response);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1,... |
@Override
public void cancel(ExecutionAttemptID executionAttemptId) {
cancelLogicalSlotRequest(executionAttemptId.getExecutionVertexId(), null);
} | @Test
void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception {
// physical slot request is not completed and does not complete logical requests
testLogicalSlotRequestCancellationOrRelease(
true,
true,
(context, assignment... |
public static String encode(String plain) {
Preconditions.checkNotNull(plain, "Cannot encode null object");
String encoded;
try {
encoded = URLEncoder.encode(plain, CHARSET);
} catch (UnsupportedEncodingException uee) {
throw new OAuthException("Charset not found ... | @Test
public void shouldPercentEncodeString() {
final String plain = "this is a test &^";
final String encoded = "this%20is%20a%20test%20%26%5E";
assertEquals(encoded, OAuthEncoder.encode(plain));
} |
public RemotingChannel removeConsumerChannel(ProxyContext ctx, String group, Channel channel) {
return removeChannel(buildConsumerKey(group), channel);
} | @Test
public void testRemoveConsumerChannel() {
String group = "group";
String clientId = RandomStringUtils.randomAlphabetic(10);
{
Channel consumerChannel = createMockChannel();
RemotingChannel consumerRemotingChannel = this.remotingChannelManager.createConsumerChan... |
public void check(@NotNull Set<Long> partitionIds, long currentTimeMs)
throws CommitRateExceededException, CommitFailedException {
Preconditions.checkNotNull(partitionIds, "partitionIds is null");
// Does not limit the commit rate of compaction transactions
if (transactionState.getSo... | @Test
public void testCompactionTxn() throws CommitRateExceededException {
long partitionId = 54321;
long currentTimeMs = System.currentTimeMillis();
Set<Long> partitions = new HashSet<>(Collections.singletonList(partitionId));
transactionState = new TransactionState(dbId, Lists.new... |
@Override
public Expression resolveSelect(final int idx, final Expression expression) {
final Expression resolved = columnMappings.get(idx);
return resolved == null ? expression : resolved;
} | @Test
public void shouldResolveUdtfSelectExpressionToInternalName() {
// Given:
final Expression exp = mock(Expression.class);
// When:
final Expression result = flatMapNode.resolveSelect(2, exp);
// Then:
assertThat(result, is(new UnqualifiedColumnReferenceExp(ColumnName.of("KSQL_SYNTH_0"))... |
@Override
public void start() {
if (isDisabled()) {
LOG.debug(MESSAGE_SCM_STEP_IS_DISABLED_BY_CONFIGURATION);
return;
}
if (settings.hasKey(SCM_PROVIDER_KEY)) {
settings.get(SCM_PROVIDER_KEY).ifPresent(this::setProviderIfSupported);
} else {
autodetection();
if (this.prov... | @Test
void log_when_exclusion_is_disabled() {
when(settings.getBoolean(CoreProperties.SCM_EXCLUSIONS_DISABLED_KEY)).thenReturn(Optional.of(true));
underTest.start();
assertThat(logTester.logs()).contains(MESSAGE_SCM_EXCLUSIONS_IS_DISABLED_BY_CONFIGURATION);
} |
@Override
public void run() {
try {
final Set<String> distinctRecurringJobSignatures = getDistinctRecurringJobSignaturesThatDoNotExistAnymore();
final Set<String> distinctScheduledJobSignatures = getDistinctScheduledJobSignaturesThatDoNotExistAnymore();
Set<String> jobsT... | @Test
void onRunItLogsAllScheduledAndRecurringJobsThatDoNotExist() {
when(storageProvider.getRecurringJobs()).thenReturn(new RecurringJobsResult(asList(
aDefaultRecurringJob().build(),
aDefaultRecurringJob().withJobDetails(classThatDoesNotExistJobDetails()).build()
))... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractBaseReplicatedRecordStore that = (AbstractBaseReplicatedRecordStore) o;
if (!Objects.equals(name... | @Test
public void testEquals() {
assertEquals(recordStore, recordStore);
assertEquals(recordStoreSameAttributes, recordStore);
assertNotEquals(null, recordStore);
assertNotEquals(new Object(), recordStore);
assertNotEquals(recordStoreOtherStorage, recordStore);
asse... |
public static <C> AsyncBuilder<C> builder() {
return new AsyncBuilder<>();
} | @Test
void ensureRetryerClonesItself() throws Throwable {
server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
server.enqueue(new MockResponse().setResponseCode(200).setBody("foo 2"));
server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 3"));
server.enqueue(new Moc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.