focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <EventT> Write<EventT> write() {
return new AutoValue_JmsIO_Write.Builder<EventT>().build();
} | @Test
public void testWriteMessageWithCFProviderFn() throws Exception {
ArrayList<String> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
data.add("Message " + i);
}
pipeline
.apply(Create.of(data))
.apply(
JmsIO.<String>write()
.withConnect... |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetEnumeration2() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtils.get(asEnumeration(Collections.emptyIterator()), -1);
});
} |
public List<ContainerEndpoint> read(ApplicationId applicationId) {
var optionalData = curator.getData(containerEndpointsPath(applicationId));
return optionalData.map(SlimeUtils::jsonToSlime)
.map(ContainerEndpointSerializer::endpointListFromSlime)
.o... | @Test
public void readingNonExistingEntry() {
final var cache = new ContainerEndpointsCache(Path.createRoot(), new MockCurator());
final var endpoints = cache.read(ApplicationId.defaultId());
assertTrue(endpoints.isEmpty());
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(new DefaultPathContainerService().isContainer(file)) {
return PathAttributes.EMPTY;
}
... | @Test
public void testFindDirectory() throws Exception {
final Path file = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
new DriveDirectory... |
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
synchronized (redoService.getRegisteredInstances()) {
List<Instance> retainInstance = getRetainInstance(serviceName, groupName, instances);
... | @Test
void testBatchDeregisterService() throws NacosException {
try {
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
instanceList.add(new Instance());
client.batchRegisterService(SERVICE_NAME... |
@Override
public void abortTransaction() throws ProducerFencedException {
verifyNotClosed();
verifyNotFenced();
verifyTransactionsInitialized();
verifyTransactionInFlight();
if (this.abortTransactionException != null) {
throw this.abortTransactionException;
... | @Test
public void shouldThrowOnAbortIfTransactionsNotInitialized() {
buildMockProducer(true);
assertThrows(IllegalStateException.class, () -> producer.abortTransaction());
} |
<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 testSimple() {
long fetchOffset = 5;
int startingOffset = 10;
int numRecords = 11; // Records for 10-20
FetchResponseData.PartitionData partitionData = new FetchResponseData.PartitionData()
.setRecords(newRecords(startingOffset, numRecords, fe... |
public final void removeAllThreadLevelSensors(final String threadId) {
final String key = threadSensorPrefix(threadId);
synchronized (threadLevelSensors) {
final Deque<String> sensors = threadLevelSensors.remove(key);
while (sensors != null && !sensors.isEmpty()) {
... | @Test
public void shouldRemoveThreadLevelSensors() {
final Metrics metrics = mock(Metrics.class);
final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, VERSION, time);
addSensorsOnAllLevels(metrics, streamsMetrics);
setupRemoveSensorsTest(metrics, THREA... |
@Override public void callExtensionPoint( LogChannelInterface log, Object object ) throws KettleException {
AbstractMeta meta;
if ( object instanceof Trans ) {
meta = ( (Trans) object ).getTransMeta();
} else if ( object instanceof JobExecutionExtension ) {
meta = ( (JobExecutionExtension) objec... | @Test
public void testCallExtensionPointWithTransMeta() throws Exception {
MetastoreLocatorOsgi metastoreLocator = new MetastoreLocatorImpl();
LogChannelInterface logChannelInterface = mock( LogChannelInterface.class );
TransMeta mockTransMeta = mock( TransMeta.class );
Collection<MetastoreLocator> me... |
public static DataCacheInfo analyzeDataCacheInfo(Map<String, String> properties) throws AnalysisException {
boolean enableDataCache = analyzeBooleanProp(properties, PropertyAnalyzer.PROPERTIES_DATACACHE_ENABLE, true);
boolean enableAsyncWriteBack =
analyzeBooleanProp(properties, Propert... | @Test
public void testAnalyzeDataCacheInfo() {
Map<String, String> properties = new HashMap<>();
properties.put(PropertyAnalyzer.PROPERTIES_DATACACHE_ENABLE, "true");
properties.put(PropertyAnalyzer.PROPERTIES_ENABLE_ASYNC_WRITE_BACK, "true");
try {
PropertyAnalyzer.anal... |
@Override
public Optional<String> getContentHash() {
return Optional.ofNullable(mContentHash);
} | @Test
public void close() throws Exception {
mStream.close();
Mockito.verify(mMockS3Client, never())
.initiateMultipartUpload(any(InitiateMultipartUploadRequest.class));
Mockito.verify(mMockS3Client, never())
.completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
assertTr... |
@Override
public int getColumnLength(final Object value) {
throw new UnsupportedSQLOperationException("PostgreSQLStringArrayBinaryProtocolValue.getColumnLength()");
} | @Test
void assertGetColumnLength() {
assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().getColumnLength("val"));
} |
static void checkNearCacheNativeMemoryConfig(InMemoryFormat inMemoryFormat, NativeMemoryConfig nativeMemoryConfig,
boolean isEnterprise) {
if (!isEnterprise) {
return;
}
if (inMemoryFormat != NATIVE) {
return;
}
... | @Test(expected = InvalidConfigurationException.class)
public void checkNearCacheNativeMemoryConfig_shouldThrowExceptionWithoutNativeMemoryConfig_NATIVE_onEE() {
checkNearCacheNativeMemoryConfig(NATIVE, null, true);
} |
@Override
public SendResult send(
Message msg) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
if (this.getAutoBatch() && !(msg instanceof MessageBatch)) {
return sendByAccumulator(msg, null, null... | @Test
public void testSendMessage_NoRoute() throws RemotingException, InterruptedException, MQBrokerException {
when(mQClientAPIImpl.getNameServerAddressList()).thenReturn(Collections.singletonList("127.0.0.1:9876"));
try {
producer.send(message);
failBecauseExceptionWasNotTh... |
@Override
protected void doExecute() {
if (vpls == null) {
vpls = get(Vpls.class);
}
if (interfaceService == null) {
interfaceService = get(InterfaceService.class);
}
VplsCommandEnum enumCommand = VplsCommandEnum.enumFromString(command);
if (e... | @Test
public void testClean() {
((TestVpls) vplsCommand.vpls).initSampleData();
vplsCommand.command = VplsCommandEnum.CLEAN.toString();
vplsCommand.doExecute();
Collection<VplsData> vplss = vplsCommand.vpls.getAllVpls();
assertEquals(0, vplss.size());
} |
@NonNull
public String keyFor(@NonNull String id) {
return id;
} | @Test
public void testKeyForCaseSensitiveEmailAddress() {
IdStrategy idStrategy = new IdStrategy.CaseSensitiveEmailAddress();
assertThat(idStrategy.keyFor("john.smith@acme.org"), is("john.smith@acme.org"));
assertThat(idStrategy.keyFor("John.Smith@acme.org"), is("John.Smith@acme.org"));
... |
public String message() {
return message;
} | @Test
public void shouldNotFailWhenNoMessageSet() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
assertThat(result.message(), is(nullValue()));
} |
public static boolean isNegative(Slice decimal)
{
return (getRawInt(decimal, SIGN_INT_INDEX) & SIGN_INT_MASK) != 0;
} | @Test
public void testIsNegative()
{
assertEquals(isNegative(MIN_DECIMAL), true);
assertEquals(isNegative(MAX_DECIMAL), false);
assertEquals(isNegative(unscaledDecimal(0)), false);
} |
@Override
public boolean test(Pair<Point, Point> pair) {
return testVertical(pair) && testHorizontal(pair);
} | @Test
public void testVertSeparation() {
Point p1 = (new PointBuilder()).time(EPOCH).latLong(0.0, 0.0).altitude(Distance.ofFeet(1000.0)).build();
Point p2 = (new PointBuilder()).time(EPOCH).latLong(0.0, 0.0).altitude(Distance.ofFeet(1000.0)).build();
Point p3 = (new PointBuilder()).time(EPO... |
public static void toJson(Metadata metadata, Writer writer) throws IOException {
if (metadata == null) {
writer.write("null");
return;
}
long max = TikaConfig.getMaxJsonStringFieldLength();
try (JsonGenerator jsonGenerator = new JsonFactory()
.setS... | @Test
public void testNull() {
StringWriter writer = new StringWriter();
boolean ex = false;
try {
JsonMetadata.toJson(null, writer);
} catch (IOException e) {
ex = true;
}
assertFalse(ex);
assertEquals("null", writer.toString());
} |
@Override
public int hashCode() {
return operands.hashCode();
} | @Test
void requireThatHashCodeIsImplemented() {
assertEquals(new Disjunction().hashCode(), new Disjunction().hashCode());
} |
public JobStatsExtended enrich(JobStats jobStats) {
JobStats latestJobStats = getLatestJobStats(jobStats, previousJobStats);
if (lock.tryLock()) {
setFirstRelevantJobStats(latestJobStats);
setJobStatsExtended(latestJobStats);
setPreviousJobStats(latestJobStats);
... | @Test
void estimatedTimeProcessingIsCalculated5() {
JobStats firstJobStats = getJobStats(now().minusSeconds(3610), 10L, 0L, 0L, 100L);
JobStats secondJobStats = getJobStats(now().minusSeconds(3600), 5L, 4L, 0L, 101L);
JobStats thirdJobStats = getJobStats(now(), 4L, 4L, 0L, 102L);
Jo... |
public void moveAllChildrenTo(final FilePath target) throws IOException, InterruptedException {
if (this.channel != target.channel) {
throw new IOException("pullUpTo target must be on the same host");
}
act(new MoveAllChildrenTo(target));
} | @Issue("JENKINS-16846")
@Test public void moveAllChildrenTo() throws IOException, InterruptedException {
File tmp = temp.getRoot();
final String dirname = "sub";
final File top = new File(tmp, "test");
final File sub = new File(top, dirname);
final File subsub... |
public String toMysqlDataTypeString() {
return "unknown";
} | @Test
public void testMysqlDataType() {
Object[][] testCases = new Object[][] {
{ScalarType.createType(PrimitiveType.BOOLEAN), "tinyint"},
{ScalarType.createType(PrimitiveType.LARGEINT), "bigint unsigned"},
{ScalarType.createDecimalV3NarrowestType(18, 4), "dec... |
public static Sessions withGapDuration(Duration gapDuration) {
return new Sessions(gapDuration);
} | @Test
public void testInvalidOutputAtEarliest() throws Exception {
try {
WindowFnTestUtils.validateGetOutputTimestamps(
Sessions.withGapDuration(Duration.millis(10)),
TimestampCombiner.EARLIEST,
ImmutableList.of(
(List<Long>) ImmutableList.of(1L, 3L),
... |
private long advisoryPartitionSize(long defaultValue) {
return confParser
.longConf()
.option(SparkWriteOptions.ADVISORY_PARTITION_SIZE)
.sessionConf(SparkSQLProperties.ADVISORY_PARTITION_SIZE)
.tableProperty(TableProperties.SPARK_WRITE_ADVISORY_PARTITION_SIZE_BYTES)
.default... | @TestTemplate
public void testAdvisoryPartitionSize() {
Table table = validationCatalog.loadTable(tableIdent);
SparkWriteConf writeConf = new SparkWriteConf(spark, table, ImmutableMap.of());
long value1 = writeConf.writeRequirements().advisoryPartitionSize();
assertThat(value1).isGreaterThan(64L * 1... |
public static boolean checkLiteralOverflowInDecimalStyle(BigDecimal value, ScalarType scalarType) {
int realPrecision = getRealPrecision(value);
int realScale = getRealScale(value);
BigInteger underlyingInt = value.setScale(scalarType.getScalarScale(), RoundingMode.HALF_UP).unscaledValue();
... | @Test
public void testCheckLiteralOverflowInDecimalStyleFail() throws AnalysisException {
BigDecimal decimal32Values[] = {
new BigDecimal("100000.0000"),
new BigDecimal("99999.99995"),
new BigDecimal("-100000.0000"),
new BigDecimal("-99999.9999... |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetStreamsConfigTopicUnprefixedProperties() {
final KsqlConfig ksqlConfig = new KsqlConfig(
Collections.singletonMap(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, 2));
final Object result = ksqlConfig.getKsqlStreamConfigProps().get(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG);
asser... |
@Override
public Cursor<Tuple> zScan(byte[] key, ScanOptions options) {
return new KeyBoundCursor<Tuple>(key, 0, options) {
private RedisClient client;
@Override
protected ScanIteration<Tuple> doScan(byte[] key, long cursorId, ScanOptions options) {
if (... | @Test
public void testZScan() {
connection.zAdd("key".getBytes(), 1, "value1".getBytes());
connection.zAdd("key".getBytes(), 2, "value2".getBytes());
Cursor<RedisZSetCommands.Tuple> t = connection.zScan("key".getBytes(), ScanOptions.scanOptions().build());
assertThat(t.hasNext()).is... |
public void execute(int[] bytecode) {
for (var i = 0; i < bytecode.length; i++) {
Instruction instruction = Instruction.getInstruction(bytecode[i]);
switch (instruction) {
case LITERAL:
// Read the next byte from the bytecode.
int value = bytecode[++i];
// Push the ... | @Test
void testInvalidInstruction() {
var bytecode = new int[1];
bytecode[0] = 999;
var vm = new VirtualMachine();
assertThrows(IllegalArgumentException.class, () -> vm.execute(bytecode));
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatArray() {
final SqlArray array = SqlTypes.array(SqlTypes.BOOLEAN);
assertThat(ExpressionFormatter.formatExpression(new Type(array)), equalTo("ARRAY<BOOLEAN>"));
} |
@Override
public Collection<String> getJdbcUrlPrefixes() {
return Collections.singletonList(String.format("jdbc:%s:", getType().toLowerCase()));
} | @Test
void assertGetJdbcUrlPrefixes() {
assertThat(TypedSPILoader.getService(DatabaseType.class, "MariaDB").getJdbcUrlPrefixes(), is(Collections.singletonList("jdbc:mariadb:")));
} |
@Override
public Optional<ShardingConditionValue> generate(final BinaryOperationExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) {
String operator = predicate.getOperator().toUpperCase();
if (!isSupportedOperator(operator)) {
... | @SuppressWarnings("unchecked")
@Test
void assertGenerateConditionValueWithGreaterThanOperator() {
BinaryOperationExpression rightValue = new BinaryOperationExpression(0, 0, mock(ColumnSegment.class), new LiteralExpressionSegment(0, 0, 1), ">", null);
Optional<ShardingConditionValue> shardingCond... |
@Override
public boolean start() throws IOException {
LOG.info("Starting reader using {}", initCheckpoint);
try {
shardReadersPool = createShardReadersPool();
shardReadersPool.start();
} catch (TransientKinesisException e) {
throw new IOException(e);
}
return advance();
} | @Test
public void startReturnsTrueIfSomeDataAvailable() throws IOException {
when(shardReadersPool.nextRecord())
.thenReturn(CustomOptional.of(a))
.thenReturn(CustomOptional.absent());
assertThat(reader.start()).isTrue();
} |
public float[][] getValues()
{
float[][] retval = new float[3][3];
retval[0][0] = single[0];
retval[0][1] = single[1];
retval[0][2] = single[2];
retval[1][0] = single[3];
retval[1][1] = single[4];
retval[1][2] = single[5];
retval[2][0] = single[6];
... | @Test
void testGetValues()
{
Matrix m = new Matrix(2, 4, 4, 2, 15, 30);
float[][] values = m.getValues();
assertEquals(2, values[0][0], 0);
assertEquals(4, values[0][1], 0);
assertEquals(0, values[0][2], 0);
assertEquals(4, values[1][0], 0);
assertEquals(2... |
public static <X> TypeInformation<X> getForObject(X value) {
return new TypeExtractor().privateGetForObject(value);
} | @Test
void testRow() {
Row row = new Row(2);
row.setField(0, "string");
row.setField(1, 15);
TypeInformation<Row> rowInfo = TypeExtractor.getForObject(row);
assertThat(rowInfo.getClass()).isEqualTo(RowTypeInfo.class);
assertThat(rowInfo.getArity()).isEqualTo(2);
... |
@Nullable
public String ensureBuiltinRole(String roleName, String description, Set<String> expectedPermissions) {
Role previousRole = null;
try {
previousRole = roleService.load(roleName);
if (!previousRole.isReadOnly() || !expectedPermissions.equals(previousRole.getPermissio... | @Test
public void ensureBuiltinRoleWithoutReadOnly() throws Exception {
final Role existingRole = mock(Role.class);
when(existingRole.getId()).thenReturn("new-id");
when(existingRole.isReadOnly()).thenReturn(false); // The existing role needs to be read-only
when(roleService.load("... |
public static List<String> getTokens() {
final List<String> tokens = new ArrayList<>(Arrays.asList(SqlBaseLexer.ruleNames));
return tokens.stream().filter(pattern.asPredicate().negate()).collect(Collectors.toList());
} | @Test
public void shouldNeedBackQuotes() {
List<String> tokens = GrammarTokenExporter.getTokens();
assertEquals(expectedTokens, tokens);
} |
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) {
if (LOG.isTraceEnabled()) {
LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}"
+ " Used Normalized Resources: {} Total Normalized Resources:... | @Test
public void testCalculateMinWithOnlyCpu() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 2)));
NormalizedResources usedResources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_R... |
public String getPlugin() {
return plugin;
} | @Test
public void thePluginCanBeChanged() {
doReturn(pluginManager).when(xmppServer).getPluginManager();
final SystemProperty<Long> longProperty = SystemProperty.Builder.ofType(Long.class)
.setKey("a-plugin-property")
.setDefaultValue(42L)
.setPlugin("TestPlugin... |
public void asyncDestroy() {
if (!(dataSource instanceof AutoCloseable)) {
return;
}
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(this::graceDestroy);
executor.shutdown();
} | @Test
void assertAsyncDestroyWithAutoCloseableDataSource() throws SQLException {
MockedDataSource dataSource = new MockedDataSource();
try (Connection ignored = dataSource.getConnection()) {
new DataSourcePoolDestroyer(dataSource).asyncDestroy();
}
Awaitility.await().atMo... |
public void executeTask(final Runnable r) {
if (!isStopped()) {
this.scheduledExecutorService.execute(r);
} else {
logger.warn("PullMessageServiceScheduledThread has shutdown");
}
} | @Test
public void testExecuteTask() {
Runnable runnable = mock(Runnable.class);
pullMessageService.executeTask(runnable);
pullMessageService.makeStop();
pullMessageService.executeTask(runnable);
verify(executorService, times(1)).execute(any(Runnable.class));
} |
@Override
public void deleteFileConfig(Long id) {
// 校验存在
FileConfigDO config = validateFileConfigExists(id);
if (Boolean.TRUE.equals(config.getMaster())) {
throw exception(FILE_CONFIG_DELETE_FAIL_MASTER);
}
// 删除
fileConfigMapper.deleteById(id);
... | @Test
public void testDeleteFileConfig_success() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbFileConfig.getId();
// 调用
fileConfigService.deleteF... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
callback.delete(file);
try {
if(file.isFile() || file.isSymbolicLink()) {
... | @Test
public void testDeleteNotFound() throws Exception {
final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
try {
new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), ... |
public static Counter getOpenConnectionsCounter() {
return getOrCreateCounter(MetricsConstants.OPEN_CONNECTIONS);
} | @Test
public void testJsonStructure() throws Exception {
File jsonReportFile = File.createTempFile("TestMetrics", ".json");
String jsonFile = jsonReportFile.getAbsolutePath();
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setVar(conf, MetastoreConf.ConfVars.METRICS_REPORTERS, "... |
@Override
public boolean eval(Object arg) {
QueryableEntry entry = (QueryableEntry) arg;
Data keyData = entry.getKeyData();
return (key == null || key.equals(keyData)) && predicate.apply((Map.Entry) arg);
} | @Test
public void testEval_givenFilterDoesNotContainKey_whenPredicateIsMatching_thenReturnTrue() {
//given
Predicate<Object, Object> predicate = Predicates.alwaysTrue();
QueryEventFilter filter = new QueryEventFilter(null, predicate, true);
//when
Data key2 = serializationSe... |
static String createJobIdPrefix(
String jobName, String stepUuid, JobType type, @Nullable String random) {
jobName = jobName.replaceAll("-", "");
String result =
BIGQUERY_JOB_TEMPLATE
.replaceFirst("\\{TYPE}", type.toString())
.replaceFirst("\\{JOB_ID}", jobName)
... | @Test
public void testMatchesBigQueryJobTemplate() {
assertThat(
BigQueryResourceNaming.createJobIdPrefix(
"beamapp-job-test", "abcd", JobType.EXPORT, "RANDOME"),
matchesPattern(BQ_JOB_PATTERN_REGEXP));
assertThat(
BigQueryResourceNaming.createJobIdPrefix("beamapp-job-test... |
@Override
public void showPreviewForKey(Keyboard.Key key, CharSequence label, Point previewPosition) {
mPreviewIcon.setVisibility(View.GONE);
mPreviewText.setVisibility(View.VISIBLE);
mPreviewIcon.setImageDrawable(null);
mPreviewText.setTextColor(mPreviewPopupTheme.getPreviewKeyTextColor());
mPre... | @Test
public void testPreviewLayoutCorrectlyForNoneLabel() {
PreviewPopupTheme theme = new PreviewPopupTheme();
theme.setPreviewKeyBackground(
ContextCompat.getDrawable(getApplicationContext(), blacktheme_preview_background));
theme.setPreviewKeyTextSize(1);
final KeyPreviewPopupWindow underTe... |
public Set<String> assembleAllWatchKeys(String appId, String clusterName, String namespace,
String dataCenter) {
Multimap<String, String> watchedKeysMap =
assembleAllWatchKeys(appId, clusterName, Sets.newHashSet(namespace), dataCenter);
return Sets.newHashSet(wa... | @Test
public void testAssembleAllWatchKeysWithOneNamespaceAndDefaultCluster() throws Exception {
Set<String> watchKeys =
watchKeysUtil.assembleAllWatchKeys(someAppId, defaultCluster, someNamespace, null);
Set<String> clusters = Sets.newHashSet(defaultCluster);
assertEquals(clusters.size(), watch... |
@Override
public void run() {
try {
backgroundJobServer.getJobSteward().notifyThreadOccupied();
MDCMapper.loadMDCContextFromJob(job);
performJob();
} catch (Exception e) {
if (isJobDeletedWhileProcessing(e)) {
// nothing to do anymore a... | @Test
@DisplayName("InvocationTargetException is unwrapped and the actual error is stored instead")
void invocationTargetExceptionUnwrapped() throws Exception {
var job = anEnqueuedJob().build();
var runner = mock(BackgroundJobRunner.class);
doThrow(new InvocationTargetException(new Runt... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateSpu(ProductSpuSaveReqVO updateReqVO) {
// 校验 SPU 是否存在
validateSpuExists(updateReqVO.getId());
// 校验分类、品牌
validateCategory(updateReqVO.getCategoryId());
brandService.validateProductBrand(updateReqVO.... | @Test
public void testUpdateSpu_success() {
// 准备参数
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); ... |
@Override
public HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) {
return super.restore(versionDesired, blobRetriever);
} | @Test
public void testRestoreToNonExact() {
HollowProducer producer = createProducer(tmpFolder, schema);
long version = testPublishV1(producer, 2, 7);
producer = createProducer(tmpFolder, schema);
producer.restore(version + 1, blobRetriever);
Assert.assertNotNull(lastRestore... |
@Override
@NotNull
public List<PartitionStatistics> select(@NotNull Collection<PartitionStatistics> statistics,
@NotNull Set<Long> excludeTables) {
double minScore = Config.lake_compaction_score_selector_min_score;
long now = System.currentTimeMillis();
return statistics.stre... | @Test
public void test() {
List<PartitionStatistics> statisticsList = new ArrayList<>();
PartitionStatistics statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 3));
statistics.setCompactionScore(Quantiles.compute(Collections.singleton(0.0)));
statisticsList.add(statis... |
@Override
public HttpResponse get() throws InterruptedException, ExecutionException {
try {
final Object result = process(0, null);
if (result instanceof Throwable) {
throw new ExecutionException((Throwable) result);
}
return (HttpResponse) res... | @Test(expected = InterruptedException.class)
public void errGet() throws ExecutionException, InterruptedException, TimeoutException {
get(new InterruptedException(), false);
} |
public static RunResponse from(WorkflowInstance instance, int state) {
return RunResponse.builder()
.workflowId(instance.getWorkflowId())
.workflowVersionId(instance.getWorkflowVersionId())
.workflowInstanceId(instance.getWorkflowInstanceId())
.workflowRunId(instance.getWorkflowRunId... | @Test
public void testBuildFromEvent() {
RunResponse res = RunResponse.from(stepInstance, TimelineLogEvent.info("bar"));
Assert.assertEquals(RunResponse.Status.STEP_ATTEMPT_CREATED, res.getStatus());
} |
@Override
public ExportResult<VideosContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation)
throws CopyExceptionWithFailureReason {
Preconditions.checkNotNull(authData);
KoofrClient koofrClient = koofrClientFactory.create(authData);
... | @Test
public void testExport() throws Exception {
when(client.getRootPath()).thenReturn("/Data transfer");
when(client.listRecursive("/Data transfer")).thenReturn(Fixtures.listRecursiveItems);
when(client.fileLink("/Data transfer/Album 2 :heart:/Video 1.mp4"))
.thenReturn("https://app-1.koofr.net/... |
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("Xoo Measure Sensor")
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY);
} | @Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
} |
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
if ( super.init( smi, sdi ) ) {
logError( BaseMessages.getString( PKG, "MissingTransStep.Log.CannotRunTrans" ) );
}
return false;
} | @Test
public void testInit() {
StepMetaInterface stepMetaInterface = new AbstractStepMeta() {
@Override
public void setDefault() { }
@Override
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
TransMeta t... |
public boolean isTimedOut() {
return timedOut.get();
} | @Test
public void testShellCommandTimeout() throws Throwable {
Assume.assumeFalse(WINDOWS);
String rootDir = rootTestDir.getAbsolutePath();
File shellFile = new File(rootDir, "timeout.sh");
String timeoutCommand = "sleep 4; echo \"hello\"";
Shell.ShellCommandExecutor shexc;
try (PrintWriter wr... |
public T getRecordingProxy()
{
return _templateProxy;
} | @Test(expectedExceptions = NullPointerException.class)
public void testSimpleSetDisallowNullDefault()
{
makeOne().getRecordingProxy().setFooRequired(null);
} |
public boolean isAfterFlink114() {
return flinkInterpreter.getFlinkVersion().isAfterFlink114();
} | @Test
void testStreamIPyFlink() throws InterpreterException, IOException {
if (!flinkInnerInterpreter.getFlinkVersion().isAfterFlink114()) {
IPyFlinkInterpreterTest.testStreamPyFlink(interpreter, flinkScalaInterpreter);
}
} |
public String views(Namespace ns) {
return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns), "views");
} | @Test
public void viewsWithSlash() {
Namespace ns = Namespace.of("n/s");
assertThat(withPrefix.views(ns)).isEqualTo("v1/ws/catalog/namespaces/n%2Fs/views");
assertThat(withoutPrefix.views(ns)).isEqualTo("v1/namespaces/n%2Fs/views");
} |
public boolean setRuleDescriptionContextKey(DefaultIssue issue, @Nullable String previousContextKey) {
String currentContextKey = issue.getRuleDescriptionContextKey().orElse(null);
issue.setRuleDescriptionContextKey(previousContextKey);
if (!Objects.equals(currentContextKey, previousContextKey)) {
iss... | @Test
void setRuleDescriptionContextKey_setContextKeyIfValuesAreDifferent() {
issue.setRuleDescriptionContextKey(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
boolean updated = underTest.setRuleDescriptionContextKey(issue, "hibernate");
assertThat(updated).isTrue();
assertThat(issue.getRuleDescriptionContex... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
return new DescriptiveUrlBag(Collections.singletonList(
new DescriptiveUrl(URI.create(String.format("https://webmail.freenet.de/web/?goTo=share&path=/%s#cloud",
URIEncoder.encode(PathRelativizer.relativize(PathNormalizer... | @Test
public void testToUrlFile() {
final FreenetUrlProvider provider = new FreenetUrlProvider(new Host(new FreenetProtocol(), "dav.freenet.de", 443, "/webdav"));
final DescriptiveUrlBag urls = provider.toUrl(new Path("/webdav/d/f", EnumSet.of(Path.Type.file)));
assertEquals(1, urls.size());... |
public static <T, ComparatorT extends Comparator<T> & Serializable>
Combine.Globally<T, List<T>> of(int count, ComparatorT compareFn) {
return Combine.globally(new TopCombineFn<>(count, compareFn));
} | @Test
public void testCountConstraint() {
p.enableAbandonedNodeEnforcement(false);
PCollection<String> input =
p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder(StringUtf8Coder.of()));
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(Matchers.containsString(">... |
public static Method getMethodByName(Class<?> clazz, String methodName) {
if (Objects.nonNull(clazz) && Objects.nonNull(methodName)) {
Method method = Arrays.stream(clazz.getMethods())
.filter(m -> Objects.equals(m.getName(), methodName))
.findFirst().orElse(n... | @Test
public void getMethodByNameTest() {
// private method
Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan");
Assert.assertNotNull(runStateLessThan);
// public method
Method field = ReflectUtil.getMethodByName(TestClass.class... |
static void extractSchemaWithComplexTypeHandling(
Descriptors.FieldDescriptor fieldSchema,
List<String> fieldsToUnnest,
String delimiter,
String path,
Schema pinotSchema,
@Nullable Map<String, FieldSpec.FieldType> fieldTypeMap,
@Nullable TimeUnit timeUnit) {
Descriptors.Fie... | @Test(dataProvider = "scalarCases")
public void testExtractSchemaWithComplexTypeHandling(
String fieldName, FieldSpec.DataType type, boolean isSingleValue) {
Descriptors.FieldDescriptor desc = ComplexTypes.TestMessage.getDescriptor().findFieldByName(fieldName);
Schema schema = new Schema();
ProtoBuf... |
@SuppressWarnings("unchecked")
public Mono<RateLimiterResponse> isAllowed(final String id, final RateLimiterHandle limiterHandle) {
double replenishRate = limiterHandle.getReplenishRate();
double burstCapacity = limiterHandle.getBurstCapacity();
double requestCount = limiterHandle.getRequest... | @Test
public void notAllowedTest() {
isAllowedPreInit(0L, 0L, false);
rateLimiterHandle.setAlgorithmName("tokenBucket");
Mono<RateLimiterResponse> responseMono = redisRateLimiter.isAllowed(DEFAULT_TEST_ID, rateLimiterHandle);
StepVerifier.create(responseMono).assertNext(r -> {
... |
static List<Integer> getTargetTpcPorts(List<Integer> tpcPorts, ClientTpcConfig tpcConfig) {
List<Integer> targetTpcPorts;
int tpcConnectionCount = tpcConfig.getConnectionCount();
if (tpcConnectionCount == 0 || tpcConnectionCount >= tpcPorts.size()) {
// zero means connect to all.
... | @Test
public void testGetTargetTpcPorts_whenConnectToAll() {
ClientTpcConfig config = new ClientTpcConfig();
List<Integer> tpcPorts = asList(1, 2, 3);
// when larger than the number of tpc ports, return the full set.
config.setConnectionCount(tpcPorts.size() + 1);
assertEqua... |
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
getExecuteClientProxy(instance).deregisterService(serviceName, groupName, instance);
} | @Test
void testDeregisterPersistentServiceHttp() throws NacosException, NoSuchFieldException, IllegalAccessException {
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
... |
public boolean statsHaveChanged() {
if (!aggregatedStats.hasUpdatesFromAllDistributors()) {
return false;
}
for (ContentNodeStats contentNodeStats : aggregatedStats.getStats()) {
int nodeIndex = contentNodeStats.getNodeIndex();
boolean currValue = mayHaveMerge... | @Test
void stats_have_not_changed_if_not_all_distributors_are_updated() {
Fixture f = Fixture.empty();
assertFalse(f.statsHaveChanged());
} |
static Optional<ExecutorService> lookupExecutorServiceRef(
CamelContext camelContext, String name, Object source, String executorServiceRef) {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ObjectHelper.notNull(manager, ESM_NAME);
ObjectHelper.notNull(exec... | @Test
void testLookupExecutorServiceRefWithNullRef() {
String name = "ThreadPool";
Object source = new Object();
when(camelContext.getExecutorServiceManager()).thenReturn(manager);
Exception ex = assertThrows(IllegalArgumentException.class,
() -> DynamicRouterRecipien... |
public void setBaseResource(Resource baseResource) {
handler.setBaseResource(baseResource);
} | @Test
void setsBaseResourceStringList(@TempDir Path tempDir) throws Exception {
String wooResource = Files.createDirectory(tempDir.resolve("dir-1")).toString();
String fooResource = Files.createDirectory(tempDir.resolve("dir-2")).toString();
final String[] testResources = new String[]{wooRe... |
@Override
public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager)
{
ImmutableList.Builder<ScalarFunctionImplementationChoice> implementationChoices = ImmutableList.builder();
for (PolymorphicScalarFunctionCho... | @Test
public void testTypeParameters()
throws Throwable
{
Signature signature = SignatureBuilder.builder()
.name("foo")
.kind(SCALAR)
.typeVariableConstraints(comparableWithVariadicBound("V", VARCHAR))
.returnType(parseTypeSigna... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void add1() {
String inputExpression = "y + 5 * 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix).isInstanceOf(InfixOpNode.class);
assertThat( infix.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertThat( infix... |
@Override
protected Set<StepField> getUsedFields( ExcelInputMeta meta ) {
Set<StepField> usedFields = new HashSet<>();
if ( meta.isAcceptingFilenames() && StringUtils.isNotEmpty( meta.getAcceptingStepName() ) ) {
StepField stepField = new StepField( meta.getAcceptingStepName(), meta.getAcceptingField() ... | @Test
public void testGetUsedFields_isNotAcceptingFilenames() throws Exception {
lenient().when( meta.isAcceptingFilenames() ).thenReturn( false );
lenient().when( meta.getAcceptingField() ).thenReturn( "filename" );
lenient().when( meta.getAcceptingStepName() ).thenReturn( "previousStep" );
Set<StepF... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldHandleNestedUdfs() {
// Given:
givenSourceStreamWithSchema(SINGLE_VALUE_COLUMN_SCHEMA, SerdeFeatures.of(), SerdeFeatures.of());
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(COL0),
ImmutableList.of(
new Function... |
public double currentProductionRate() {
return aggregateStat(ProducerCollector.PRODUCER_MESSAGES_PER_SEC, false);
} | @Test
public void shouldAggregateStatsAcrossAllProducers() {
final MetricCollectors metricCollectors = new MetricCollectors();
final ProducerCollector collector1 = new ProducerCollector();
collector1.configure(
ImmutableMap.of(
ProducerConfig.CLIENT_ID_CONFIG, "client1",
K... |
@Override
@CacheEvict(cacheNames = "ai:video:config", key = "#updateReqVO.type")
public void updateAiVideoConfig(AiVideoConfigUpdateReqVO updateReqVO) {
// 校验存在
validateAiVideoConfigExists(updateReqVO.getId());
// 更新
AiVideoConfigDO updateObj = AiVideoConfigConvert.INSTANCE.conve... | @Test
public void testUpdateAiVideoConfig_notExists() {
// 准备参数
AiVideoConfigUpdateReqVO reqVO = randomPojo(AiVideoConfigUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> aiVideoConfigService.updateAiVideoConfig(reqVO), AI_VIDEO_CONFIG_NOT_EXISTS);
} |
public void computeCpd(Component component, Collection<Block> originBlocks, Collection<Block> duplicationBlocks) {
CloneIndex duplicationIndex = new PackedMemoryCloneIndex();
populateIndex(duplicationIndex, originBlocks);
populateIndex(duplicationIndex, duplicationBlocks);
List<CloneGroup> duplications... | @Test
public void add_no_duplication_when_not_enough_tokens() {
settings.setProperty("sonar.cpd.xoo.minimumTokens", 10);
Collection<Block> originBlocks = singletonList(
// This block contains 5 tokens -> not enough to consider it as a duplication
new Block.Builder()
.setResourceId(ORIGIN_... |
public Matrix submatrix(int i, int j, int k, int l) {
if (i < 0 || i >= m || k < i || k >= m || j < 0 || j >= n || l < j || l >= n) {
throw new IllegalArgumentException(String.format("Invalid submatrix range (%d:%d, %d:%d) of %d x %d", i, k, j, l, m, n));
}
Matrix sub = new Matrix(k... | @Test
public void testSubmatrix() {
Matrix sub = matrix.submatrix(0, 1, 2, 2);
assertEquals(3, sub.nrow());
assertEquals(2, sub.ncol());
assertEquals(0.4f, sub.get(0,0), 1E-6f);
assertEquals(0.8f, sub.get(2,1), 1E-6f);
Matrix sub2 = sub.submatrix(0, 0, 1, 1);
... |
public static boolean isValid(String param) {
if (param == null) {
return false;
}
int length = param.length();
for (int i = 0; i < length; i++) {
char ch = param.charAt(i);
if (!Character.isLetterOrDigit(ch) && !isValidChar(ch)) {
retu... | @Test
void testIsValid() {
assertTrue(ParamUtils.isValid("test"));
assertTrue(ParamUtils.isValid("test1234"));
assertTrue(ParamUtils.isValid("test_-.:"));
assertFalse(ParamUtils.isValid("test!"));
assertFalse(ParamUtils.isValid("test~"));
} |
public static InetSocketAddress replaceUnresolvedNumericIp(InetSocketAddress inetSocketAddress) {
requireNonNull(inetSocketAddress, "inetSocketAddress");
if (!inetSocketAddress.isUnresolved()) {
return inetSocketAddress;
}
InetSocketAddress inetAddressForIpString = createForIpString(
inetSocketAddress.ge... | @Test
void shouldNotReplaceIfAlreadyResolvedWhenCallingReplaceUnresolvedNumericIp() {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 80);
InetSocketAddress processedAddress = AddressUtils.replaceUnresolvedNumericIp(socketAddress);
assertThat(processedAddress).isSameAs(socketAddress);
} |
@Override
public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance {}", namespaceId, serviceName,
instance);
if (instance.isEphemeral()) {
re... | @Test
void testRegisterServiceThrowsNacosException() throws NacosException {
Throwable exception = assertThrows(NacosException.class, () -> {
when(this.rpcClient.request(Mockito.any())).thenReturn(ErrorResponse.build(400, "err args"));
try {
... |
public void initialize(final BlockStore blockStore, final StoredBlock chainHead)
throws BlockStoreException {
StoredBlock versionBlock = chainHead;
final Stack<Long> versions = new Stack<>();
// We don't know how many blocks back we can go, so load what we can first
versions.pus... | @Test
public void testInitialize() throws BlockStoreException {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
final BlockStore blockStore = new MemoryBlockStore(TESTNET.getGenesisBlock());
final BlockChain chain = new BlockChain(BitcoinNetwork.TESTNET, blockSt... |
@Override
protected SchemaTransform from(SchemaTransformConfiguration configuration) {
return new IcebergReadSchemaTransform(configuration);
} | @Test
public void testBuildTransformWithRow() {
Map<String, String> properties = new HashMap<>();
properties.put("type", CatalogUtil.ICEBERG_CATALOG_TYPE_HADOOP);
properties.put("warehouse", "test_location");
Row transformConfigRow =
Row.withSchema(new IcebergReadSchemaTransformProvider().con... |
public byte[] serialize() throws Throwable {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
putInt(outputStream, this.replicaInfoTable.size());
for (Map.Entry<String, BrokerReplicaInfo> entry : replicaInfoTable.entrySet()) {
final byte[] brokerNa... | @Test
public void testSerialize() {
mockMetaData();
byte[] data;
try {
data = this.replicasInfoManager.serialize();
} catch (Throwable e) {
throw new RuntimeException(e);
}
final ReplicasInfoManager newReplicasInfoManager = new ReplicasInfoMana... |
public static DescribeAclsRequest parse(ByteBuffer buffer, short version) {
return new DescribeAclsRequest(new DescribeAclsRequestData(new ByteBufferAccessor(buffer), version), version);
} | @Test
public void shouldRoundTripPrefixedV1() {
final DescribeAclsRequest original = new DescribeAclsRequest.Builder(PREFIXED_FILTER).build(V1);
final DescribeAclsRequest result = DescribeAclsRequest.parse(original.serialize(), V1);
assertRequestEquals(original, result);
} |
public static Pipeline updateTransform(
String urn, Pipeline originalPipeline, TransformReplacement compositeBuilder) {
Components.Builder resultComponents = originalPipeline.getComponents().toBuilder();
for (Map.Entry<String, PTransform> pt :
originalPipeline.getComponents().getTransformsMap().en... | @Test
public void replaceExistingCompositeSucceeds() {
Pipeline p =
Pipeline.newBuilder()
.addRootTransformIds("root")
.setComponents(
Components.newBuilder()
.putTransforms(
"root",
PTransform.newB... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<ListQueries> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final RemoteHostExecutor remoteHostExecutor = RemoteHostExecuto... | @Test
public void shouldIncludeUnresponsiveIfShowQueriesFutureThrowsException() {
// Given
when(sessionProperties.getInternalRequest()).thenReturn(false);
final ConfiguredStatement<?> showQueries = engine.configure("SHOW QUERIES;");
final PersistentQueryMetadata metadata = givenPersistentQuery("id", R... |
public static UserGroupInformation getUGI(HttpServletRequest request,
Configuration conf) throws IOException {
return getUGI(null, request, conf);
} | @Test
public void testGetProxyUgi() throws IOException {
conf.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://localhost:4321/");
ServletContext context = mock(ServletContext.class);
String realUser = "TheDoctor";
String user = "TheNurse";
conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "kerb... |
@Override
protected void onPreExecute() {
super.onPreExecute();
if (dbViewerFragment.databaseViewerActivity.getAppTheme().equals(AppTheme.DARK)
|| dbViewerFragment.databaseViewerActivity.getAppTheme().equals(AppTheme.BLACK)) {
htmlInit = "<html><body><table border='1' style='width:100%;color:#... | @Test
public void testOnPreExecute() {
DbViewerFragment mock = mock(DbViewerFragment.class);
AppCompatTextView loadingText =
new AppCompatTextView(ApplicationProvider.getApplicationContext());
mock.loadingText = loadingText;
mock.databaseViewerActivity = mock(DatabaseViewerActivity.class);
... |
@Override
public PMMLRequestData getRequestData() {
return (PMMLRequestData) get(PMML_REQUEST_DATA);
} | @Test
void getRequestData() {
PMMLRequestData requestData = new PMMLRequestData();
PMMLRuntimeContextImpl retrieved = new PMMLRuntimeContextImpl(requestData, fileName, memoryCompilerClassLoader);
assertThat(retrieved.getRequestData()).isEqualTo(requestData);
} |
public static URL socketToUrl(InetSocketAddress socketAddress) {
String hostString = socketAddress.getHostString();
// If the hostString is an IPv6 address, it needs to be enclosed in square brackets
// at the beginning and end.
if (socketAddress.getAddress() != null
&& s... | @Test
void testSocketToUrl() throws MalformedURLException {
InetSocketAddress socketAddress = new InetSocketAddress("foo.com", 8080);
URL expectedResult = new URL("http://foo.com:8080");
assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
} |
@Deprecated
@Override
public Boolean hasAppendsOnly(org.apache.hadoop.hive.ql.metadata.Table hmsTable, SnapshotContext since) {
TableDesc tableDesc = Utilities.getTableDesc(hmsTable);
Table table = IcebergTableUtil.getTable(conf, tableDesc.getProperties());
return hasAppendsOnly(table.snapshots(), since... | @Test
public void testHasAppendsOnlyTrueWhenGivenSnapShotIsNull() {
HiveIcebergStorageHandler storageHandler = new HiveIcebergStorageHandler();
Boolean result = storageHandler.hasAppendsOnly(singletonList(appendSnapshot), null);
assertThat(result, is(true));
} |
public void findIntersections(Rectangle query, Consumer<T> consumer)
{
IntArrayList todoNodes = new IntArrayList(levelOffsets.length * degree);
IntArrayList todoLevels = new IntArrayList(levelOffsets.length * degree);
int rootLevel = levelOffsets.length - 1;
int rootIndex = levelOff... | @Test
public void testSingletonFlatbush()
{
List<Rectangle> items = ImmutableList.of(new Rectangle(0, 0, 1, 1));
Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {}));
assertEquals(findIntersections(rtree, EVERYTHING), items);
// hit
assertEquals(... |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
SendMessageContext sendMessageContext;
switch (request.getCode()) {
case RequestCode.CONSUMER_SEND_MSG_BACK:
return this.consumerS... | @Test
public void testProcessRequest() throws Exception {
when(messageStore.asyncPutMessage(any(MessageExtBrokerInner.class))).
thenReturn(CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))));
assertPutResu... |
@VisibleForTesting
public ProcessContinuation run(
RestrictionTracker<OffsetRange, Long> tracker,
OutputReceiver<PartitionRecord> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
InitialPipelineState initialPipelineState)
throws Exception {
LOG.debug("DNP: Watermark: "... | @Test
public void testBackToBackReconcile() throws Exception {
// We only start reconciling after 50.
// We advance watermark on every 2 restriction tracker advancement
OffsetRange offsetRange = new OffsetRange(52, Long.MAX_VALUE);
when(tracker.currentRestriction()).thenReturn(offsetRange);
when(t... |
boolean hasMoreAvailableCapacityThan(final ClientState other) {
if (capacity <= 0) {
throw new IllegalStateException("Capacity of this ClientState must be greater than 0.");
}
if (other.capacity <= 0) {
throw new IllegalStateException("Capacity of other ClientState must ... | @Test
public void shouldThrowIllegalStateExceptionIfCapacityOfThisClientStateIsZero() {
assertThrows(IllegalStateException.class, () -> zeroCapacityClient.hasMoreAvailableCapacityThan(client));
} |
@Override
public char[] convert(String source) {
return isNotEmpty(source) ? source.toCharArray() : null;
} | @Test
void testConvert() {
assertArrayEquals(new char[] {'1', '2', '3'}, converter.convert("123"));
assertNull(converter.convert(null));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.