focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean processData(DistroData distroData) {
switch (distroData.getType()) {
case ADD:
case CHANGE:
ClientSyncData clientSyncData = ApplicationUtils.getBean(Serializer.class)
.deserialize(distroData.getContent(), ClientSyncData... | @Test
void testProcessDataForBatch() {
// swap tmp
Serializer mock = Mockito.mock(Serializer.class);
when(applicationContext.getBean(Serializer.class)).thenReturn(mock);
// single instance => batch instances => batch instances => single instance
// single
Cli... |
Mono<ResponseEntity<Void>> delete(UUID id) {
return client.delete()
.uri(uriBuilder -> uriBuilder.path("/posts/{id}").build(id))
.exchangeToMono(response -> {
if (response.statusCode().equals(HttpStatus.NO_CONTENT)) {
return response.to... | @SneakyThrows
@Test
public void testDeletePostById() {
var id = UUID.randomUUID();
stubFor(delete("/posts/" + id)
.willReturn(
aResponse()
.withStatus(204)
)
);
postClient.delete(id)
... |
public MultiMap<Value, T, List<T>> get(final KeyDefinition keyDefinition) {
return tree.get(keyDefinition);
} | @Test
void testRetract() throws Exception {
toni.uuidKey.retract();
assertThat(map.get(UUIDKey.UNIQUE_UUID).keySet()).containsExactlyInAnyOrder(eder.uuidKey.getSingleValue(), michael.uuidKey.getSingleValue());
MultiMap<Value, Person, List<Person>> nameMap = map.get(KeyDefinition.ne... |
static int readDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
// copy all the bytes that return immediately, stopping at the first
// read that doesn't return a full buffer.
int nextReadLength = Math.min(buf.remaining(), temp.length);
int totalBytesRead = 0;
int bytesR... | @Test
public void testDirectRead() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocateDirect(20);
MockInputStream stream = new MockInputStream();
int len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, TEMP.get());
Assert.assertEquals(10, len);
Assert.assertEquals... |
@Override
public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return leftJoin(otherStream, toValueJoinerWi... | @Test
public void shouldNotAllowNullTableOnTableLeftJoinWithJoined() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.leftJoin(null, MockValueJoiner.TOSTRING_JOINER, Joined.as("name")));
assertThat(exception.getMessage(), equ... |
@Override
public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext,
final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException {
if (1 == queryResults.size() && !isNeedAggregateRewri... | @Test
void assertBuildGroupByMemoryMergedResultWithAggregationOnlyWithOracleLimit() throws SQLException {
final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "Oracle"));
final ShardingSphereDatabase database = mock(ShardingSphereData... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
final Region region = regionService.lookup(file);
try {
if(containerService.isContainer(f... | @Test
public void testFind() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final String name = new AlphanumericRandomStringService().random();
final Path test = new ... |
public boolean hasReadPermissionForWholeCollection(final Subject subject,
final String collection) {
return readPermissionForCollection(collection)
.map(rp -> rp.equals(DbEntity.ALL_ALLOWED) || subject.isPermitted(rp + ":*"))
... | @Test
void hasReadPermissionForWholeCollectionReturnsTrueWhenSubjectHasPermission() {
doReturn(Optional.of(
new DbEntityCatalogEntry("streams", "title", StreamImpl.class, "streams:read"))
).when(catalog)
.getByCollectionName("streams");
doReturn(true).when(su... |
@VisibleForTesting
static void validateFips(final KsqlConfig config, final KsqlRestConfig restConfig) {
if (config.getBoolean(ConfluentConfigs.ENABLE_FIPS_CONFIG)) {
final FipsValidator fipsValidator = ConfluentConfigs.buildFipsValidator();
// validate cipher suites and TLS version
validateCiph... | @Test
public void shouldFailOnInvalidProxyListenerProtocols() {
// Given:
final KsqlConfig config = configWith(ImmutableMap.of(
ConfluentConfigs.ENABLE_FIPS_CONFIG, true,
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_SSL.name
));
final KsqlRestConfig restConfig = ... |
@Override
public List<Column> getPartitionColumns() {
List<Column> partitionColumns = new ArrayList<>();
if (!partColumnNames.isEmpty()) {
partitionColumns = partColumnNames.stream().map(this::getColumn)
.collect(Collectors.toList());
}
return partitio... | @Test
public void testPartitionKeys(@Mocked FileStoreTable paimonNativeTable) {
RowType rowType =
RowType.builder().field("a", DataTypes.INT()).field("b", DataTypes.INT()).field("c", DataTypes.INT())
.build();
List<DataField> fields = rowType.getFields();
... |
public static boolean checkArpMode(String arpMode) {
if (isNullOrEmpty(arpMode)) {
return false;
} else {
return arpMode.equals(PROXY_MODE) || arpMode.equals(BROADCAST_MODE);
}
} | @Test
public void testCheckArpMode() {
assertFalse(checkArpMode(null));
assertTrue(checkArpMode("proxy"));
assertTrue(checkArpMode("broadcast"));
} |
@Override
public String toString() {
return new StringJoiner(", ", RuleDescriptionSectionDto.class.getSimpleName() + "[", "]")
.add("uuid='" + uuid + "'")
.add("key='" + key + "'")
.add("content='" + content + "'")
.add("context='" + context + "'")
.toString();
} | @Test
void testToString() {
assertThat("RuleDescriptionSectionDto[uuid='uuid', key='key', content='desc', " +
"context='RuleDescriptionSectionContextDto[key='key', displayName='displayName']']")
.isEqualTo(SECTION.toString());
} |
@Override
public IndexedFieldProvider<Class<?>> getIndexedFieldProvider() {
return entityType -> {
IndexDescriptor indexDescriptor = getIndexDescriptor(entityType);
if (indexDescriptor == null) {
return CLASS_NO_INDEXING;
}
return new SearchFieldIndexingMetadata... | @Test
public void testRecognizeStoredField() {
assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isProjectable(new String[]{"description"})).isTrue();
assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isSortable(new String[]{"description"})).isFalse();
} |
public static ValueReference createParameter(String value) {
return ValueReference.builder()
.valueType(ValueType.PARAMETER)
.value(value)
.build();
} | @Test
public void serializeParameter() throws IOException {
assertJsonEqualsNonStrict(objectMapper.writeValueAsString(ValueReference.createParameter("Test")), "{\"@type\":\"parameter\",\"@value\":\"Test\"}");
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
Long typeDefineLength = typeDefine.getLength();
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.get... | @Test
public void testConvertTimestamp() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("datetime")
.dataType("datetime")
.build();
Column colum... |
public Schema getSchema() {
return context.getSchema();
} | @Test
public void testMapSchema() {
ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(MapPrimitive.getDescriptor());
Schema schema = schemaProvider.getSchema();
assertEquals(MAP_PRIMITIVE_SCHEMA, schema);
} |
@Override
public void checkDone() throws IllegalStateException {
if (range.getFrom() == range.getTo()) {
return;
}
checkState(
lastAttemptedOffset != null,
"Last attempted offset should not be null. No work was claimed in non-empty range %s.",
range);
checkState(
... | @Test
public void testDoneBeforeClaim() throws Exception {
expected.expectMessage(
"Last attempted offset should not be null. No work was claimed in non-empty range [100, 200)");
OffsetRangeTracker tracker = new OffsetRangeTracker(new OffsetRange(100, 200));
tracker.checkDone();
} |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testIn() {
assertThat(in("s", 7, 8, 9).literals()).hasSize(3);
assertThat(in("s", 7, 8.1, Long.MAX_VALUE).literals()).hasSize(3);
assertThat(in("s", "abc", "abd", "abc").literals()).hasSize(3);
assertThat(in("s").literals()).isEmpty();
assertThat(in("s", 5).literals()).hasSize(1)... |
@Override
public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
LogicalOlapScanOperator logicalOlapScanOperator = (LogicalOlapScanOperator) input.getOp();
LogicalOlapScanOperator prunedOlapScanOperator = null;
if (logicalOlapScanOperator.getSelectedPartitionId... | @Test
public void transform1(@Mocked OlapTable olapTable, @Mocked RangePartitionInfo partitionInfo) {
FeConstants.runningUnitTest = true;
Partition part1 = new Partition(1, "p1", null, null);
Partition part2 = new Partition(2, "p2", null, null);
Partition part3 = new Partition(3, "p3... |
public static RecordBatchingStateRestoreCallback adapt(final StateRestoreCallback restoreCallback) {
Objects.requireNonNull(restoreCallback, "stateRestoreCallback must not be null");
if (restoreCallback instanceof RecordBatchingStateRestoreCallback) {
return (RecordBatchingStateRestoreCallba... | @Test
public void shouldThrowOnRestore() {
assertThrows(UnsupportedOperationException.class, () -> adapt(mock(StateRestoreCallback.class)).restore(null, null));
} |
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) {
return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs));
} | @Test
public void testGroupingKeyTypeWithRenamesInV1Table() {
PartitionSpec initialSpec = PartitionSpec.builderFor(SCHEMA).identity("data", "p1").build();
TestTables.TestTable table =
TestTables.create(tableDir, "test", SCHEMA, initialSpec, V1_FORMAT_VERSION);
table.updateSpec().addField("categor... |
@Override
public void execute(Context context) {
List<MeasureComputerWrapper> wrappers = Arrays.stream(measureComputers).map(ToMeasureWrapper.INSTANCE).toList();
validateMetrics(wrappers);
measureComputersHolder.setMeasureComputers(sortComputers(wrappers));
} | @Test
public void fail_with_ISE_when_output_metric_is_a_core_metric() {
assertThatThrownBy(() -> {
MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array(NCLOC_KEY))};
ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()),... |
@Override
public Num calculate(BarSeries series, Position position) {
if (position == null || position.getEntry() == null || position.getExit() == null) {
return series.zero();
}
Returns returns = new Returns(series, position, Returns.ReturnType.LOG);
return calculateES(r... | @Test
public void calculateWithASimplePosition() {
// if only one position in tail, VaR = ES
series = new MockBarSeries(numFunction, 100d, 104d, 90d, 100d, 95d, 105d);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series));
AnalysisCriter... |
@Override
public String toString() {
return "MappingRule{" +
"matcher=" + matcher +
", action=" + action +
'}';
} | @Test
public void testToStrings() {
MappingRuleAction action = new MappingRuleActions.PlaceToQueueAction(
"queue", true);
MappingRuleMatcher matcher = MappingRuleMatchers.createUserMatcher("bob");
MappingRule rule = new MappingRule(matcher, action);
assertEquals("MappingRule{matcher=" + match... |
public static boolean acceptEndpoint(String endpointUrl) {
return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING);
} | @Test
public void testAcceptEndpoint() {
AsyncTestSpecification specification = new AsyncTestSpecification();
NATSMessageConsumptionTask task = new NATSMessageConsumptionTask(specification);
assertTrue(NATSMessageConsumptionTask.acceptEndpoint("nats://localhost:4222/testTopic"));
assertTrue... |
ProducerListeners listeners() {
return new ProducerListeners(eventListeners.toArray(new HollowProducerEventListener[0]));
} | @Test
public void testAddDuringCycle() {
ProducerListenerSupport ls = new ProducerListenerSupport();
class SecondCycleListener implements CycleListener {
int cycleStart;
int cycleComplete;
@Override public void onCycleSkip(CycleSkipReason reason) {
}... |
public static <T> List<T>
sub(List<T> list, int start, int end) {
return sub(list, start, end, 1);
} | @Test
public void subTest() {
final List<Integer> of = ListUtil.of(1, 2, 3, 4);
final List<Integer> sub = ListUtil.sub(of, 2, 4);
sub.remove(0);
// 对子列表操作不影响原列表
assertEquals(4, of.size());
assertEquals(1, sub.size());
} |
@Override
public Response removeFromClusterNodeLabels(Set<String> oldNodeLabels,
HttpServletRequest hsr) throws Exception {
if (CollectionUtils.isEmpty(oldNodeLabels)) {
routerMetrics.incrRemoveFromClusterNodeLabelsFailedRetrieved();
RouterAuditLogger.logFailure(getUser().getShortUserName(), RE... | @Test
public void testRemoveFromClusterNodeLabels2() throws Exception {
Set<String> oldNodeLabels = Sets.newHashSet();
oldNodeLabels.add("A0");
Response response = interceptor.removeFromClusterNodeLabels(oldNodeLabels, null);
Assert.assertNotNull(response);
Object entityObj = response.getEntity(... |
public static LocalDateTime of(Instant instant) {
return of(instant, ZoneId.systemDefault());
} | @Test
public void ofTest() {
final String dateStr = "2020-01-23T12:23:56";
final DateTime dt = DateUtil.parse(dateStr);
LocalDateTime of = LocalDateTimeUtil.of(dt);
assertNotNull(of);
assertEquals(dateStr, of.toString());
// 不加Z是标准当地时间,与UTC时间不同
of = LocalDateTimeUtil.ofUTC(dt.getTime());
assertNotEqu... |
public static List<Group> enumerateFrom(Group root) {
List<Group> leaves = new ArrayList<>();
visitNode(root, leaves);
return leaves;
} | @Test
void singleLeafIsEnumeratedInNestedCase() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario", dummyDistribution());
child.addSubGroup(new Group(2, "toad"));
g.addSubGroup(child);
List<Group> leaves = LeafGro... |
@Override
public boolean isSigned(final int column) {
Preconditions.checkArgument(1 == column);
return true;
} | @Test
void assertIsSigned() throws SQLException {
assertTrue(actualMetaData.isSigned(1));
} |
@SuppressWarnings("unchecked")
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
//check to see if the window size config is set and the window size is already set from the constructor
final Long configWindowSize;
if (configs.get(StreamsConfig.WINDOW_SI... | @Test
public void shouldThrowConfigExceptionWhenInvalidWindowedInnerClassDeserialiserSupplied() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class");
assertThrows(ConfigException.class, () -> timeWindowedDeserializer.configure(props, false));
} |
public static Counter totalCommentCounter(MeterRegistry registry, String name) {
return counter(registry, name, Tag.of(SCENE, TOTAL_COMMENT_SCENE));
} | @Test
void totalCommentCounter() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
MeterUtils.totalCommentCounter(meterRegistry, "content.halo.run.posts.fake-post")
.increment(3);
RequiredSearch requiredSearch = meterRegistry.get("content.halo.run.posts.fake-post");
... |
@Override
public Map<Consumer, List<Range>> getConsumerKeyHashRanges() {
Map<Consumer, List<Range>> result = new LinkedHashMap<>();
rwLock.readLock().lock();
try {
int start = 0;
for (Map.Entry<Integer, List<Consumer>> entry: hashRing.entrySet()) {
for... | @Test
public void testGetConsumerKeyHashRanges() throws BrokerServiceException.ConsumerAssignException {
ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(3);
List<String> consumerName = Arrays.asList("consumer1", "consumer2", "consumer3");
... |
public Status upload(String localFilePath, String remoteFilePath) {
// Preconditions.checkArgument(remoteFilePath.startsWith(location), remoteFilePath);
// get md5usm of local file
File file = new File(localFilePath);
String md5sum;
try {
md5sum = DigestUtils.md5Hex(n... | @Test
public void testUpload() {
new Expectations() {
{
storage.upload(anyString, anyString);
minTimes = 0;
result = Status.OK;
storage.rename(anyString, anyString);
minTimes = 0;
result = Status.OK;... |
public T getResult() {
return result;
} | @Test
public void testWeb3Sha3() throws IOException {
buildResponse(
"{\n"
+ " \"id\":64,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec... |
@Override
public String render(String text) {
if (StringUtils.isBlank(text)) {
return "";
}
if (regex.isEmpty() || link.isEmpty()) {
Comment comment = new Comment();
comment.escapeAndAdd(text);
return comment.render();
}
try {
... | @Test
public void shouldUseLinkFromConfigurationRegardlessOfItsValidity() throws Exception {
String link = "aaa${ID}";
String regex = "\\d+";
trackingTool = new DefaultCommentRenderer(link, regex);
String result = trackingTool.render("111: checkin message");
assertThat(resul... |
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + urn.hashCode();
return result;
} | @Test
public void hashcode_fail_withDiffURN() {
ScheduledTaskHandler handlerA = ScheduledTaskHandlerImpl.of(1, "MyScheduler", "MyTask");
String myTaskURN = handlerA.toUrn();
ScheduledTaskHandler handlerB = ScheduledTaskHandlerImpl.of(1, "MyScheduler", "MyTask2");
String myTask2URN =... |
@Override
public void run() {
Date now = new Date();
LOG.info("Application cleaner run at time {}", now);
FederationStateStoreFacade facade = getGPGContext().getStateStoreFacade();
try {
// Get the candidate list from StateStore before calling router
Set<ApplicationId> allStateStoreApps =... | @Test
public void testFederationStateStoreAppsCleanUp() throws YarnException {
// Set first app to be still known by Router
ApplicationId appId = appIds.get(0);
routerAppIds.add(appId);
// Another random app not in stateStore known by Router
appId = ApplicationId.newInstance(100, 200);
router... |
@Override
protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException {
String defaultErrorMessage = HttpStatus.getMessage(code);
String errorPage = replaceHtml(code, defaultErrorMessage);
writer.write(errorPage);... | @Test
public void shouldWriteErrorPageFor404WithMessage() throws Exception {
errorHandler.writeErrorPage(request, writer, 404, null, false);
verify(writer).write(captor.capture());
String fileContents = captor.getValue();
assertThat(fileContents, containsString("<h1>404</h1>"));
... |
@Override
public void check(final String databaseName, final EncryptRuleConfiguration ruleConfig, final Map<String, DataSource> dataSourceMap, final Collection<ShardingSphereRule> builtRules) {
checkEncryptors(ruleConfig.getEncryptors());
checkTables(databaseName, ruleConfig.getTables(), ruleConfig.... | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void assertCheckWhenConfigInvalidAssistColumn() {
EncryptRuleConfiguration config = createInvalidAssistColumnConfiguration();
RuleConfigurationChecker checker = OrderedSPILoader.getServicesByClass(RuleConfigurationChecker.class, Collections.sing... |
@Bean
@ConditionalOnMissingBean(PolarisDataChangedInit.class)
public DataChangedInit polarisDataChangedInit(final PolarisProperties polarisProperties, final ConfigFileService configFileService) {
return new PolarisDataChangedInit(polarisProperties, configFileService);
} | @Test
public void testPolarisDataInit() {
PolarisSyncConfiguration polarisListener = new PolarisSyncConfiguration();
PolarisProperties polarisProperties = mock(PolarisProperties.class);
ConfigFileService polarisConfigFileService = mock(ConfigFileService.class);
assertNotNull(polarisL... |
public Properties apply(final Properties properties) {
if (properties == null) {
throw new IllegalArgumentException("properties must not be null");
} else {
if (properties.isEmpty()) {
return new Properties();
} else {
final Properties filtered = new Properties();
for (... | @Test
public void filtersNothingByDefault() {
// Given
Properties anyProperties = System.getProperties();
Filter f = new Filter();
// When
Properties filtered = f.apply(anyProperties);
// Then
assertEquals(anyProperties, filtered);
assertEquals(anyProperties.size(), filtered.size());... |
public KsqlGenericRecord build(
final List<ColumnName> columnNames,
final List<Expression> expressions,
final LogicalSchema schema,
final DataSourceType dataSourceType
) {
final List<ColumnName> columns = columnNames.isEmpty()
? implicitColumns(schema)
: columnNames;
i... | @Test
public void shouldAcceptNullsForAnyColumn() {
// Given:
final LogicalSchema schema = LogicalSchema.builder()
.keyColumn(KEY, SqlTypes.STRING)
.valueColumn(COL0, SqlTypes.BIGINT)
.build();
final List<ColumnName> names = ImmutableList.of(KEY, COL0);
// When:
final Ksql... |
@Override
public void write(Object object) throws IOException {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
preventMemoryLeak();
} | @Test
public void resetsObjectOutputStreamAccordingToGivenResetFrequency() throws IOException {
// given
ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
String object = "foo";
// when
objectWriter.write(object);
objectWriter.write(ob... |
public TopicConfigSerializeWrapper getAllTopicConfig(final String addr,
long timeoutMillis) throws RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCod... | @Test
public void assertGetAllTopicConfig() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
TopicConfigSerializeWrapper responseBody = new TopicConfigSerializeWrapper();
responseBody.getTopicConfigTable().put("key", new TopicConfig());
setRespons... |
public void ready() {
sync.releaseShared(UNUSED);
} | @Test
public void testStartingGunNoInterruptions() throws InterruptedException {
StartingGun sg = new StartingGun();
Thread[] threads = startWaitingThreads(sg);
Thread.sleep(PAUSE);
allThreadsAlive(threads);
sg.ready();
allThreadsDead(threads);
} |
public synchronized void add(String topic, long nowMs) {
Objects.requireNonNull(topic, "topic cannot be null");
if (topics.put(topic, nowMs + metadataIdleMs) == null) {
newTopics.add(topic);
requestUpdateForNewTopics();
}
} | @Test
public void testTimeToNextUpdateOverwriteBackoff() {
long now = 10000;
// New topic added to fetch set and update requested. It should allow immediate update.
metadata.updateWithCurrentRequestVersion(responseWithCurrentTopics(), false, now);
metadata.add("new-topic", now);
... |
public static boolean isValidPrivateKey(String privateKey) {
String cleanPrivateKey = Numeric.cleanHexPrefix(privateKey);
return cleanPrivateKey.length() == PRIVATE_KEY_LENGTH_IN_HEX;
} | @Test
public void testIsValidPrivateKey() {
assertTrue(isValidPrivateKey(SampleKeys.PRIVATE_KEY_STRING));
assertTrue(isValidPrivateKey(Numeric.prependHexPrefix(SampleKeys.PRIVATE_KEY_STRING)));
assertFalse(isValidPrivateKey(""));
assertFalse(isValidPrivateKey(SampleKeys.PRIVATE_KEY_... |
public static String createErrorMessage(HttpException exception) {
String json = tryParseAsJsonError(exception.content());
if (json != null) {
return json;
}
String msg = "HTTP code " + exception.code();
if (isHtml(exception.content())) {
return msg;
}
return msg + ": " + Strin... | @Test
public void createErrorMessage_whenLongContent_shouldCreateErrorMsg() {
String content = StringUtils.repeat("mystring", 1000);
assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).hasSize(15 + 128);
} |
public static TopicMessageType getMessageType(SendMessageRequestHeader requestHeader) {
Map<String, String> properties = MessageDecoder.string2messageProperties(requestHeader.getProperties());
String traFlag = properties.get(MessageConst.PROPERTY_TRANSACTION_PREPARED);
TopicMessageType topicMess... | @Test
public void testGetMessageTypeWithEmptyProperties() {
TopicMessageType result = BrokerMetricsManager.getMessageType(new SendMessageRequestHeader());
assertThat(TopicMessageType.NORMAL).isEqualTo(result);
} |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void parseDingTalkTest() {
final String uaString = "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/18A373 AliApp(DingTalk/5.1.33) com.laiwang.DingTalk/13976299 Channel/201200 language/zh-Hans-CN WK";
final UserAgent ua = UserAgentUtil.parse(uaStr... |
private Top() {
// do not instantiate
} | @Test
@Category(NeedsRunner.class)
@SuppressWarnings("unchecked")
public void testTop() {
PCollection<String> input =
p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder(StringUtf8Coder.of()));
PCollection<List<String>> top1 = input.apply(Top.of(1, new OrderByLength()));
PCollection<List<S... |
public Sample readSample() {
Sample out = lastSampleRead;
lastSampleRead = nextSample();
return out;
} | @Test
public void testReadSample() {
try (CsvSampleReader reader = new CsvSampleReader(tempCsv, metadata)) {
for (long i = 0; i < NR_ROWS; i++) {
Sample expected = new SampleBuilder(metadata).add(i)
.add("a" + i).build();
assertThat(reader.... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithMissingAndExtraElements() {
expectFailureWhenTestingThat(asList(1, 2, 3)).containsExactly(1, 2, 4);
assertFailureValue("missing (1)", "4");
assertFailureValue("unexpected (1)", "3");
} |
public static int getPackageIdentifier(int resId) {
return (resId >>> 24);
} | @Test
public void testGetPackageIdentifier() {
assertThat(ResourceIds.getPackageIdentifier(0x01000000)).isEqualTo(0x01);
assertThat(ResourceIds.getPackageIdentifier(0x7F000000)).isEqualTo(0x7F);
} |
@SuppressWarnings("unchecked")
@Override
public void punctuate(final ProcessorNode<?, ?, ?, ?> node,
final long timestamp,
final PunctuationType type,
final Punctuator punctuator) {
if (processorContext.currentNode() != null) ... | @Test
public void punctuateShouldThrowStreamsExceptionWhenProcessingExceptionHandlerRepliesWithFail() {
when(stateManager.taskId()).thenReturn(taskId);
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
task = createStatelessTask(createConfig(
AT_LEAST_ONCE,
"... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeCreateSourceTableCorrectly() {
final String output = anon.anonymize(
"CREATE SOURCE TABLE my_table (profileId VARCHAR, latitude DOUBLE, longitude DOUBLE)\n"
+ "WITH (kafka_topic='locations', value_format='json');");
Approvals.verify(output);
} |
public Set<Map.Entry<Identifier, UntypedMetric>> entrySet() {
return values.entrySet();
} | @Test
final void testEntrySet() {
assertEquals(0, bucket.entrySet().size());
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle_" + i, null), AssumedType.GAUGE));
}
assertEquals(4, bucket.entrySet().size());
for (int i = ... |
public static CallRoutingTable fromTsv(final Reader inputReader) throws IOException {
try (final BufferedReader reader = new BufferedReader(inputReader)) {
// use maps to silently dedupe CidrBlocks
Map<CidrBlock.IpV4CidrBlock, List<String>> ipv4Map = new HashMap<>();
Map<CidrBlock.IpV6CidrBlock, L... | @Test
public void testParserSuccess() throws IOException {
var input =
"""
192.1.12.0/24 datacenter-1 datacenter-2 datacenter-3
193.123.123.0/24 datacenter-1 datacenter-2
1.123.123.0/24 datacenter-1
2001:db8:b0aa::/48 datacenter-1
2001:db8:b0ab::/48 d... |
@Bean
@ConfigurationProperties(prefix = "shenyu.httpclient")
public HttpClientProperties httpClientProperties() {
return new HttpClientProperties();
} | @Test
public void testHttpClientProperties() {
applicationContextRunner
.withPropertyValues(
"debug=true",
"shenyu.httpclient.connectTimeout=3",
"shenyu.httpclient.responseTimeout=0",
"shenyu.http... |
public static NamenodeRole convert(NamenodeRoleProto role) {
switch (role) {
case NAMENODE:
return NamenodeRole.NAMENODE;
case BACKUP:
return NamenodeRole.BACKUP;
case CHECKPOINT:
return NamenodeRole.CHECKPOINT;
}
return null;
} | @Test
public void testConvertNamenodeRole() {
assertEquals(NamenodeRoleProto.BACKUP,
PBHelper.convert(NamenodeRole.BACKUP));
assertEquals(NamenodeRoleProto.CHECKPOINT,
PBHelper.convert(NamenodeRole.CHECKPOINT));
assertEquals(NamenodeRoleProto.NAMENODE,
PBHelper.convert(NamenodeRole... |
@Override
public String getDisplayName() {
return CaseInsensitiveString.str(getName());
} | @Test
void shouldReturnUpstreamPipelineNameAsDisplayNameIfMaterialNameIsNotDefined() throws Exception {
DependencyMaterial material = new DependencyMaterial(new CaseInsensitiveString("upstream"), new CaseInsensitiveString("first"));
assertThat(material.getDisplayName()).isEqualTo("upstream");
} |
public void updateLabel(final String instanceId, final Collection<String> labels) {
if (instance.getMetaData().getId().equals(instanceId)) {
instance.getLabels().clear();
instance.getLabels().addAll(labels);
}
for (ComputeNodeInstance each : allClusterInstances) {
... | @Test
void assertUpdateLabel() {
InstanceMetaData instanceMetaData = mock(InstanceMetaData.class);
when(instanceMetaData.getId()).thenReturn("foo_instance_id");
ComputeNodeInstanceContext context = new ComputeNodeInstanceContext(
new ComputeNodeInstance(instanceMetaData), moc... |
public static String getBaseUrl() {
try {
var requestAttrs = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return getBaseUrl(requestAttrs.getRequest());
} catch (IllegalStateException e) {
// method is called outside of web request contex... | @Test
public void testWithXForwardedHostCommaSeparated() throws Exception {
// basic request
doReturn("http").when(request).getScheme();
doReturn("localhost").when(request).getServerName();
doReturn(8080).when(request).getServerPort();
doReturn("/").when(request).getContextPa... |
@VisibleForTesting
RoleDO validateRoleForUpdate(Long id) {
RoleDO role = roleMapper.selectById(id);
if (role == null) {
throw exception(ROLE_NOT_EXISTS);
}
// 内置角色,不允许删除
if (RoleTypeEnum.SYSTEM.getType().equals(role.getType())) {
throw exception(ROLE_C... | @Test
public void testValidateUpdateRole_success() {
RoleDO roleDO = randomPojo(RoleDO.class);
roleMapper.insert(roleDO);
// 准备参数
Long id = roleDO.getId();
// 调用,无异常
roleService.validateRoleForUpdate(id);
} |
AwsCredentials credentials() {
if (!StringUtil.isNullOrEmptyAfterTrim(awsConfig.getAccessKey())) {
return AwsCredentials.builder()
.setAccessKey(awsConfig.getAccessKey())
.setSecretKey(awsConfig.getSecretKey())
.build();
}
if (!StringUt... | @Test(expected = InvalidConfigurationException.class)
public void credentialsEcsException() {
// given
AwsConfig awsConfig = AwsConfig.builder().build();
given(awsMetadataApi.credentialsEcs()).willThrow(new RuntimeException("Error fetching credentials"));
given(environment.isRunningO... |
public static <S> S load(Class<S> service, ClassLoader loader) throws EnhancedServiceNotFoundException {
return InnerEnhancedServiceLoader.getServiceLoader(service).load(loader, true);
} | @Test
public void classCastExceptionTest() {
Assertions.assertThrows(EnhancedServiceNotFoundException.class, () -> {
Hello1 load = EnhancedServiceLoader.load(Hello1.class);
});
} |
Mono<ImmutableMap<String, String>> resolve(List<SchemaReference> refs) {
return resolveReferences(refs, new Resolving(ImmutableMap.of(), ImmutableSet.of()))
.map(Resolving::resolved);
} | @Test
void returnsEmptyMapOnEmptyInputs() {
StepVerifier.create(schemaReferencesResolver.resolve(null))
.assertNext(map -> Assertions.assertThat(map).isEmpty())
.verifyComplete();
StepVerifier.create(schemaReferencesResolver.resolve(List.of()))
.assertNext(map -> Assertions.assertThat... |
public static Range<Comparable<?>> safeClosed(final Comparable<?> lowerEndpoint, final Comparable<?> upperEndpoint) {
try {
return Range.closed(lowerEndpoint, upperEndpoint);
} catch (final ClassCastException ex) {
Optional<Class<?>> clazz = getTargetNumericType(Arrays.asList(low... | @Test
void assertSafeClosedForInteger() {
Range<Comparable<?>> range = SafeNumberOperationUtils.safeClosed(12, 500);
assertThat(range.lowerEndpoint(), is(12));
assertThat(range.upperEndpoint(), is(500));
} |
public SqlConfig setStatementTimeoutMillis(long statementTimeoutMillis) {
checkNotNegative(statementTimeoutMillis, "Timeout cannot be negative");
this.statementTimeoutMillis = statementTimeoutMillis;
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testQueryTimeoutNegative() {
new SqlConfig().setStatementTimeoutMillis(-1L);
} |
@Override
public void smoke() {
tobacco.smoke(this);
} | @Test
void testSmokeEveryThing() {
List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(),
new RivendellTobacco(),
new SecondBreakfastTobacco()
);
// Verify if the sorceress is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final var advancedSorceress = n... |
@Override
public BlameAlgorithmEnum getBlameAlgorithm(int availableProcessors, int numberOfFiles) {
BlameAlgorithmEnum forcedStrategy = configuration.get(PROP_SONAR_SCM_USE_BLAME_ALGORITHM)
.map(BlameAlgorithmEnum::valueOf)
.orElse(null);
if (forcedStrategy != null) {
return forcedStrategy;... | @Test
public void useRepositoryBlame_whenFileBlamePropsDisableOrUnspecified_shouldEnableRepoBlame() {
when(configuration.get(DefaultBlameStrategy.PROP_SONAR_SCM_USE_BLAME_ALGORITHM)).thenReturn(Optional.of(GIT_NATIVE_BLAME.name()));
assertThat(underTest.getBlameAlgorithm(1, 10000)).isEqualTo(GIT_NATIVE_BLAME... |
public long scan(
final UnsafeBuffer termBuffer,
final long rebuildPosition,
final long hwmPosition,
final long nowNs,
final int termLengthMask,
final int positionBitsToShift,
final int initialTermId)
{
boolean lossFound = false;
int rebuildOff... | @Test
void shouldHandleLongerRetryDelay()
{
lossDetector = getLossHandlerWithLongRetry();
final long rebuildPosition = ACTIVE_TERM_POSITION;
final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);
insertDataFrame(offsetOfMessage(0));
insertDataFrame... |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
... | @Test
public void testInstallIntent() {
List<Intent> intentsToUninstall = Lists.newArrayList();
List<Intent> intentsToInstall = createFlowObjectiveIntents();
IntentData toUninstall = null;
IntentData toInstall = new IntentData(createP2PIntent(),
... |
public static Set<Set<LogicalVertex>> computePipelinedRegions(
final Iterable<? extends LogicalVertex> topologicallySortedVertices) {
final Map<LogicalVertex, Set<LogicalVertex>> vertexToRegion =
PipelinedRegionComputeUtil.buildRawRegions(
topologicallySorted... | @Test
void testDiamondWithMixedPipelinedAndBlockingEdges() {
JobVertex v1 = new JobVertex("v1");
JobVertex v2 = new JobVertex("v2");
JobVertex v3 = new JobVertex("v3");
JobVertex v4 = new JobVertex("v4");
v2.connectNewDataSetAsInput(
v1, DistributionPattern.P... |
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors(
ReconnaissanceReport reconnaissanceReport) {
return tsunamiPlugins.entrySet().stream()
.filter(entry -> isVulnDetector(entry.getKey()))
.map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc... | @Test
public void getVulnDetectors_whenSoftwareFilterHasNoMatchingService_returnsEmpty() {
NetworkService wordPressService =
NetworkService.newBuilder()
.setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 443))
.setTransportProtocol(TransportProtocol.TCP)
.... |
@SuppressWarnings("unchecked")
public T getValue() {
final T value = (T) FROM_STRING.get(getConverterClass()).apply(JiveGlobals.getProperty(key), this);
if (value == null || (Collection.class.isAssignableFrom(value.getClass()) && ((Collection) value).isEmpty())) {
return defaultValue;
... | @Test
public void willCreateAListOfCommaWhitespaceSeparatedString2() {
final String key = "another whitespace csv list property";
final SystemProperty<List<String>> property = SystemProperty.Builder.ofType(List.class)
.setKey(key)
.setDefaultValue(Collections.emptyList())
... |
public RunResponse restart(RunRequest runRequest) {
RunResponse runResponse = restartRecursively(runRequest);
if (runResponse.getStatus() == RunResponse.Status.NON_TERMINAL_ERROR) {
LOG.error(
"workflow instance {} does not support restart action as it is in a non-terminal status [{}]",
... | @Test
public void testRestart() {
WorkflowInstance wfInstance = new WorkflowInstance();
wfInstance.setInitiator(new ManualInitiator());
wfInstance.setStatus(WorkflowInstance.Status.SUCCEEDED);
wfInstance.setWorkflowInstanceId(10L);
wfInstance.setWorkflowRunId(1L);
wfInstance.setWorkflowId("tes... |
@Override
public AppResponse process(Flow flow, RequestAccountRequest request) {
digidClient.remoteLog("3");
Map<String, Object> result = digidClient.createRegistration(request);
if (result.get(lowerUnderscore(STATUS)).equals("NOK")) {
if (result.get(ERROR) != null) {
... | @Test
void processNOKTest(){
RequestAccountRequest requestAccountRequest = createRequest();
String expectedErrorMsg = "error";
when(digidClientMock.createRegistration(requestAccountRequest)).thenReturn(Map.of(
lowerUnderscore(STATUS), "NOK",
lowerUnderscore(ERROR), e... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestPurgeSegments()
{
internalEncodeLogHeader(buffer, 0, 1000, 1000, () -> 500_000_000L);
final PurgeSegmentsRequestEncoder requestEncoder = new PurgeSegmentsRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder)
.co... |
@Override
public void createTable(Table table) {
validateTableType(table);
// first assert the table name is unique
if (tables.containsKey(table.getName())) {
throw new IllegalArgumentException("Duplicate table name: " + table.getName());
}
// invoke the provider's create
providers.get... | @Test
public void testCreateTable() throws Exception {
Table table = mockTable("person");
store.createTable(table);
Table actualTable = store.getTables().get("person");
assertEquals(table, actualTable);
} |
public static boolean containsDistinctType(List<Type> types)
{
LinkedList<Type> allTypes = new LinkedList<>(types);
while (!allTypes.isEmpty()) {
Type type = allTypes.removeLast();
if (isDistinctType(type)) {
return true;
}
allTypes.add... | @Test
public void testContainsDistinctType()
{
QualifiedObjectName distinctTypeName = QualifiedObjectName.valueOf("test.dt.int00");
DistinctTypeInfo distinctTypeInfo = new DistinctTypeInfo(distinctTypeName, INTEGER.getTypeSignature(), Optional.empty(), false);
DistinctType distinctType =... |
public void handleIrcError(int num) {
if (IRCConstants.ERR_NICKNAMEINUSE == num) {
handleNickInUse();
}
} | @Test
public void doHandleIrcErrorNickInUse() {
when(connection.getNick()).thenReturn("nick");
endpoint.handleIrcError(IRCConstants.ERR_NICKNAMEINUSE);
verify(connection).doNick("nick-");
when(connection.getNick()).thenReturn("nick---");
// confirm doNick was not called
... |
public Optional<Long> claimNextId() {
long nextId = producerIdCounter.getAndIncrement();
if (nextId > lastProducerId()) {
return Optional.empty();
}
return Optional.of(nextId);
} | @Test
public void testClaimNextId() throws Exception {
for (int i = 0; i < 50; i++) {
ProducerIdsBlock block = new ProducerIdsBlock(0, 1, 1);
CountDownLatch latch = new CountDownLatch(1);
AtomicLong counter = new AtomicLong(0);
CompletableFuture.runAsync(() ->... |
@Override
public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) {
final LargeUploadOutputStream proxy = new LargeUploadOutputStream(file, status);
return new HttpResponseOutputStream<StorageObject>(new MemorySegementingO... | @Test
public void testWriteZeroLength() throws Exception {
final SwiftRegionService regionService = new SwiftRegionService(session);
final SwiftLargeUploadWriteFeature feature = new SwiftLargeUploadWriteFeature(session, regionService,
new SwiftSegmentService(session, ".segments-test/... |
public static String getString(long date, String format) {
Date d = new Date(date);
return getString(d, format);
} | @Test
public void getString_longSignature() {
String expectedDateAsString = "16/03/2020";
long expectedDate = 1584371565000L;
String format = "dd/MM/yyyy";
assertEquals(expectedDateAsString, DateUtils.getString(expectedDate, format));
} |
public static Sensor skippedIdempotentUpdatesSensor(final String threadId,
final String taskId,
final String processorNodeId,
final StreamsMetricsImpl streamsMetrics) {
return throughputSensor(
threadId,
taskId,
processorNodeId,
... | @Test
public void shouldGetIdempotentUpdateSkipSensor() {
final String metricNamePrefix = "idempotent-update-skip";
final String descriptionOfCount = "The total number of skipped idempotent updates";
final String descriptionOfRate = "The average number of skipped idempotent updates per secon... |
@Override
@Nonnull
public Member getLocalMember() {
throw new UnsupportedOperationException("Client has no local member!");
} | @Test(expected = UnsupportedOperationException.class)
public void getLocalMember() {
client().getCluster().getLocalMember();
} |
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated t... | @Test
void getUnversionedProfileIncorrectGroupSendEndorsement() throws Exception {
final AciServiceIdentifier targetServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final AciServiceIdentifier authorizedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
// Expiration must be ... |
public static SqlToConnectTypeConverter sqlToConnectConverter() {
return SQL_TO_CONNECT_CONVERTER;
} | @Test
public void shouldConvertGeneralizedUnionTypeFromSqlToConnect() {
// Given:
SqlStruct sqlStruct = SqlStruct.builder()
.field("connect_union_field_0", SqlPrimitiveType.of(SqlBaseType.STRING))
.field("connect_union_field_1", SqlPrimitiveType.of(SqlBaseType.BOOLEAN))
.field("connect... |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_submit_nameUsed() {
run("submit", "-n", "fooName", testJobJarFile.toString());
assertTrueEventually(() -> assertEquals(1, hz.getJet().getJobs().size()), 5);
Job job = hz.getJet().getJobs().get(0);
assertEquals("fooName", job.getName());
} |
@Override
public AMFeedback statusUpdate(TaskAttemptID taskAttemptID,
TaskStatus taskStatus) throws IOException, InterruptedException {
org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId yarnAttemptID =
TypeConverter.toYarn(taskAttemptID);
AMFeedback feedback = new AMFeedback();
feed... | @Test
public void testSingleStatusUpdate()
throws IOException, InterruptedException {
configureMocks();
startListener(true);
listener.statusUpdate(attemptID, firstReduceStatus);
verify(ea).handle(eventCaptor.capture());
TaskAttemptStatusUpdateEvent updateEvent =
(TaskAttemptStatusU... |
public XAConnectionFactory xaConnectionFactory(XAConnectionFactory xaConnectionFactory) {
return TracingXAConnectionFactory.create(xaConnectionFactory, this);
} | @Test void xaConnectionFactory_wrapsInput() {
assertThat(jmsTracing.xaConnectionFactory(mock(XAConnectionFactory.class)))
.isInstanceOf(TracingXAConnectionFactory.class);
} |
public MaintenanceAssociation decode(ObjectNode json, CodecContext context, int mdNameLen) {
if (json == null || !json.isObject()) {
return null;
}
JsonNode maNode = json.get(MA);
String maName = nullIsIllegal(maNode.get(MA_NAME), "maName is required").asText();
Str... | @Test
public void testDecodeMa1NoTypeGiven() throws IOException {
String mdString = "{\"ma\": { \"maName\": \"ma-1\"," +
"\"component-list\": [], " +
"\"rmep-list\": [], " +
"\"maNumericId\": 1}}";
InputStream input = new ByteArrayInputStream(
... |
public static long calculate(PhysicalRel rel, ExpressionEvalContext evalContext) {
GcdCalculatorVisitor visitor = new GcdCalculatorVisitor(evalContext);
visitor.go(rel);
if (visitor.gcd == 0) {
// there's no window aggr in the rel, return the value for joins, which is already capped... | @Test
public void when_noSlidingWindowInTree_then_returnDefault() {
HazelcastTable table = partitionedTable("map", asList(field(KEY, INT), field(VALUE, INT)), 1);
List<QueryDataType> parameterTypes = asList(INT, INT);
final String sql = "SELECT * FROM TABLE(IMPOSE_ORDER((SELECT __key, this ... |
@Override
public List<String> detect(ClassLoader classLoader) {
List<File> classpathContents =
classGraph
.disableNestedJarScanning()
.addClassLoader(classLoader)
.scan(1)
.getClasspathFiles();
return classpathContents.stream().map(File::getAbsolutePath... | @Test
public void shouldNotDetectOrdinaryFiles() throws Exception {
File textFile = tmpFolder.newFile("ordinaryTextFile.txt");
ClassLoader classLoader = new URLClassLoader(new URL[] {textFile.toURI().toURL()});
ClasspathScanningResourcesDetector detector =
new ClasspathScanningResourcesDetector(ne... |
@Override
protected void init() throws ServiceException {
LOG.info("Using FileSystemAccess JARs version [{}]", VersionInfo.getVersion());
String security = getServiceConfig().get(AUTHENTICATION_TYPE, "simple").trim();
if (security.equals("kerberos")) {
String defaultName = getServer().getName();
... | @Test
@TestDir
public void serviceHadoopConf() throws Exception {
String dir = TestDirHelper.getTestDir().getAbsolutePath();
String services = StringUtils.join(",",
Arrays.asList(InstrumentationService.class.getName(),
SchedulerService.class.getName(),
FileSyste... |
@Override
public AuthenticationDataSource getAuthDataSource() {
return authenticationDataSource;
} | @Test
public void verifyHttpAuthConstructorInitializesAuthDataSourceAndDoesNotAuthenticateData() {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRemoteAddr()).thenReturn("localhost");
when(request.getRemotePort()).thenReturn(8080);
CountingAuthenticatio... |
@Bean("ScmChangedFiles")
public ScmChangedFiles provide(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
Path rootBaseDir = project.getBaseDir();
Set<ChangedFile> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDi... | @Test
public void testProviderDoesntSupport() {
when(branchConfiguration.targetBranchName()).thenReturn("target");
when(branchConfiguration.isPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenRetu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.