focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void validateToken(String token) throws AccessException {
getExecuteTokenManager().validateToken(token);
} | @Test
void testValidateToken() throws AccessException {
tokenManagerDelegate.validateToken("token");
} |
public Set<Long> findCmdIds(List<Status> statusList) throws JobDoesNotExistException {
Set<Long> set = new HashSet<>();
for (Map.Entry<Long, CmdInfo> x : mInfoMap.entrySet()) {
if (statusList.isEmpty()
|| statusList.contains(getCmdStatus(
x.getValue().getJobControlId())... | @Test
public void testFindCmdIdsForCancel() throws Exception {
long cancelId = generateMigrateCommandForStatus(Status.CANCELED);
mSearchingCriteria.add(Status.CANCELED);
Set<Long> cancelCmdIds = mCmdJobTracker.findCmdIds(mSearchingCriteria);
Assert.assertEquals(cancelCmdIds.size(), 1);
Assert.asse... |
void refreshTopicPartitions()
throws InterruptedException, ExecutionException {
List<TopicPartition> sourceTopicPartitions = findSourceTopicPartitions();
List<TopicPartition> targetTopicPartitions = findTargetTopicPartitions();
Set<TopicPartition> sourceTopicPartitionsSet = new Has... | @Test
public void testRefreshTopicPartitions() throws Exception {
MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"),
new DefaultReplicationPolicy(), new DefaultTopicFilter(), new DefaultConfigPropertyFilter());
connector.initialize(mo... |
public MutableTree<K> beginWrite() {
return new MutableTree<>(this);
} | @Test
public void reverseIterationTest() {
Random random = new Random(5743);
Persistent23Tree.MutableTree<Integer> tree = new Persistent23Tree<Integer>().beginWrite();
int[] p = genPermutation(random);
TreeSet<Integer> added = new TreeSet<>();
for (int i = 0; i < ENTRIES_TO_A... |
@Override
public void failover(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName());
} | @Test
public void testFailover() throws InterruptedException {
Collection<RedisServer> masters = connection.masters();
connection.failover(masters.iterator().next());
Thread.sleep(10000);
RedisServer newMaster = connection.masters().iterator().next();
assert... |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetPartialGenericFunction() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("partialGenericFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getSchemaFromType(genericType);
// Then:
assertThat(r... |
private RemotingCommand getConsumerConnectionList(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetConsumerConnectionListRequestHeader requestHeader =
(GetConsu... | @Test
public void testGetConsumerConnectionList() throws RemotingCommandException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_CONNECTION_LIST, null);
request.addExtField("consumerGroup", "GID-group-test");
consumerManager = mock(ConsumerManager.c... |
public Value parse(String json) {
return this.delegate.parse(json);
} | @Test
public void testParseJson() throws Exception {
final JsonParser parser = new JsonParser();
final Value msgpackValue = parser.parse("{\"col1\": 1, \"col2\": \"foo\", \"col3\": [1,2,3], \"col4\": {\"a\": 1}}");
assertTrue(msgpackValue.isMapValue());
final Map<Value, Value> map = ... |
@Override
public EdgeExplorer createEdgeExplorer(final EdgeFilter edgeFilter) {
// re-use these objects between setBaseNode calls to prevent GC
final EdgeExplorer mainExplorer = baseGraph.createEdgeExplorer(edgeFilter);
final VirtualEdgeIterator virtualEdgeIterator = new VirtualEdgeIterator(... | @Test
public void testVirtEdges() {
initGraph(g);
EdgeIterator iter = g.createEdgeExplorer().setBaseNode(0);
iter.next();
List<EdgeIteratorState> vEdges = Collections.singletonList(iter.detach(false));
VirtualEdgeIterator vi = new VirtualEdgeIterator(EdgeFilter.ALL_EDGES, vE... |
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava3RetryAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava3RetryAspectExt.canHandleReturnType(Single.class)).isTrue();
} |
@Override
public void decryptKey(EncryptionKey key) {
assert plainKey != null;
if (!(key instanceof NormalKey)) {
throw new IllegalArgumentException("NormalKey cannot not decrypt " + key.getClass().getName());
}
NormalKey normalKey = (NormalKey) key;
normalKey.set... | @Test
public void testDecryptKey() {
NormalKey newKey = (NormalKey) normalKey.generateKey();
byte[] plainKey = newKey.getPlainKey();
newKey.setPlainKey(null);
normalKey.decryptKey(newKey);
assertArrayEquals(newKey.getPlainKey(), plainKey);
} |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test(expected = SemanticException.class)
public void testShowCreateTableEmptyDb() throws SemanticException, DdlException {
ShowCreateTableStmt stmt = new ShowCreateTableStmt(new TableName("emptyDb", "testTable"),
ShowCreateTableStmt.CreateTableType.TABLE);
ShowResultSet resultSet =... |
@Override
public KStream<K, V> peek(final ForeachAction<? super K, ? super V> action) {
return peek(action, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullActionOnPeek() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.peek(null));
assertThat(exception.getMessage(), equalTo("action can't be null"));
} |
@VisibleForTesting
void validateDeptExists(Long id) {
if (id == null) {
return;
}
DeptDO dept = deptMapper.selectById(id);
if (dept == null) {
throw exception(DEPT_NOT_FOUND);
}
} | @Test
public void testValidateDeptExists_notFound() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> deptService.validateDeptExists(id), DEPT_NOT_FOUND);
} |
public static RLESparseResourceAllocation merge(ResourceCalculator resCalc,
Resource clusterResource, RLESparseResourceAllocation a,
RLESparseResourceAllocation b, RLEOperator operator, long start, long end)
throws PlanningException {
NavigableMap<Long, Resource> cumA =
a.getRangeOverlappi... | @Test
public void testMergeAdd() throws PlanningException {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResou... |
public static AbstractProtocolNegotiatorBuilderSingleton getSingleton() {
return SINGLETON;
} | @Test
void testSingletonInstance() {
AbstractProtocolNegotiatorBuilderSingleton singleton1 = ClusterProtocolNegotiatorBuilderSingleton.getSingleton();
AbstractProtocolNegotiatorBuilderSingleton singleton2 = ClusterProtocolNegotiatorBuilderSingleton.getSingleton();
assertSame(singleton1, sing... |
public Collection<Stream> getByName(String name) {
return nameToStream.get(name);
} | @Test
public void getByName() {
// make sure getByName always returns a collection
final Collection<Stream> streams = cacheService.getByName("nonexisting");
assertThat(streams).isNotNull().isEmpty();
} |
@Override
public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner) throws Exception {
response = discovery.discoverNodes();
List<Address> addresses = response.getPrivateMemberAddresses();
listenerRunner.onPossibleAddressesCollected(addresses);
return new... | @Test(expected = IllegalStateException.class)
public void testLoadAddresses_whenExceptionIsThrown() throws Exception {
ViridianAddressProvider provider = new ViridianAddressProvider(createBrokenDiscovery());
provider.loadAddresses(createListenerRunner());
} |
public String getTableName() {
return tableName;
} | @Test
public void getTableNameOutputNull() {
// Arrange
final DdlResult objectUnderTest = new DdlResult();
// Act
final String actual = objectUnderTest.getTableName();
// Assert result
Assert.assertNull(actual);
} |
@ExceptionHandler(MethodArgumentNotValidException.class)
protected ShenyuAdminResult handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) {
LOG.warn("method argument not valid", e);
BindingResult bindingResult = e.getBindingResult();
String errorMsg = bindingResult.... | @Test
public void testHandleMethodArgumentNotValidException() throws InstantiationException, IllegalAccessException, NoSuchMethodException {
BindingResult bindingResult = spy(new DirectFieldBindingResult("test", "TestClass"));
MethodParameter methodParameter = spy(new SynthesizingMethodParameter(thi... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetMapSchemaFromMapClassVariadic() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("mapType", Map.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getVarArgsSchemaFromType(type);
assertThat(schema, instanceOf(MapType.... |
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_fails_with_NPE_if_uuid_is_null() {
treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root").build());
NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap());
... |
@Override
public void updateNotice(NoticeSaveReqVO updateReqVO) {
// 校验是否存在
validateNoticeExists(updateReqVO.getId());
// 更新通知公告
NoticeDO updateObj = BeanUtils.toBean(updateReqVO, NoticeDO.class);
noticeMapper.updateById(updateObj);
} | @Test
public void testUpdateNotice_success() {
// 插入前置数据
NoticeDO dbNoticeDO = randomPojo(NoticeDO.class);
noticeMapper.insert(dbNoticeDO);
// 准备更新参数
NoticeSaveReqVO reqVO = randomPojo(NoticeSaveReqVO.class, o -> o.setId(dbNoticeDO.getId()));
// 更新
noticeSer... |
@Override
public void exportData(JsonWriter writer) throws IOException {
// version tag at the root
writer.name(THIS_VERSION);
writer.beginObject();
// clients list
writer.name(CLIENTS);
writer.beginArray();
writeClients(writer);
writer.endArray();
writer.name(GRANTS);
writer.beginArray();
wr... | @Test
public void testExportSystemScopes() throws IOException {
SystemScope scope1 = new SystemScope();
scope1.setId(1L);
scope1.setValue("scope1");
scope1.setDescription("Scope 1");
scope1.setRestricted(true);
scope1.setDefaultScope(false);
scope1.setIcon("glass");
SystemScope scope2 = new SystemScop... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> deleted = new ArrayList<Path>();
for(Path file : files.keySet()) {
boolean skip = false;
for(Path d : dele... | @Test(expected = NotfoundException.class)
public void testDeleteNotFound() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().... |
public boolean hasNextStage(final CaseInsensitiveString lastStageName) {
if (this.isEmpty()) {
return false;
}
return nextStage(lastStageName) != null;
} | @Test
public void shouldReturnFalseThePassInStageDoesNotExist() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null, completedStage(), buildingStage());
assertThat(pipelineConfig.hasNextStage(new CaseInsensitiveString("notExist")), is(false));
} |
@Override
public FSDataOutputStream create(Path f, WriteMode overwriteMode) throws IOException {
return createOutputStream(() -> originalFs.create(f, overwriteMode));
} | @Test
void testSlowOutputStreamNotClosed() throws Exception {
final LimitedConnectionsFileSystem fs =
new LimitedConnectionsFileSystem(LocalFileSystem.getSharedInstance(), 1, 0L, 1000L);
// some competing threads
final Random rnd = new Random();
final ReaderThread[] ... |
@JsonCreator
public static Duration parse(String duration) {
final Matcher matcher = DURATION_PATTERN.matcher(duration);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid duration: " + duration);
}
final long count = Long.parseLong(matcher.group(1));
... | @Test
void unableParseWrongDurationTimeUnit() {
assertThatIllegalArgumentException().isThrownBy(() -> Duration.parse("1gs"));
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testValidJoinOnClause()
{
analyze("SELECT * FROM (VALUES (2, 2)) a(x,y) JOIN (VALUES (2, 2)) b(x,y) ON TRUE");
analyze("SELECT * FROM (VALUES (2, 2)) a(x,y) JOIN (VALUES (2, 2)) b(x,y) ON 1=1");
analyze("SELECT * FROM (VALUES (2, 2)) a(x,y) JOIN (VALUES (2, 2)) b(x,y) O... |
public List<String> parse(final CharSequence line) {
return this.lineParser.parse( line.toString() );
} | @Test
public void testDoubleQuotes() {
final CsvLineParser parser = new CsvLineParser();
final String s = "a,\"\"\"b\"\"\",c";
final List<String> list = parser.parse(s);
assertThat(list).hasSize(3).containsExactly("a", "\"b\"", "c");
} |
@Override
public PageData<WidgetsBundle> findSystemWidgetsBundles(WidgetsBundleFilter widgetsBundleFilter, PageLink pageLink) {
if (widgetsBundleFilter.isFullSearch()) {
return DaoUtil.toPageData(
widgetsBundleRepository
.findSystemWidgetsBundlesFu... | @Test
public void testFindSystemWidgetsBundles() {
createSystemWidgetBundles(30, "WB_");
widgetsBundles = widgetsBundleDao.find(TenantId.SYS_TENANT_ID);
assertEquals(30, widgetsBundles.size());
// Get first page
PageLink pageLink = new PageLink(10, 0, "WB");
PageData<... |
@Description("Returns a LineString from an array of points")
@ScalarFunction("ST_LineString")
@SqlType(GEOMETRY_TYPE_NAME)
public static Slice stLineString(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input)
{
CoordinateSequence coordinates = readPointCoordinates(input, "ST_LineString", t... | @Test
public void testSTLineString()
{
// General case, 2+ points
assertFunction("ST_LineString(array[ST_Point(1,2), ST_Point(3,4)])", GEOMETRY, "LINESTRING (1 2, 3 4)");
assertFunction("ST_LineString(array[ST_Point(1,2), ST_Point(3,4), ST_Point(5, 6)])", GEOMETRY, "LINESTRING (1 2, 3 4,... |
public static int readVInt(ByteData arr, long position) {
byte b = arr.get(position++);
if(b == (byte) 0x80)
throw new RuntimeException("Attempting to read null value as int");
int value = b & 0x7F;
while ((b & 0x80) != 0) {
b = arr.get(position++);
valu... | @Test(expected = EOFException.class)
public void testReadVIntEmptyInputStream() throws IOException {
InputStream is = new ByteArrayInputStream(BYTES_EMPTY);
VarInt.readVInt(is);
} |
@Udf
public <T extends Comparable<? super T>> T arrayMax(@UdfParameter(
description = "Array of values from which to find the maximum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldFindStringMax() {
final List<String> input = Arrays.asList("foo", "food", "bar");
assertThat(udf.arrayMax(input), is("food"));
} |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateMultiStatsWhenOnlySomeAvailable() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3", "part4");
ColumnStatisticsData data1 = new ColStatsBuilder<>(Decimal.class).numNulls(1).numDVs(3)
.low(ONE).high(THREE).hll(1, 2, 3).kll(1, 2, 3).... |
static int internalEncodeLogHeader(
final MutableDirectBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final NanoClock nanoClock)
{
if (captureLength < 0 || captureLength > length || captureLength > MAX_CAPTURE_LENGTH)
{
... | @Test
void encodeLogHeaderThrowsIllegalArgumentExceptionIfCaptureLengthIsGreaterThanLength()
{
assertThrows(IllegalArgumentException.class,
() -> internalEncodeLogHeader(buffer, 0, 100, 80, () -> 0));
} |
@Operation(summary = "Get single service")
@GetMapping(value = "{id}", produces = "application/json")
@ResponseBody
public Service getById(@PathVariable("id") Long id) {
return serviceService.getServiceById(id);
} | @Test
public void getServiceById() {
Service service = new Service();
service.setName("test");
when(serviceServiceMock.getServiceById(anyLong())).thenReturn(service);
Service result = controller.getById(1L);
assertEquals("test", result.getName());
verify(serviceServ... |
@ConstantFunction(name = "concat_ws", argTypes = {VARCHAR, VARCHAR}, returnType = VARCHAR)
public static ConstantOperator concat_ws(ConstantOperator split, ConstantOperator... values) {
Preconditions.checkArgument(values.length > 0);
if (split.isNull()) {
return ConstantOperator.createNu... | @Test
public void concat_ws_with_null() {
ConstantOperator[] argWithNull = {ConstantOperator.createVarchar("star"),
ConstantOperator.createNull(Type.VARCHAR),
ConstantOperator.createVarchar("cks")};
ConstantOperator result =
ScalarOperatorFunctions.con... |
@Override
public void prepare(ExecutorDetails exec) {
this.exec = exec;
} | @Test
public void testPreferRackWithTopoExecutors() {
INimbus iNimbus = new INimbusTest();
double compPcore = 100;
double compOnHeap = 775;
double compOffHeap = 25;
int topo1NumSpouts = 1;
int topo1NumBolts = 5;
int topo1SpoutParallelism = 100;
int top... |
@VisibleForTesting
static AvroMetadata readMetadataFromFile(ResourceId fileResource) throws IOException {
String codec = null;
String schemaString = null;
byte[] syncMarker;
try (InputStream stream = Channels.newInputStream(FileSystems.open(fileResource))) {
BinaryDecoder decoder = DecoderFactor... | @Test
public void testReadSchemaString() throws Exception {
List<Bird> expected = createRandomRecords(DEFAULT_RECORD_COUNT);
String codec = DataFileConstants.NULL_CODEC;
String filename =
generateTestFile(
codec, expected, SyncBehavior.SYNC_DEFAULT, 0, AvroCoder.of(Bird.class), codec);... |
@Override
public ExportResult<CalendarContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) {
if (!exportInformation.isPresent()) {
return exportCalendars(authData, Optional.empty());
} else {
StringPaginationToken paginationToke... | @Test
public void exportEventFirstSet() throws IOException {
setUpSingleEventResponse();
// Looking at first page, with at least one page after it
ContainerResource containerResource = new IdOnlyContainerResource(CALENDAR_ID);
ExportInformation exportInformation = new ExportInformation(null, containe... |
public static VelocityEngine getEngine() {
try {
val props = new Properties();
props.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
props.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
props.setProperty("resource.loader.string.class", StringR... | @Test
public void defaultProperties() {
val engine = VelocityEngineFactory.getEngine();
assertNotNull(engine);
assertEquals("org.apache.velocity.runtime.resource.loader.StringResourceLoader",
engine.getProperty("resource.loader.string.class"));
assertEquals("org.apache.v... |
public static <Key extends Comparable, Value, ListType extends List<Value>> MultiMap<Key, Value, ListType> make(final boolean updatable,
final NewSubMapProvider<Value, ListType> newSubMapProvider) {
... | @Test
void normal() throws Exception {
assertThat(MultiMapFactory.make(false) instanceof ChangeHandledMultiMap).isFalse();
} |
public static <T> Partition<T> of(
int numPartitions,
PartitionWithSideInputsFn<? super T> partitionFn,
Requirements requirements) {
Contextful ctfFn =
Contextful.fn(
(T element, Contextful.Fn.Context c) ->
partitionFn.partitionFor(element, numPartitions, c),
... | @Test
public void testPartitionGetName() {
assertEquals("Partition", Partition.of(3, new ModFn()).getName());
} |
public static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length) {
return CRC(0x1021, 0x1D0F, data, offset, length, false, false, 0x0000);
} | @Test
public void AUG_CCITT_123456789() {
final byte[] data = "123456789".getBytes();
assertEquals(0xE5CC, CRC16.AUG_CCITT(data, 0, 9));
} |
@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 iterableContainsExactlyOutOfOrder() {
assertThat(asList(1, 2, 3, 4)).containsExactly(3, 1, 4, 2);
} |
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) {
if ( lists == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "lists", "cannot be null"));
}
final Set<Object> resultSet = new LinkedHashSet<>();
for ( final Obj... | @Test
void invokeSingleObjectInAnArray() {
final int[] testArray = new int[]{10};
FunctionTestUtil.assertResult(unionFunction.invoke(new Object[]{testArray}),
Collections.singletonList(testArray));
} |
@Override
public PageResult<FileConfigDO> getFileConfigPage(FileConfigPageReqVO pageReqVO) {
return fileConfigMapper.selectPage(pageReqVO);
} | @Test
public void testGetFileConfigPage() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setName("芋道源码")
.setStorage(FileStorageEnum.LOCAL.getStorage());
dbFileConfig.setCreateTime(LocalDateTimeUtil.parse("2020-01-23", DatePattern.NORM_DATE_PATTERN));// 等会查询到
... |
@Override
public void isEqualTo(@Nullable Object expected) {
if (sameClassMessagesWithDifferentDescriptors(actual, expected)) {
// This can happen with DynamicMessages, and it's very confusing if they both have the
// same string.
failWithoutActual(
simpleFact("Not true that messages c... | @Test
public void testMapWithDefaultKeysAndValues() throws InvalidProtocolBufferException {
Descriptor descriptor = getFieldDescriptor("o_int").getContainingType();
String defaultString = "";
int defaultInt32 = 0;
Message message = makeProtoMap(ImmutableMap.of(defaultString, 1, "foo", defaultInt32));
... |
public static SqlType fromValue(final BigDecimal value) {
// SqlDecimal does not support negative scale:
final BigDecimal decimal = value.scale() < 0
? value.setScale(0, BigDecimal.ROUND_UNNECESSARY)
: value;
/* We can't use BigDecimal.precision() directly for all cases, since it defines
... | @Test
public void shouldGetSchemaFromDecimal2_2() {
// When:
final SqlType schema = DecimalUtil.fromValue(new BigDecimal(".12"));
// Note: this behavior is different from the SQL specification, where
// we expect precision = 2, scale = 2. This difference is because we use
// BigDecimal in our imp... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final WindowRangeQuery<GenericKey, GenericRow> query = WindowR... | @Test
public void shouldReturnValueIfSessionEndsAtLowerBoundIfLowerStartBoundClosed() {
// Given:
final Range<Instant> endBounds = Range.closed(
LOWER_INSTANT,
UPPER_INSTANT
);
final Instant wstart = LOWER_INSTANT.minusMillis(1);
givenSingleSession(wstart, LOWER_INSTANT);
// When... |
@Override
public void unSubscribe(ConsumerConfig consumerConfig) {
String directUrl = consumerConfig.getDirectUrl();
notifyListeners.get(directUrl).remove(consumerConfig);
} | @Test
public void testUnSubscribe() {
ConsumerConfig<Object> consumerConfig = new ConsumerConfig<>();
String directUrl = "bolt://alipay.com";
consumerConfig.setDirectUrl(directUrl);
List<ProviderGroup> providerGroups = domainRegistry.subscribe(consumerConfig);
assertTrue(doma... |
@Override
public long getQueryCount() {
throw new UnsupportedOperationException("Queries on replicated maps are not supported.");
} | @Test(expected = UnsupportedOperationException.class)
public void testQueryCount() {
localReplicatedMapStats.getQueryCount();
} |
public SerializableFunction<T, Row> getToRowFunction() {
return toRowFunction;
} | @Test
public void testOuterOneOfProtoToRow() throws InvalidProtocolBufferException {
ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(OuterOneOf.getDescriptor());
SerializableFunction<DynamicMessage, Row> toRow = schemaProvider.getToRowFunction();
// equality doesn't work between dynamic me... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertBytes() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("BINARY")
.dataType("BINARY")
.length(1L)
.b... |
@Deprecated
@Override public void toXML(Object obj, OutputStream out) {
super.toXML(obj, out);
} | @Issue("JENKINS-8006") // Previously a null entry in an array caused NPE
@Test
public void emptyStack() {
assertEquals("<object-array><null/><null/></object-array>",
Run.XSTREAM.toXML(new Object[2]).replaceAll("[ \n\r\t]+", ""));
} |
public final DisposableServer bindNow() {
return bindNow(Duration.ofSeconds(45));
} | @Test
void testDisposeTimeoutLongOverflow() {
assertThatExceptionOfType(ArithmeticException.class)
.isThrownBy(() -> new TestServerTransport(Mono.just(EmbeddedChannel::new)).bindNow().disposeNow(Duration.ofMillis(Long.MAX_VALUE)));
} |
public List<PhotoAlbum> split(int numberOfNewAlbums) {
return IntStream.range(1, numberOfNewAlbums + 1)
.mapToObj(
i ->
new PhotoAlbum(
String.format("%s-pt%d", id, i),
String.format("%s (%d/%d)", id, i, numberOfNewAlbums),
... | @Test
public void splitNegative() {
PhotoAlbum originalAlbum = new PhotoAlbum("123", "MyAlbum", DESCRIPTION);
List<PhotoAlbum> actual = originalAlbum.split(-1);
Truth.assertThat(actual).isEmpty();
} |
@Override
public Config getConfig() {
return config;
} | @Test
public void testSingleConfigYAML() throws IOException {
RedissonClient r = createInstance();
String t = r.getConfig().toYAML();
Config c = Config.fromYAML(t);
assertThat(c.toYAML()).isEqualTo(t);
} |
public static String resolveRaw(String str) {
int len = str.length();
if (len <= 4) {
return null;
}
int endPos = len - 1;
char last = str.charAt(endPos);
// optimize to not create new objects
if (last == ')') {
char char1 = str.charAt(0)... | @Test
void testURIScannerType2() {
final String resolvedRaw1 = URIScanner.resolveRaw("RAW{++?w0rd}");
Assertions.assertEquals("++?w0rd", resolvedRaw1);
} |
Set<String> getRetry() {
return retry;
} | @Test
public void determineRetryWhenNotSet() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry(null);
assertEquals(new HashSet<>(Collections.singletonList("never")), helper.getRetry());
} |
public <T> T sendAndReceive(String destination, Message<?> message, Type type) {
return sendAndReceive(destination, message, type, null, producer.getSendMsgTimeout(), 0);
} | @Test
public void testSendAndReceive_Async() {
try {
rocketMQTemplate.sendAndReceive(stringRequestTopic, MessageBuilder.withPayload("requestTopicASync").build(), new RocketMQLocalRequestCallback<String>() {
@Override public void onSuccess(String message) {
Sys... |
public Optional<EndpointCertificateSecrets> readEndpointCertificateSecrets(EndpointCertificateMetadata metadata) {
return Optional.of(readFromSecretStore(metadata));
} | @Test
void reads_from_correct_endpoint_certificate_store() {
MockSecretStore secretStore = new MockSecretStore();
secretStore.put("cert", 1, X509CertificateUtils.toPem(digicertCertificate));
secretStore.put("key", 1, KeyUtils.toPem(keyPair.getPrivate()));
DefaultEndpointCertificateSe... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void testBuildSessionEnvironment() {
String sessionName = "test";
Map<String, String> configMap = new HashMap<>();
configMap.put("key1", "value1");
configMap.put("key2", "value2");
SessionEnvironment expectedEnvironment =
new SessionEnvironment(... |
static boolean solve(RaidRoom[] rooms)
{
if (rooms == null)
{
return false;
}
List<RaidRoom> match = null;
Integer start = null;
Integer index = null;
int known = 0;
for (int i = 0; i < rooms.length; i++)
{
if (rooms[i] == null || rooms[i].getType() != RoomType.COMBAT || rooms[i] == UNKNOWN_C... | @Test
public void testSolve5()
{
RaidRoom[] rooms = new RaidRoom[]{GUARDIANS, UNKNOWN_COMBAT, SHAMANS, VASA};
RotationSolver.solve(rooms);
assertArrayEquals(new RaidRoom[]{GUARDIANS, VESPULA, SHAMANS, VASA}, rooms);
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof URL)) {
return false;
}
URL other = (URL) obj;
return Objects.equals(this.getUrl... | @Test
void testEquals() {
URL url1 = URL.valueOf(
"10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0");
URL url2 = URL.valueOf(
"10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group... |
public void refreshOptions() {
connectionBox = (XulListbox) document.getElementById( "connection-type-list" );
accessBox = (XulListbox) document.getElementById( "access-type-list" );
Object connectionKey = DataHandler.connectionNametoID.get( connectionBox.getSelectedItem() );
String databaseName = nul... | @Test
public void testRefreshOptions() throws Exception {
XulListbox connectionBox = mock( XulListbox.class );
when( document.getElementById( "connection-type-list" ) ).thenReturn( connectionBox );
when( connectionBox.getSelectedItem() ).thenReturn( "myDb" );
XulListbox accessBox = mock( XulListbox.cl... |
CacheConfig<K, V> asCacheConfig() {
return this.copy(new CacheConfig<>(), false);
} | @Test
public void serializationSucceeds_whenKVTypes_setAsClassNames() {
CacheConfig cacheConfig = newDefaultCacheConfig("test");
cacheConfig.setKeyClassName("java.lang.Integer");
cacheConfig.setValueClassName("java.lang.String");
PreJoinCacheConfig preJoinCacheConfig = new PreJoinCac... |
public void createPartitionMetadataTable() {
List<String> ddl = new ArrayList<>();
if (this.isPostgres()) {
// Literals need be added around literals to preserve casing.
ddl.add(
"CREATE TABLE \""
+ tableName
+ "\"(\""
+ COLUMN_PARTITION_TOKEN
... | @Test
public void testCreatePartitionMetadataTablePostgres() throws Exception {
when(op.get(TIMEOUT_MINUTES, TimeUnit.MINUTES)).thenReturn(null);
partitionMetadataAdminDaoPostgres.createPartitionMetadataTable();
verify(databaseAdminClient, times(1))
.updateDatabaseDdl(eq(INSTANCE_ID), eq(DATABASE_... |
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smpp... | @Test
public void createSmppMessageFromDeliveryReceiptWithoutShortMessageShouldNotThrowException() {
DeliverSm deliverSm = new DeliverSm();
deliverSm.setSmscDeliveryReceipt();
deliverSm.setOptionalParameters(new OptionalParameter.Short((short) 0x2153, (short) 0));
try {
... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.MAIL_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteMailTemplate(Long id) {
// 校验是否存在
validateMailTemplateExists(id);
// 删除
mailTemplateMapper.deleteById(id);
} | @Test
public void testDeleteMailTemplate_success() {
// mock 数据
MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailTemplate.getId();
// 调用
mailTemplateServic... |
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml4(input));
} | @Test
public void shouldEmphasisText() {
assertThat(Markdown.convertToHtml("This is *Sparta !!!*")).isEqualTo("This is <strong>Sparta !!!</strong>");
assertThat(Markdown.convertToHtml("This is *A*")).isEqualTo("This is <strong>A</strong>");
assertThat(Markdown.convertToHtml("This should not be * \n emphas... |
public static Boolean not(Boolean value) {
return value == null ? null : !value;
} | @SuppressWarnings({"ConstantConditions", "SimplifiableJUnitAssertion"})
@Test
public void testNot() {
assertEquals(true, TernaryLogic.not(false));
assertEquals(false, TernaryLogic.not(true));
assertEquals(null, TernaryLogic.not(null));
} |
@Override
public SendResult send(
Message msg) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
if (this.getAutoBatch() && !(msg instanceof MessageBatch)) {
return sendByAccumulator(msg, null, null... | @Test
public void testSendMessageAsync_Success() throws RemotingException, InterruptedException, MQBrokerException, MQClientException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRou... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void creation_date_support_zoneddatetime() {
SearchRequest request = new SearchRequest()
.setCreatedAt("2013-04-16T09:08:24+0200");
IssueQuery query = underTest.create(request);
assertThat(query.createdAt()).isEqualTo(parseDateTime("2013-04-16T09:08:24+0200"));
} |
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean is... | @Test
void testNoRestartStrategySpecifiedInJobConfig() {
final Configuration jobConf = new Configuration();
jobConf.set(RestartStrategyOptions.RESTART_STRATEGY, NO_RESTART_STRATEGY.getMainValue());
final Configuration clusterConf = new Configuration();
clusterConf.set(RestartStrategy... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_serializable_complex_object_with_non_serializable_nested_object() {
Map<String, List<NonSerializableObject>> map = new LinkedHashMap<>();
map.put("key1", Lists.newArrayList(new NonSerializableObject("name1")));
map.put("key2", Lists.newArrayList(
ne... |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenCommentMarker_skipsLine() {
CSVFormat csvFormat = csvFormat().withCommentMarker('#');
PCollection<String> input =
pipeline.apply(
Create.of(headerLine(csvFormat), "#should skip me", "a,1,1.1", "b,2,2.2", "c,3,3.3"));
CsvIOStringToCsvRecord underTest = new CsvIOS... |
public ScopedSpan startScopedSpanWithParent(String name, @Nullable TraceContext parent) {
if (name == null) throw new NullPointerException("name == null");
TraceContext context =
parent != null ? decorateContext(parent, parent.spanId()) : newRootContext(0);
return newScopedSpan(parent, context, name);... | @Test void startScopedSpanWithParent_resultantSpanIsLocalRoot() {
ScopedSpan span = tracer.startScopedSpanWithParent("foo", context);
try {
assertThat(span.context().spanId()).isEqualTo(span.context().localRootId()); // Sanity check
assertThat(span.context().isLocalRoot()).isTrue();
ScopedSpa... |
public static Collection<MetaDataLoaderMaterial> getMetaDataLoaderMaterials(final Collection<String> tableNames,
final GenericSchemaBuilderMaterial material, final boolean checkMetaDataEnable) {
Map<String, Collection<String>> dataS... | @Test
void assertGetSchemaMetaDataLoaderMaterialsWhenNotConfigCheckMetaDataEnableForSingleTableDataNode() {
ShardingSphereRule rule = mock(ShardingSphereRule.class);
DataNodeRuleAttribute ruleAttribute = mock(DataNodeRuleAttribute.class);
when(ruleAttribute.getDataNodesByTableName("t_single"... |
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
getRawMapping().setConf(conf);
} | @Test
public void testFileDoesNotExist() {
TableMapping mapping = new TableMapping();
Configuration conf = new Configuration();
conf.set(NET_TOPOLOGY_TABLE_MAPPING_FILE_KEY, "/this/file/does/not/exist");
mapping.setConf(conf);
List<String> names = new ArrayList<String>();
names.add(hostName1... |
public PipelineTemplateConfig templateByName(CaseInsensitiveString foo) {
for (PipelineTemplateConfig templateConfig : this) {
if (templateConfig.name().equals(foo)) {
return templateConfig;
}
}
return null;
} | @Test
public void shouldReturnTemplateByName() {
PipelineTemplateConfig template1 = template("template1");
TemplatesConfig templates = new TemplatesConfig(template1, template("template2"));
assertThat(templates.templateByName(new CaseInsensitiveString("template1")), is(template1));
} |
public static void resumeConsumers(final Queue<Consumer<byte[]>> consumers) {
consumers.forEach(Consumer::resume);
} | @Test
public void resumeConsumers() {
Consumer<byte[]> consumer = mock(Consumer.class);
Queue<Consumer<byte[]>> consumers = new ConcurrentLinkedQueue<>();
consumers.add(consumer);
PulsarUtils.resumeConsumers(consumers);
verify(consumer).resume();
} |
public static Timestamp parseTimestamp(final String str) {
return PARSER.parseToTimestamp(str);
} | @Test
public void shouldParseTimestamp() {
assertThat(SqlTimeTypes.parseTimestamp("2019-03-17T10:00:00"), is(new Timestamp(1552816800000L)));
assertThat(SqlTimeTypes.parseTimestamp("2019-03-17T03:00-0700"), is(new Timestamp(1552816800000L)));
} |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldBuildTimestampColumnWithFormat() {
// Given:
givenProperties(ImmutableMap.of(
CommonCreateConfigs.TIMESTAMP_NAME_PROPERTY,
new StringLiteral(quote(ELEMENT1.getName().text())),
CommonCreateConfigs.TIMESTAMP_FORMAT_PROPERTY,
new StringLiteral("%s")
));... |
public ControllerResult<ElectMasterResponseHeader> electMaster(final ElectMasterRequestHeader request,
final ElectPolicy electPolicy) {
final String brokerName = request.getBrokerName();
final Long brokerId = request.getBrokerId();
final ControllerResult<ElectMasterResponseHeader> result... | @Test
public void testElectMasterPreferHigherOffsetWhenEpochEquals() {
mockMetaData();
final ElectMasterRequestHeader request = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME);
ElectPolicy electPolicy = new DefaultElectPolicy(this.heartbeatManager::isBrokerActive, this.hear... |
public EvaluationResult evaluate(Condition condition, Measure measure) {
checkArgument(SUPPORTED_METRIC_TYPE.contains(condition.getMetric().getType()), "Conditions on MetricType %s are not supported", condition.getMetric().getType());
Comparable measureComparable = parseMeasure(measure);
if (measureCompara... | @Test
@UseDataProvider("unsupportedMetricTypes")
public void fail_when_metric_is_not_supported(MetricType metricType) {
Metric metric = createMetric(metricType);
Measure measure = newMeasureBuilder().create("3.14159265358");
assertThatThrownBy(() -> underTest.evaluate(createCondition(metric, LESS_THAN,... |
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch,
Timer timer) {
metadata.addTransientTopics(topicsForPartitions(timestampsToSearch.keySet()));
try {
Map<TopicPartit... | @Test
public void testGetOffsetsForTimesTimeout() {
buildFetcher();
assertThrows(TimeoutException.class, () -> offsetFetcher.offsetsForTimes(
Collections.singletonMap(new TopicPartition(topicName, 2), 1000L), time.timer(100L)));
} |
public static <T extends Classifiable<T>> double accuracy(MetricTarget<T> target, ConfusionMatrix<T> cm) {
if (target.getOutputTarget().isPresent()) {
return accuracy(target.getOutputTarget().get(), cm);
} else {
return accuracy(target.getAverageTarget().get(), cm);
}
... | @Test
public void testAccuracy() {
List<Prediction<Label>> predictions = Arrays.asList(
mkPrediction("a", "a"),
mkPrediction("c", "b"),
mkPrediction("b", "b"),
mkPrediction("b", "c")
);
ImmutableOutputInfo<Label> domain = mkDoma... |
@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 assertBuildGroupByMemoryMergedResultWithAggregationOnlyWithSQLServerLimit() throws SQLException {
final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "SQLServer"));
ShardingSphereDatabase database = mock(ShardingSphereData... |
@SuppressWarnings("all")
public static Boolean toBooleanObject(String str) {
String formatStr = (str == null ? StringUtils.EMPTY : str).toLowerCase();
if (TRUE_SET.contains(formatStr)) {
return true;
} else if (FALSE_SET.contains(formatStr)) {
return false;
... | @Test
void testToBooleanObject() {
assertTrue(ConvertUtils.toBooleanObject("T"));
assertTrue(ConvertUtils.toBooleanObject("t"));
assertTrue(ConvertUtils.toBooleanObject("Y"));
assertTrue(ConvertUtils.toBooleanObject("y"));
assertFalse(ConvertUtils.toBooleanObject("f"));
... |
public static List<InetSocketAddress> getJobMasterRpcAddresses(AlluxioConfiguration conf) {
// First check whether job rpc addresses are explicitly configured.
if (conf.isSet(PropertyKey.JOB_MASTER_RPC_ADDRESSES)) {
return parseInetSocketAddresses(
conf.getList(PropertyKey.JOB_MASTER_RPC_ADDRESS... | @Test
public void getJobMasterRpcAddresses() {
AlluxioConfiguration conf =
createConf(ImmutableMap.of(PropertyKey.JOB_MASTER_RPC_ADDRESSES, "host1:99,host2:100"));
assertEquals(
Arrays.asList(InetSocketAddress.createUnresolved("host1", 99),
InetSocketAddress.createUnresolved("host2... |
public SeaTunnelRow reconvert(InternalRow record) throws IOException {
if (isMultiTable) {
String tableId = record.getString(1);
return rowSerializationMap.get(tableId).reconvert(record);
}
return rowSerialization.reconvert(record);
} | @Test
public void testWriteConverter() throws IOException {
initSchema();
initData();
MultiTableManager multiTableManager =
new MultiTableManager(new CatalogTable[] {catalogTable1});
SeaTunnelRow seaTunnelRow = multiTableManager.reconvert(specificInternalRow1);
... |
@Override
public AppResponse process(Flow flow, RdaSessionRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException, SharedServiceClientException {
var authAppSession = appSessionService.getSession(request.getAuthSessionId());
if (!isAppSessionAuthenticated(authAppSessi... | @Test
void processOk() throws FlowNotDefinedException, SharedServiceClientException, IOException, NoSuchAlgorithmException {
//given
AppAuthenticator appAuthenticator = new AppAuthenticator();
appAuthenticator.setUserAppId("userAppId");
appAuthenticator.setInstanceId("123456");
... |
@Override
public void initialize(ServiceConfiguration config) throws IOException, IllegalArgumentException {
String prefix = (String) config.getProperty(CONF_TOKEN_SETTING_PREFIX);
if (null == prefix) {
prefix = "";
}
this.confTokenSecretKeySettingName = prefix + CONF_TOK... | @Test
public void testTrimAuthSecretKeyFilePath() throws Exception {
String space = " ";
SecretKey secretKey = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256);
File secretKeyFile = File.createTempFile("pulsar-test-secret-key-", ".key");
secretKeyFile.deleteOnExit();
... |
public static ValueLabel formatPacketRate(long packets) {
return new ValueLabel(packets, PACKETS_UNIT).perSec();
} | @Test
public void formatPacketRateMega() {
vl = TopoUtils.formatPacketRate(9_000_000);
assertEquals(AM_WL, "8.58 Mpps", vl.toString());
} |
@Override
public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
Path target;
if(source.attributes().getCustom().containsKey(KEY_DELETE_MARKER)) {
// De... | @Test
public void testMoveVirtualHost() throws Exception {
final S3AccessControlListFeature acl = new S3AccessControlListFeature(virtualhost);
final Path test = new S3TouchFeature(virtualhost, acl).touch(new Path(new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatu... |
public static Future<?> runInThread(String groupId, final Runnable runnable) {
return GROUP_THREAD_POOLS.getOrDefault(groupId, GlobalThreadPoolHolder.INSTANCE).submit(runnable);
} | @Test
public void testRunThread() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
ThreadPoolsFactory.runInThread(GROUP_ID_001, () -> latch.countDown());
latch.await();
} |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void kGroupedStreamAnonymousStoreTypedMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.count(Materialized.as(Materialized.StoreType.IN_MEMORY));
final To... |
@Override
public void report() {
try {
tryReport();
} catch (ConcurrentModificationException | NoSuchElementException ignored) {
// at tryReport() we don't synchronize while iterating over the various maps which might
// cause a
// ConcurrentModificati... | @Test
void testOnlyMeterRegistered() {
reporter.notifyOfAddedMetric(new MeterView(new SimpleCounter()), "metric", metricGroup);
reporter.report();
assertThat(testLoggerResource.getMessages())
.noneMatch(logOutput -> logOutput.contains("-- Counter"))
.noneMat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.