focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public boolean contains(final Object value)
{
return contains((int)value);
} | @Test
void initiallyContainsNoElements()
{
for (int i = 0; i < 10_000; i++)
{
assertFalse(testSet.contains(i));
}
} |
@DELETE
@Path("{id}")
@Timed
@ApiOperation(value = "Delete index set")
@AuditEvent(type = AuditEventTypes.INDEX_SET_DELETE)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "Unauthorized"),
@ApiResponse(code = 404, message = "Index set not found"),
})
public... | @Test
public void deleteDenied() {
notPermitted();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Not authorized to access resource id <id>");
try {
indexSetsResource.delete("id", false);
} finally {
verifyNoMore... |
String buildCustomMessage(EventNotificationContext ctx, TeamsEventNotificationConfig config, String template) throws PermanentEventNotificationException {
final List<MessageSummary> backlog = getMessageBacklog(ctx, config);
Map<String, Object> model = getCustomMessageModel(ctx, config.type(), backlog, c... | @Test(expected = PermanentEventNotificationException.class)
public void buildCustomMessageWithInvalidTemplate() throws EventNotificationException {
teamsEventNotificationConfig = buildInvalidTemplate();
teamsEventNotification.buildCustomMessage(eventNotificationContext, teamsEventNotificationConfig,... |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testRetryByException() throws UnreliableException {
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
Collections.<Class<? extends Exception>, RetryPolicy>singletonMap(FatalException.class, TRY_ONCE_THEN_FAIL);
UnreliableInterface unreliable = (UnreliableInterfac... |
@Override
public void monitor(RedisServer master) {
connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(),
master.getPort().intValue(), master.getQuorum().intValue());
} | @Test
public void testMonitor() {
Collection<RedisServer> masters = connection.masters();
RedisServer master = masters.iterator().next();
master.setName(master.getName() + ":");
connection.monitor(master);
} |
public boolean hasLogicTable(final String logicTable) {
return shardingTables.containsKey(logicTable);
} | @Test
void assertHasLogicTable() {
assertTrue(createBindingTableRule().hasLogicTable("Logic_Table"));
} |
@Override
public Object deserialize(Asn1ObjectInputStream in, Class<? extends Object> type, Asn1ObjectMapper mapper) {
final Asn1Entity entity = type.getAnnotation(Asn1Entity.class);
final Fields fields = new FieldSet(entity.partial(), mapper.getFields(type));
return readFields(mapper, in, f... | @Test
public void shouldDeserializeWithOptional() {
assertEquals(new Set(1, 2, 3), deserialize(
new SetConverter(), Set.class, new byte[] {
(byte) 0x81, 1, 0x01, (byte) 0x82, 1, 0x02, (byte) 0x83, 1, 0x03
}
));
} |
public List<MessageQueue> fetchPublishMessageQueues(String topic) throws MQClientException {
try {
TopicRouteData topicRouteData = this.mQClientFactory.getMQClientAPIImpl().getTopicRouteInfoFromNameServer(topic, timeoutMillis);
if (topicRouteData != null) {
TopicPublishIn... | @Test
public void assertFetchPublishMessageQueues() throws MQClientException {
List<MessageQueue> queueList = mqAdminImpl.fetchPublishMessageQueues(defaultTopic);
assertNotNull(queueList);
assertEquals(6, queueList.size());
for (MessageQueue each : queueList) {
assertEqua... |
@Override
public ImportResult importItem(UUID jobId,
IdempotentImportExecutor idempotentExecutor,
TokensAndUrlAuthData authData, ContactsModelWrapper data) throws Exception{
JCardReader reader = new JCardReader(data.getVCards());
try {
// TODO(olsona): address any other problems that might a... | @Test
public void importFirstResources() throws Exception {
// Set up: small number of VCards to be imported
int numberOfVCards = 5;
List<VCard> vCardList = new LinkedList<>();
for (int i = 0; i < numberOfVCards; i++) {
StructuredName structuredName = new StructuredName();
structuredName.s... |
@Override
public boolean equals(Object obj) {
if (obj instanceof SqlDaySecondInterval) {
SqlDaySecondInterval other = ((SqlDaySecondInterval) obj);
return millis == other.millis;
}
return false;
} | @Test
public void testEquals() {
SqlDaySecondInterval value = new SqlDaySecondInterval(1);
checkEquals(value, new SqlDaySecondInterval(1), true);
checkEquals(value, new SqlDaySecondInterval(2), false);
} |
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "lookupConstraints is ImmutableList")
public List<LookupConstraint> getLookupConstraints() {
return lookupConstraints;
} | @Test
public void shouldExtractKeyFromNonEqualComparison() {
// Given:
final Expression expression = new ComparisonExpression(
Type.GREATER_THAN,
new UnqualifiedColumnReferenceExp(ColumnName.of("K")),
new IntegerLiteral(1)
);
final QueryFilterNode filterNode = new QueryFilterN... |
@Override
public Map<String, Node> allActive() {
return transformMap(delegate.allActive());
} | @Test
public void testAllActive() throws NodeNotFoundException {
assertThat(nodeService.allActive().keySet()).isEmpty();
nodeService.registerServer(nodeId.getNodeId(), true, TRANSPORT_URI, LOCAL_CANONICAL_HOSTNAME);
assertThat(nodeService.allActive().keySet()).containsExactly(nodeId.getNodeI... |
@Override
public PageData<WidgetsBundle> findAllTenantWidgetsBundlesByTenantId(WidgetsBundleFilter widgetsBundleFilter, PageLink pageLink) {
return findTenantWidgetsBundlesByTenantIds(Arrays.asList(widgetsBundleFilter.getTenantId().getId(), NULL_UUID), widgetsBundleFilter, pageLink);
} | @Test
public void testTagsSearchInFindAllWidgetsBundlesByTenantId() {
for (var entry : SHOULD_FIND_SEARCH_TO_TAGS_MAP.entrySet()) {
String searchText = entry.getKey();
String[] tags = entry.getValue();
WidgetsBundle systemWidgetBundle = createSystemWidgetBundle("Test Wid... |
static final String[] getPrincipalNames(String keytabFileName) throws IOException {
Keytab keytab = Keytab.loadKeytab(new File(keytabFileName));
Set<String> principals = new HashSet<>();
List<PrincipalName> entries = keytab.getPrincipals();
for (PrincipalName entry : entries) {
principals.add(entr... | @Test
public void testGetPrincipalNamesFromKeytab() throws IOException {
createKeyTab(testKeytab, testPrincipals);
// read all principals in the keytab file
String[] principals = KerberosUtil.getPrincipalNames(testKeytab);
Assert.assertNotNull("principals cannot be null", principals);
int ex... |
public static String toString(Object obj) {
return String.valueOf(obj);
} | @Test
public void upperFirstTest() {
final StringBuilder sb = new StringBuilder("KEY");
final String s = StrUtil.upperFirst(sb);
assertEquals(s, sb.toString());
} |
public static IpAddress valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new IpAddress(Version.INET, bytes);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfArrayInvalidOffsetIPv6() {
IpAddress ipAddress;
byte[] value;
value = new byte[] {11, 22, 33, // Preamble
0x11, 0x11, 0x22, 0x22,
0x33, 0x33... |
public boolean submitProcessingErrors(Message message) {
return submitProcessingErrorsInternal(message, message.processingErrors());
} | @Test
public void submitProcessingErrors_nothingSubmittedAndMessageNotFilteredOut_ifSubmissionEnabledAndDuplicatesAreKeptAndMessageDoesntSupportFailureHandling() throws Exception {
// given
final Message msg = Mockito.mock(Message.class);
when(msg.getMessageId()).thenReturn("msg-x");
... |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testZeroGuar() {
int[][] qData = new int[][] {
// / A B C D E F
{ 200, 100, 0, 99, 100, 10, 90 }, // abs
{ 200, 200, 200, 200, 200, 200, 200 }, // maxCap
{ 170, 80, 60, 20, 90, 90, 0 }, // used
{ 10, 0, 0, 0, 10, 0, 10 }, // pend... |
@Around(CLIENT_INTERFACE_PUBLISH_CONFIG_RPC)
Object publishConfigAroundRpc(ProceedingJoinPoint pjp, ConfigPublishRequest request, RequestMeta meta)
throws Throwable {
final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_RPC;
final List<ConfigCha... | @Test
void testPublishConfigAroundRpc() throws Throwable {
Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE);
ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class);
ConfigPublishRequest request = new Con... |
private int addValueMeta( RowMetaInterface rowMeta, String fieldName ) {
ValueMetaInterface valueMeta = new ValueMetaString( fieldName );
valueMeta.setOrigin( getStepname() );
// add if doesn't exist
int index = -1;
if ( !rowMeta.exists( valueMeta ) ) {
index = rowMeta.size();
rowMeta.ad... | @Test
public void readInputWithDefaultValues() throws Exception {
final String virtualFile = createVirtualFile( "pdi-14832.txt", "1,\n" );
TextFileInputMeta meta = new TextFileInputMeta();
TextFileInputField field2 = field( "col2" );
field2.setIfNullValue( "DEFAULT" );
meta.setInputFields( new Te... |
@Override
public void onTaskFinished(TaskAttachment attachment) {
if (attachment instanceof BrokerPendingTaskAttachment) {
onPendingTaskFinished((BrokerPendingTaskAttachment) attachment);
} else if (attachment instanceof BrokerLoadingTaskAttachment) {
onLoadingTaskFinished((B... | @Test
public void testPendingTaskOnFinishedWithJobCancelled(@Injectable BrokerPendingTaskAttachment attachment) {
BrokerLoadJob brokerLoadJob = new BrokerLoadJob();
Deencapsulation.setField(brokerLoadJob, "state", JobState.CANCELLED);
brokerLoadJob.onTaskFinished(attachment);
Set<Lo... |
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
} | @Test
public void grow() {
// Default capacity is 10
IntArrayList list = new IntArrayList();
for (int i = 1; i <= 11; i++) {
list.add(i);
}
assertThat(list.trimAndGet()).hasSize(11);
} |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testNewMemberIsRejectedWithMaximumMembersIsReached() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
String memberId3 = Uuid.... |
@Override
public void deleteRewardActivity(Long id) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(id);
if (!dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 未关闭的活动,不能删除噢
throw exception(REWARD_ACTIVITY_DELETE_FA... | @Test
public void testDeleteRewardActivity_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> rewardActivityService.deleteRewardActivity(id), REWARD_ACTIVITY_NOT_EXISTS);
} |
@Override
public Num calculate(BarSeries series, Position position) {
if (position == null || !position.isClosed()) {
return series.zero();
}
Returns returns = new Returns(series, position, Returns.ReturnType.LOG);
return calculateVaR(returns, confidence);
} | @Test
public void calculateWithNoBarsShouldReturn0() {
series = new MockBarSeries(numFunction, 100d, 95d, 100d, 80d, 85d, 70d);
AnalysisCriterion varCriterion = getCriterion();
assertNumEquals(numOf(0), varCriterion.calculate(series, new BaseTradingRecord()));
} |
public void apply() {
if (applied) {
throw new IllegalStateException("can't apply twice");
}
applied = true;
PluginFileWriteRule writeRule = new PluginFileWriteRule(
props.nonNullValueAsFile(ProcessProperties.Property.PATH_HOME.getKey()).toPath(),
props.nonNullValueAsFile(ProcessPrope... | @Test
public void apply_calls_PluginSecurityManager() {
Properties properties = new Properties();
properties.setProperty(PATH_HOME.getKey(), "home");
properties.setProperty(PATH_TEMP.getKey(), "temp");
Props props = new Props(properties);
CeSecurityManager ceSecurityManager = new CeSecurityManager... |
@Override
public Set<TopicPartition> getAllSubscribedPartitions(Consumer<?, ?> consumer) {
Set<TopicPartition> allPartitions = new HashSet<>();
for (String topic : topics) {
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic);
if (partitionInfoList != null) ... | @Test
public void testFilter() {
String matchingTopicOne = "test-1";
String matchingTopicTwo = "test-11";
String unmatchedTopic = "unmatched";
NamedTopicFilter filter = new NamedTopicFilter(matchingTopicOne, matchingTopicTwo);
when(consumerMock.partitionsFor... |
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return DatasourceConfiguration.isEmbeddedStorage() && EnvUtil.getStandaloneMode();
} | @Test
void testMatches() {
MockedStatic<DatasourceConfiguration> propertyUtilMockedStatic = Mockito.mockStatic(DatasourceConfiguration.class);
MockedStatic<EnvUtil> envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class);
propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbe... |
@Override
public ConfigDef config() {
return CONFIG_DEF;
} | @Test
public void testPatternMayNotBeEmptyInConfig() {
Map<String, String> props = new HashMap<>();
props.put("pattern", "");
ConfigException e = assertThrows(ConfigException.class, () -> config(props));
assertTrue(e.getMessage().contains("String must be non-empty"));
} |
public static void main(String[] args) {
new App("No Danger", "Green Light");
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@SuppressWarnings({"deprecation", "checkstyle:linelength"})
public void convertSiteProperties(Configuration conf,
Configuration yarnSiteConfig, boolean drfUsed,
boolean enableAsyncScheduler, boolean userPercentage,
FSConfigToCSConfigConverterParams.PreemptionMode preemptionMode) {
yarnSiteConfig... | @Test
public void testSiteDrfEnabledConversion() {
converter.convertSiteProperties(yarnConfig, yarnConvertedConfig, true,
false, false, null);
assertEquals("Resource calculator type", DominantResourceCalculator.class,
yarnConvertedConfig.getClass(
CapacitySchedulerConfiguration.RE... |
public int minValue()
{
final int missingValue = this.missingValue;
int min = 0 == size ? missingValue : Integer.MAX_VALUE;
final int[] entries = this.entries;
@DoNotSub final int length = entries.length;
for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += ... | @Test
void shouldHaveNoMinValueForEmptyCollection()
{
assertEquals(MISSING_VALUE, map.minValue());
} |
@Override
public Stream<Pair<String, CompactionOperation>> getPendingLogCompactionOperations() {
return execute(preferredView::getPendingLogCompactionOperations, () -> getSecondaryView().getPendingLogCompactionOperations());
} | @Test
public void testGetPendingLogCompactionOperations() {
Stream<Pair<String, CompactionOperation>> actual;
Stream<Pair<String, CompactionOperation>> expected = Collections.singleton(
(Pair<String, CompactionOperation>) new ImmutablePair<>("test", new CompactionOperation()))
.stream();
... |
@Override
public Response filter(Request request, RequestMeta meta, Class handlerClazz) throws NacosException {
try {
Method method = getHandleMethod(handlerClazz);
if (method.isAnnotationPresent(Secured.class) && authConfigs.isAuthEnabled()) {
... | @Test
void testFilter() {
Mockito.when(authConfigs.isAuthEnabled()).thenReturn(true);
Request healthCheckRequest = new HealthCheckRequest();
try {
Response healthCheckResponse = remoteRequestAuthFilter.filter(healthCheckRequest, new RequestMeta(), MockRequestHan... |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_have_publish_plugin_disabled_by_default() {
RuntimeOptions options = cucumberPropertiesParser
.parse(properties)
.enablePublishPlugin()
.build();
assertThat(options.plugins(), empty());
} |
@Override
public PrimitiveTypeEncoding<UTF8Buffer> getEncoding(UTF8Buffer value) {
return value.getLength() <= 255 ? smallBufferEncoding : largeBufferEncoding;
} | @Test
public void testGetEncodingForSmallUTF8Buffer() {
PrimitiveTypeEncoding<UTF8Buffer> encoding = utf8BufferEncoding.getEncoding(smallBuffer);
assertTrue(encoding instanceof UTF8BufferType.SmallUTF8BufferEncoding);
assertEquals(1, encoding.getConstructorSize());
assertEquals(smal... |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void testMetadataVersionIsOlderThanDefaultKafkaVersion() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withMetadataVersion(KafkaVersionTestUtils.PREVIOUS_METADATA_VERSION)
.endKafka()
... |
public static URL toURL(java.nio.file.Path path) throws MalformedURLException {
final String scheme = path.toUri().getScheme();
return new URL(scheme, null, -1, path.toString());
} | @Test
void testAbsolutePathToURL() throws MalformedURLException {
final java.nio.file.Path absolutePath = temporaryFolder.getRoot().toAbsolutePath();
final URL absoluteURL = FileUtils.toURL(absolutePath);
final java.nio.file.Path transformedURL = Paths.get(absoluteURL.getPath());
as... |
public static Find find(String regex) {
return find(regex, 0);
} | @Test
@Category(NeedsRunner.class)
public void testFindNone() {
PCollection<String> output = p.apply(Create.of("a", "b", "c", "d")).apply(Regex.find("[xyz]"));
PAssert.that(output).empty();
p.run();
} |
@Override
public Class<? extends SumLabeledStorageBuilder> builder() {
return SumLabeledStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
function.accept(
MeterEntity.newService("service-test", Layer.GENERAL),
HTTP_CODE_COUNT_1
);
function.calculate();
StorageBuilder<SumLabeledFunction> storageBuilder = func... |
public static NearCacheConfig copyWithInitializedDefaultMaxSizeForOnHeapMaps(NearCacheConfig nearCacheConfig) {
if (nearCacheConfig == null) {
return null;
}
EvictionConfig evictionConfig = nearCacheConfig.getEvictionConfig();
if (nearCacheConfig.getInMemoryFormat() == InMem... | @Test
public void testCopyInitDefaultMaxSizeForOnHeapMaps_doesNotCopy_whenSizeIsConfigured() {
NearCacheConfig nearCacheConfig = new NearCacheConfig();
nearCacheConfig.setEvictionConfig(new EvictionConfig().setSize(10));
NearCacheConfig copy = NearCacheConfigAccessor.copyWithInitializedDefau... |
String getOwnerId(TbContext ctx) {
return "Tenant[" + ctx.getTenantId().getId() + "]RuleNode[" + ctx.getSelf().getId().getId() + "]";
} | @Test
public void verifyGetOwnerIdMethod() {
given(ctxMock.getTenantId()).willReturn(TENANT_ID);
given(ctxMock.getSelf()).willReturn(new RuleNode(RULE_NODE_ID));
String actualOwnerIdStr = mqttNode.getOwnerId(ctxMock);
String expectedOwnerIdStr = "Tenant[" + TENANT_ID.getId() + "]Rul... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest req) {
var now = clock.instant();
var bearerToken = requestBearerToken(req).orElse(null);
if (bearerToken == null) {
log.fine("Missing bearer token");
return Optional.of(new ErrorResponse(Response.St... | @Test
void fails_for_token_with_invalid_permission() {
var req = FilterTestUtils.newRequestBuilder()
.withMethod(Method.GET)
.withHeader("Authorization", "Bearer " + WRITE_TOKEN.secretTokenString())
.build();
var responseHandler = new MockResponseHandl... |
@Override
public boolean put(PageId pageId, ByteBuffer page, CacheContext cacheContext) {
LOG.debug("put({},{} bytes) enters", pageId, page.remaining());
if (mState.get() != READ_WRITE) {
Metrics.PUT_NOT_READY_ERRORS.inc();
Metrics.PUT_ERRORS.inc();
return false;
}
int originPosition... | @Test
public void highStorageOverheadPut() throws Exception {
// a store that is so inefficient to store any data
double highOverhead = CACHE_SIZE_BYTES / PAGE_SIZE_BYTES + 0.1;
mConf.set(PropertyKey.USER_CLIENT_CACHE_STORE_OVERHEAD, highOverhead);
mCacheManager = createLocalCacheManager();
assert... |
public static HttpHeaderDateFormat get() {
return dateFormatThreadLocal.get();
} | @Test
public void testFormat() {
HttpHeaderDateFormat format = HttpHeaderDateFormat.get();
final String formatted = format.format(DATE);
assertNotNull(formatted);
assertEquals("Sun, 06 Nov 1994 08:49:37 GMT", formatted);
} |
public static List<Chunk> split(String s) {
int pos = s.indexOf(SLASH);
if (pos == -1) {
throw new RuntimeException("path did not start with or contain '/'");
}
List<Chunk> list = new ArrayList();
int startPos = 0;
int searchPos = 0;
boolean anyDepth =... | @Test
void testOnlyName2() {
List<PathSearch.Chunk> list = PathSearch.split("//listitem/{Taxpayer Information}");
logger.debug("list: {}", list);
PathSearch.Chunk first = list.get(0);
assertTrue(first.anyDepth);
assertEquals("listitem", first.controlType);
assertNull(... |
public void addBasicProperty(String name, String strValue) {
if (strValue == null) {
return;
}
name = StringUtil.capitalizeFirstLetter(name);
Method adderMethod =aggregationAssessor.findAdderMethod(name);
if (adderMethod == null) {
addError("No adder fo... | @Test
public void addValueOfTest() {
setter.addBasicProperty("fileSize", "1GB");
setter.addBasicProperty("fileSize", "10KB");
assertEquals(2, house.fileSizes.size());
assertEquals(FileSize.valueOf("1GB"), house.fileSizes.get(0));
assertEquals(FileSize.valueOf("10KB"), house.... |
public String defaultRemoteUrl() {
final String sanitizedUrl = sanitizeUrl();
try {
URI uri = new URI(sanitizedUrl);
if (uri.getUserInfo() != null) {
uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri... | @Test
void shouldReturnTheURLWhenNoCredentialsAreSpecified() {
assertThat(new HgUrlArgument("http://url##branch").defaultRemoteUrl(), is("http://url#branch"));
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateJob(JobSaveReqVO updateReqVO) throws SchedulerException {
validateCronExpression(updateReqVO.getCronExpression());
// 校验存在
JobDO job = validateJobExists(updateReqVO.getId());
// 只有开启状态,才可以修改.原因是,如果出暂停状态,修改 ... | @Test
public void testUpdateJob_success() throws SchedulerException {
// mock 数据
JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus()));
jobMapper.insert(job);
// 准备参数
JobSaveReqVO updateReqVO = randomPojo(JobSaveReqVO.class, o -> {
... |
@PublicAPI(usage = ACCESS)
public Md5sum getMd5sum() {
return md5sum;
} | @Test
public void compensates_error_on_md5_calculation() throws Exception {
Source source = newSource(new URI("bummer"));
assertThat(source.getMd5sum()).isEqualTo(Md5sum.UNDETERMINED);
} |
@ScalarOperator(ADD)
@SqlType(StandardTypes.REAL)
public static long add(@SqlType(StandardTypes.REAL) long left, @SqlType(StandardTypes.REAL) long right)
{
return floatToRawIntBits(intBitsToFloat((int) left) + intBitsToFloat((int) right));
} | @Test
public void testAdd()
{
assertFunction("REAL'12.34' + REAL'56.78'", REAL, 12.34f + 56.78f);
assertFunction("REAL'-17.34' + REAL'-22.891'", REAL, -17.34f + -22.891f);
assertFunction("REAL'-89.123' + REAL'754.0'", REAL, -89.123f + 754.0f);
assertFunction("REAL'-0.0' + REAL'0.... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testMultipleAbortMarkers() {
buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
ByteBuffer buffer = ByteBuffer.allocate(1024);
int currentOffset = 0;
... |
public static BigDecimal toNanos(Timestamp timestamp) {
final BigDecimal secondsAsNanos =
BigDecimal.valueOf(timestamp.getSeconds()).subtract(MIN_SECONDS).scaleByPowerOfTen(9);
final BigDecimal nanos = BigDecimal.valueOf(timestamp.getNanos());
return secondsAsNanos.add(nanos);
} | @Test
public void testToNanosConvertTimestampToNanos() {
assertEquals(
new BigDecimal("62135596810000000009"),
TimestampUtils.toNanos(Timestamp.ofTimeSecondsAndNanos(10L, 9)));
} |
public void ensureActiveGroup() {
while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) {
log.warn("still waiting to ensure active group");
}
} | @Test
public void testWakeupAfterSyncGroupSentExternalCompletion() throws Exception {
setupCoordinator();
mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
mockClient.prepareResponse(joinGroupFollowerResponse(1, memberId, leaderId, Errors.NONE));
mockClient.pr... |
Map<ProjectionProducer<PTransform<?, ?>>, Map<PCollection<?>, FieldAccessDescriptor>>
getPushdownOpportunities() {
return pushdownOpportunities.build();
} | @Test
public void testSimplePushdownProducer_returnsOnePushdown() {
Pipeline p = Pipeline.create();
PTransform<PBegin, PCollection<Row>> source = new SimpleSourceWithPushdown();
PCollection<Row> output = p.apply(source);
Map<PCollection<?>, FieldAccessDescriptor> pCollectionFieldAccess =
Immu... |
@Override
public void asyncRequest(Request request, final RequestCallBack requestCallBack) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
//set callback .
Futures... | @Test
void testAsyncRequestError() throws NacosException, ExecutionException, InterruptedException {
when(future.get()).thenReturn(errorResponsePayload);
doAnswer(invocationOnMock -> {
((Runnable) invocationOnMock.getArgument(0)).run();
return null;
}).when(future).ad... |
@Override
protected ExecuteContext doAfter(ExecuteContext context) {
final Class<?> type = (Class<?>) context.getMemberFieldValue("type");
if (type == null) {
return context;
}
if (canInjectClusterInvoker(type.getName()) && isDefined.compareAndSet(false, true)) {
... | @Test
public void testApacheDubbo() throws NoSuchMethodException {
final ExtensionLoaderInterceptor interceptor = new ExtensionLoaderInterceptor();
final HashMap<String, Class<?>> result = new HashMap<>();
interceptor.doAfter(buildContext(true, result));
Assert.assertEquals(result.ge... |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldCastDecimalRoundingUpNegative() {
// When:
final BigDecimal decimal = DecimalUtil.cast(new BigDecimal("-1.12"), 2, 1);
// Then:
assertThat(decimal, is(new BigDecimal("-1.1")));
} |
public static void clean(
Object func, ExecutionConfig.ClosureCleanerLevel level, boolean checkSerializable) {
clean(func, level, checkSerializable, Collections.newSetFromMap(new IdentityHashMap<>()));
} | @Test
void testWriteReplace() {
WithWriteReplace.SerializablePayload writeReplace =
new WithWriteReplace.SerializablePayload(new WithWriteReplace.Payload("text"));
assertThat(writeReplace.get().getRaw()).isEqualTo("text");
ClosureCleaner.clean(writeReplace, ExecutionConfig.Cl... |
public static int getFieldCount(LogicalType logicalType) {
return logicalType.accept(FIELD_COUNT_EXTRACTOR);
} | @Test
void testFieldCountExtraction() {
DataType dataType = ROW(FIELD("f0", INT()), FIELD("f1", STRING()));
assertThat(LogicalTypeChecks.getFieldCount(dataType.getLogicalType())).isEqualTo(2);
} |
@Override
public long arrayInsert(String path, long index, Object... values) {
return get(arrayInsertAsync(path, index, values));
} | @Test
public void testArrayInsert() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
TestType t = new TestType();
NestedType nt = new NestedType();
nt.setValues(Arrays.asList("t1", "t2", "t4"));
t.setType(nt);
al.set(t);... |
public List<String[]> select(int m) {
final List<String[]> result = new ArrayList<>((int) count(this.datas.length, m));
select(0, new String[m], 0, result);
return result;
} | @Test
public void selectTest() {
Combination combination = new Combination(new String[] { "1", "2", "3", "4", "5" });
List<String[]> list = combination.select(2);
assertEquals(Combination.count(5, 2), list.size());
assertArrayEquals(new String[] {"1", "2"}, list.get(0));
assertArrayEquals(new String[] {"1",... |
public static List<TierFactory> initializeTierFactories(Configuration configuration) {
String externalTierFactoryClass =
configuration.get(
NettyShuffleEnvironmentOptions
.NETWORK_HYBRID_SHUFFLE_EXTERNAL_REMOTE_TIER_FACTORY_CLASS_NAME);
... | @Test
void testInitDurableExternalRemoteTierWithHigherPriority() {
Configuration configuration = new Configuration();
configuration.set(
NettyShuffleEnvironmentOptions.NETWORK_HYBRID_SHUFFLE_REMOTE_STORAGE_BASE_PATH,
tmpDir.toString());
configuration.set(
... |
public static boolean canDrop(
FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) {
Objects.requireNonNull(pred, "pred cannnot be null");
Objects.requireNonNull(columns, "columns cannnot be null");
return pred.accept(new DictionaryFilter(columns, dictionarie... | @Test
public void testLtEqMissingColumn() throws Exception {
BinaryColumn b = binaryColumn("missing_column");
assertTrue(
"Should drop block for any non-null query",
canDrop(ltEq(b, Binary.fromString("any")), ccmd, dictionaries));
} |
@Override
public <T> Serde<T> createSerde(
final Schema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srFactory,
final Class<T> targetType,
final boolean isKey
) {
validateSchema(schema);
final Optional<Schema> physicalSchema;
if (useSchemaRegis... | @Test
public void shouldUseOldJsonDeserializerOnJsonSrWhenJsonSchemaConverterIsDisabled() {
// Given
final ConnectSchema connectSchema = (ConnectSchema) SchemaBuilder.string().build();
when(config.getBoolean(KsqlConfig.KSQL_JSON_SR_CONVERTER_DESERIALIZER_ENABLED))
.thenReturn(false);
// When
... |
public static boolean isCompositeType(LogicalType logicalType) {
if (logicalType instanceof DistinctType) {
return isCompositeType(((DistinctType) logicalType).getSourceType());
}
LogicalTypeRoot typeRoot = logicalType.getTypeRoot();
return typeRoot == STRUCTURED_TYPE || typ... | @Test
void testIsCompositeTypeLegacySimpleType() {
DataType dataType = TypeConversions.fromLegacyInfoToDataType(Types.STRING);
assertThat(LogicalTypeChecks.isCompositeType(dataType.getLogicalType())).isFalse();
} |
public void log(QueryLogParams params) {
_logger.debug("Broker Response: {}", params._response);
if (!(_logRateLimiter.tryAcquire() || shouldForceLog(params))) {
_numDroppedLogs.incrementAndGet();
return;
}
final StringBuilder queryLogBuilder = new StringBuilder();
for (QueryLogEntry v... | @Test
public void shouldOmitClientId() {
// Given:
Mockito.when(_logRateLimiter.tryAcquire()).thenReturn(true);
QueryLogger.QueryLogParams params = generateParams(false, 0, 456);
QueryLogger queryLogger = new QueryLogger(_logRateLimiter, 100, false, _logger, _droppedRateLimiter);
// When:
que... |
public boolean finishAndReleaseAll() {
return finish(true);
} | @Test
public void testFinishAndReleaseAll() {
ByteBuf in = Unpooled.buffer();
ByteBuf out = Unpooled.buffer();
try {
EmbeddedChannel channel = new EmbeddedChannel();
assertTrue(channel.writeInbound(in));
assertEquals(1, in.refCnt());
assertTru... |
public DirectExecutionContext getExecutionContext(
AppliedPTransform<?, ?, ?> application, StructuralKey<?> key) {
StepAndKey stepAndKey = StepAndKey.of(application, key);
return new DirectExecutionContext(
clock,
key,
(CopyOnAccessInMemoryStateInternals) applicationStateInternals.... | @Test
public void getExecutionContextDifferentStepsIndependentState() {
StructuralKey<?> myKey = StructuralKey.of("foo", StringUtf8Coder.of());
DirectExecutionContext fooContext = context.getExecutionContext(impulseProducer, myKey);
StateTag<BagState<Integer>> intBag = StateTags.bag("myBag", VarIntCoder.... |
@Override
public void execute(@Nonnull Runnable command) {
throwRejectedExecutionExceptionIfShutdown();
command.run();
} | @Test
void testExecute() {
final CompletableFuture<Thread> future = new CompletableFuture<>();
testTaskSubmissionBeforeShutdown(
testInstance ->
testInstance.execute(() -> future.complete(Thread.currentThread())));
assertThat(future).isCompletedWithVa... |
@Udf
public <T> Boolean contains(
@UdfParameter final String jsonArray,
@UdfParameter final T val
) {
try (JsonParser parser = PARSER_FACTORY.createParser(jsonArray)) {
if (parser.nextToken() != START_ARRAY) {
return false;
}
while (parser.nextToken() != null) {
fi... | @Test
public void shouldFindLongsInJsonArray() {
assertEquals(true, jsonUdf.contains("[1]", 1L));
assertEquals(true, jsonUdf.contains("[1111111111111111]", 1111111111111111L));
assertEquals(true, jsonUdf.contains("[[222222222222222], 33333]", 33333L));
assertEquals(true, jsonUdf.cont... |
public FEELFnResult<Object> invoke(@ParameterName("list") List list) {
if ( list == null || list.isEmpty() ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty"));
} else {
try {
return FEELFnResult.ofResult(C... | @Test
void invokeNullList() {
FunctionTestUtil.assertResultError(minFunction.invoke((List) null), InvalidParametersEvent.class);
} |
public static List<ValueMetaInterface> getValueMetaPluginClasses() throws KettlePluginException {
List<ValueMetaInterface> list = new ArrayList<ValueMetaInterface>();
List<PluginInterface> plugins = pluginRegistry.getPlugins( ValueMetaPluginType.class );
for ( PluginInterface plugin : plugins ) {
Va... | @Test
public void testGetValueMetaPluginClasses() throws KettlePluginException {
List<ValueMetaInterface> dataTypes = ValueMetaFactory.getValueMetaPluginClasses();
boolean numberExists = false;
boolean stringExists = false;
boolean dateExists = false;
boolean booleanExists = false;
boolean in... |
public static boolean isBasicType(Object object) {
if (null == object) {
return false;
}
return ClassUtil.isBasicType(object.getClass());
} | @Test
public void isBasicTypeTest() {
int a = 1;
final boolean basicType = ObjectUtil.isBasicType(a);
assertTrue(basicType);
} |
@Override
@Nullable
public int[] readIntArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, INT_ARRAY, super::readIntArray);
} | @Test
public void testReadIntArray() throws Exception {
assertNull(reader.readIntArray("NO SUCH FIELD"));
} |
@Override
protected void addWordToStorage(String word, int frequency) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testCanNotAddToStorage() {
mUnderTest.addWordToStorage("wording", 3);
} |
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
return delegate.invokeAll(tasks);
} | @Test
public void invokeAll1() throws InterruptedException {
underTest.invokeAll(callables, timeout, SECONDS);
verify(executorService).invokeAll(callables, timeout, SECONDS);
} |
@Override
protected void validateDataImpl(TenantId tenantId, Customer customer) {
validateString("Customer title", customer.getTitle());
if (customer.getTitle().equals(CustomerServiceImpl.PUBLIC_CUSTOMER_TITLE)) {
throw new DataValidationException("'Public' title for customer is system r... | @Test
void testValidateNameInvocation() {
Customer customer = new Customer();
customer.setTitle("Customer A");
customer.setTenantId(tenantId);
validator.validateDataImpl(tenantId, customer);
verify(validator).validateString("Customer title", customer.getTitle());
} |
@Override
public void suspend() {
switch (state()) {
case CREATED:
transitToSuspend();
break;
case RESTORING:
transitToSuspend();
break;
case RUNNING:
try {
// use try-ca... | @Test
public void shouldAlwaysSuspendCreatedTasks() {
when(stateManager.taskId()).thenReturn(taskId);
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
task = createStatefulTask(createConfig("100"), true);
assertThat(task.state(), equalTo(CREATED));
task.suspend();
... |
@Override
public void put(SchedulerQueryContext query)
throws OutOfCapacityException {
Preconditions.checkNotNull(query);
_queueLock.lock();
String groupName = _groupSelector.getSchedulerGroupName(query);
try {
SchedulerGroup groupContext = getOrCreateGroupContext(groupName);
checkGr... | @Test
public void testTakeWithLimits()
throws OutOfCapacityException, BrokenBarrierException, InterruptedException {
// Test that take() will not return query if that group is already using hardLimit resources
Map<String, Object> properties = new HashMap<>();
properties.put(ResourceManager.QUERY_WOR... |
public Labels strimziSelectorLabels() {
Map<String, String> newLabels = new HashMap<>(3);
List<String> strimziSelectorLabels = new ArrayList<>(3);
strimziSelectorLabels.add(STRIMZI_CLUSTER_LABEL);
strimziSelectorLabels.add(STRIMZI_NAME_LABEL);
strimziSelectorLabels.add(STRIMZI_K... | @Test
public void testStrimziSelectorLabels() {
Map<String, String> sourceMap = new HashMap<>(5);
sourceMap.put(Labels.STRIMZI_CLUSTER_LABEL, "my-cluster");
sourceMap.put("key1", "value1");
sourceMap.put(Labels.STRIMZI_KIND_LABEL, "Kafka");
sourceMap.put("key2", "value2");
... |
public static InetAddress findConnectingAddress(
InetSocketAddress targetAddress, long maxWaitMillis, long startLoggingAfter)
throws IOException {
if (targetAddress == null) {
throw new NullPointerException("targetAddress must not be null");
}
if (maxWaitMilli... | @Test
void testFindConnectingAddressWhenGetLocalHostThrows() throws Exception {
try (MockedStatic mocked = mockStatic(InetAddress.class)) {
mocked.when(InetAddress::getLocalHost)
.thenThrow(new UnknownHostException())
.thenCallRealMethod();
}
... |
public static Date parse(String date, ParsePosition pos) throws ParseException {
Exception fail = null;
try {
int offset = pos.getIndex();
// extract year
int year = parseInt(date, offset, offset += 4);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract... | @Test
@SuppressWarnings("UndefinedEquals")
public void testDateParseWithDefaultTimezone() throws ParseException {
String dateStr = "2018-06-25";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime();
assertThat(dat... |
@Override public String service() {
// MethodDescriptor.getServiceName() is not in our floor version: gRPC 1.2
return GrpcParser.service(call.getMethodDescriptor().getFullMethodName());
} | @Test void service() {
when(call.getMethodDescriptor()).thenReturn(methodDescriptor);
assertThat(request.service()).isEqualTo("helloworld.Greeter");
} |
public QueueConnection queueConnection(QueueConnection connection) {
// It is common to implement both interfaces
if (connection instanceof XAQueueConnection) {
return xaQueueConnection((XAQueueConnection) connection);
}
return TracingConnection.create(connection, this);
} | @Test void queueConnection_doesntDoubleWrap() {
QueueConnection wrapped = jmsTracing.queueConnection(mock(QueueConnection.class));
assertThat(jmsTracing.queueConnection(wrapped))
.isSameAs(wrapped);
} |
@Override
public URI toURI() {
throw new UnsupportedOperationException("Not implemented");
} | @Test(expectedExceptions = UnsupportedOperationException.class)
public void testToURI() {
fs.getFile("nonsuch.txt").toURI();
} |
public static <T> Write<T> delete() {
return Write.<T>builder(MutationType.DELETE).build();
} | @Test
public void testDelete() throws Exception {
List<Row> results = getRows(CASSANDRA_TABLE);
assertEquals(NUM_ROWS, results.size());
Scientist einstein = new Scientist();
einstein.id = 0;
einstein.department = "phys";
einstein.name = "Einstein";
pipeline
.apply(Create.of(einste... |
public String getGreeting() {
return "Hello World!";
} | @Test void appHasAGreeting() {
App classUnderTest = new App();
assertNotNull(classUnderTest.getGreeting(), "app should have a greeting");
} |
@VisibleForTesting
static Optional<Catalog> loadCatalog(Configuration conf, String catalogName) {
String catalogType = getCatalogType(conf, catalogName);
if (NO_CATALOG_TYPE.equalsIgnoreCase(catalogType)) {
return Optional.empty();
} else {
String name = catalogName == null ? ICEBERG_DEFAULT_C... | @Test
public void testLoadCatalogLocation() {
assertThat(Catalogs.loadCatalog(conf, Catalogs.ICEBERG_HADOOP_TABLE_NAME)).isNotPresent();
} |
public IssuesChangesNotification newIssuesChangesNotification(Set<DefaultIssue> issues, Map<String, UserDto> assigneesByUuid) {
AnalysisChange change = new AnalysisChange(analysisMetadataHolder.getAnalysisDate());
Set<ChangedIssue> changedIssues = issues.stream()
.map(issue -> new ChangedIssue.Builder(iss... | @Test
public void newIssuesChangesNotification_fails_with_ISE_if_branch_has_not_been_set() {
RuleKey ruleKey = RuleKey.of("foo", "bar");
DefaultIssue issue = new DefaultIssue()
.setRuleKey(ruleKey);
Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid();
ruleRepository.add(ruleKey);
... |
@Override
public ApiResult<TopicPartition, ListOffsetsResultInfo> handleResponse(
Node broker,
Set<TopicPartition> keys,
AbstractResponse abstractResponse
) {
ListOffsetsResponse response = (ListOffsetsResponse) abstractResponse;
Map<TopicPartition, ListOffsetsResultInfo>... | @Test
public void testHandleSuccessfulResponse() {
ApiResult<TopicPartition, ListOffsetsResultInfo> result =
handleResponse(createResponse(emptyMap()));
assertResult(result, offsetTimestampsByPartition.keySet(), emptyMap(), emptyList(), emptySet());
} |
@GetMapping("/{memberId}/products")
public ResponseEntity<List<ProductByMemberResponse>> findProductHistories(
@PathVariable("memberId") final Long memberId,
@AuthMember final Long authId
) {
return ResponseEntity.ok(memberService.findProductHistories(memberId, authId));
} | @Test
void 상품_판매_내역을_조회한다() throws Exception {
// given
when(memberService.findProductHistories(anyLong(), anyLong()))
.thenReturn(List.of(new ProductByMemberResponse(1L, 1L, "상품명", 10000, Location.BUILDING_CENTER, ProductStatus.WAITING, LocalDateTime.now())));
// when & the... |
public static void validatePolymorhpicInfo(PolymorphicInfo info) {
if (info.getPcaVersion() != 1) {
logger.error("Unsupported PCA version {}", info.getPcaVersion());
throw new ClientException("Polymorphic info is not correct");
}
int polymorphicFlags = info.getFlags().int... | @Test
public void invalidPolymorphicRandomizedPip() {
final PolymorphicInfo info = mapper.read(
Hex.decode("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"),
PolymorphicInfo.class);
ClientException thrown = assertThrows(ClientException.class, () -> Card... |
private <T> T accept(Expression<T> expr) {
return expr.accept(this);
} | @Test
public void testAnd() throws Exception {
final Expr.Greater trueExpr = Expr.Greater.create(Expr.NumberValue.create(2), Expr.NumberValue.create(1));
final Expr.Greater falseExpr = Expr.Greater.create(Expr.NumberValue.create(1), Expr.NumberValue.create(2));
assertThat(Expr.And.create(tr... |
public static boolean webSocketHostPathMatches(String hostPath, String targetPath) {
boolean exactPathMatch = true;
if (ObjectHelper.isEmpty(hostPath) || ObjectHelper.isEmpty(targetPath)) {
// This scenario should not really be possible as the input args come from the vertx-websocket consum... | @Test
void webSocketHostNullPathNotMatches() {
String hostPath = null;
String targetPath = null;
assertFalse(VertxWebsocketHelper.webSocketHostPathMatches(hostPath, targetPath));
} |
public static AWSCredentialsProvider deserialize(String awsCredentialsProviderSerialized) {
ObjectMapper om = new ObjectMapper();
om.registerModule(new AwsModule());
try {
return om.readValue(awsCredentialsProviderSerialized, AWSCredentialsProvider.class);
} catch (IOException e) {
throw new... | @Test(expected = IllegalArgumentException.class)
public void testFailOnAWSCredentialsProviderDeserialization() {
deserialize("invalid string");
} |
public static <N> ImmutableGraph<N> singletonGraph(Graph<N> graph, N node) {
final MutableGraph<N> mutableGraph = GraphBuilder.from(graph).build();
mutableGraph.addNode(node);
return ImmutableGraph.copyOf(mutableGraph);
} | @Test
public void singletonGraphWithTemplate() {
final MutableGraph<String> templateGraph = GraphBuilder
.directed()
.allowsSelfLoops(true)
.build();
final ImmutableGraph<String> singletonGraph = Graphs.singletonGraph(templateGraph, "Test");
as... |
@Override
public BufferWithSubpartition getNextBuffer(@Nullable MemorySegment transitBuffer) {
checkState(isFinished, "Sort buffer is not ready to be read.");
checkState(!isReleased, "Sort buffer is already released.");
if (!hasRemaining()) {
freeSegments.add(transitBuffer);
... | @Test
void testBufferIsRecycledWhenSortBufferIsEmpty() throws Exception {
int numSubpartitions = 10;
int bufferPoolSize = 512;
int numBuffersForSort = 20;
NetworkBufferPool globalPool = new NetworkBufferPool(bufferPoolSize, BUFFER_SIZE_BYTES);
BufferPool bufferPool = globalP... |
@VisibleForTesting
public static void validateIngestionConfig(TableConfig tableConfig, @Nullable Schema schema) {
IngestionConfig ingestionConfig = tableConfig.getIngestionConfig();
if (ingestionConfig != null) {
String tableNameWithType = tableConfig.getTableName();
// Batch
if (ingestion... | @Test
public void ingestionBatchConfigsTest() {
Map<String, String> batchConfigMap = new HashMap<>();
batchConfigMap.put(BatchConfigProperties.INPUT_DIR_URI, "s3://foo");
batchConfigMap.put(BatchConfigProperties.OUTPUT_DIR_URI, "gs://bar");
batchConfigMap.put(BatchConfigProperties.INPUT_FS_CLASS, "org... |
@Override
public SettableFuture schedule(SourceScheduler scheduler)
{
// Return a new future even if newDriverGroupReady has not finished.
// Returning the same SettableFuture instance could lead to ListenableFuture retaining too many listener objects.
// TODO: After initial scheduling,... | @Test
public void testSchedule()
{
LifespanScheduler lifespanScheduler = getLifespanScheduler();
TestingSourceScheduler sourceScheduler = new TestingSourceScheduler();
lifespanScheduler.scheduleInitial(sourceScheduler);
lifespanScheduler.onLifespanExecutionFinished(sourceSchedule... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.