focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static void main(String[] args) {
var sd = serviceDiscovery();
var service = sd.findAny();
var goodOrderSaga = service.execute(newSaga("good_order"));
var badOrderSaga = service.execute(newSaga("bad_order"));
LOGGER.info("orders: goodOrder is {}, badOrder is {}",
goodOrderSaga.getResu... | @Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> SagaApplication.main(new String[]{}));
} |
public Class<?> compileGroovy(String sFilterCode) throws CompilationFailedException {
GroovyClassLoader loader = new GroovyClassLoader();
return loader.parseClass(sFilterCode);
} | @Test
void testCompile() {
Class<?> filterClass = FilterVerifier.INSTANCE.compileGroovy(sGoodGroovyScriptFilter);
assertNotNull(filterClass);
filterClass = FilterVerifier.INSTANCE.compileGroovy(sNotZuulFilterGroovy);
assertNotNull(filterClass);
assertThrows(CompilationFailed... |
@Override
public boolean setPonLink(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();
... | @Test
public void testValidSetPonLink() throws Exception {
String target;
boolean result;
for (int i = ZERO; i < VALID_SET_TCS.length; i++) {
target = VALID_SET_TCS[i];
currentKey = i;
result = voltConfig.setPonLink(target);
assertTrue("Incorr... |
private Messages() {
super( BUNDLE_NAME );
} | @Test
public void testMessages() {
assertEquals( "Wrong message returned", "test message 1", Messages.getInstance().getString( "test.MESSAGE1" ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
assertEquals(
"Wrong message returned", "test message 2: A", Messages.getInstance().getString( "test.MESSAGE2",... |
public ErrorResponse buildErrorResponse(RestLiServiceException result)
{
// In some cases, people use 3XX to signal client a redirection. This falls into the category of blurred boundary
// whether this should be an error or not, in order to not disrupt change the behavior of existing code
// Thus excludi... | @SuppressWarnings("deprecation")
@Test
public void testExceptionClass()
{
ErrorResponseBuilder builder = new ErrorResponseBuilder();
RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "foobar", new IllegalStateException("foo"));
exception.setServiceErrorCode(12... |
@ConstantFunction(name = "bitxor", argTypes = {BIGINT, BIGINT}, returnType = BIGINT)
public static ConstantOperator bitxorBigint(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createBigint(first.getBigint() ^ second.getBigint());
} | @Test
public void bitxorBigint() {
assertEquals(0, ScalarOperatorFunctions.bitxorBigint(O_BI_100, O_BI_100).getBigint());
} |
@Override
public PageResult<TenantDO> getTenantPage(TenantPageReqVO pageReqVO) {
return tenantMapper.selectPage(pageReqVO);
} | @Test
public void testGetTenantPage() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> { // 等会查询到
o.setName("芋道源码");
o.setContactName("芋艿");
o.setContactMobile("15601691300");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
... |
public Collection<Set<V>> computeMaxCliques() {
lazyRun();
return maximumCliques;
} | @Test
public void test6DisconnectedSubgraphsOfWholeGraph() {
List<List<String>> groups = new ArrayList<>();
for (int i = 0; i < 20; i++) {
int j = i;
int vertexCount = i + 10;
List<String> vertices = IntStream.range(0, vertexCount).mapToObj(v -> j + "_" + v).colle... |
@Override
public Optional<ScmInfo> getScmInfo(Component component) {
requireNonNull(component, "Component cannot be null");
if (component.getType() != Component.Type.FILE) {
return Optional.empty();
}
return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent);
} | @Test
public void return_empty_if_component_is_not_file() {
Component c = mock(Component.class);
when(c.getType()).thenReturn(Type.DIRECTORY);
assertThat(underTest.getScmInfo(c)).isEmpty();
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatBetweenPredicate() {
final BetweenPredicate predicate = new BetweenPredicate(new StringLiteral("blah"), new LongLiteral(5), new LongLiteral(10));
assertThat(ExpressionFormatter.formatExpression(predicate), equalTo("('blah' BETWEEN 5 AND 10)"));
} |
@Override
public String pluginNamed() {
return PluginEnum.GRPC.getName();
} | @Test
public void testPpluginNamed() {
assertEquals(grpcPluginDataHandler.pluginNamed(), PluginEnum.GRPC.getName());
} |
public Embed embed(byte[] bytes, ResourceType resourceType) {
if (embeds == null) {
embeds = new ArrayList();
}
Embed embed = saveToFileAndCreateEmbed(bytes, resourceType);
embeds.add(embed);
return embed;
} | @Test
void testEmbed() {
run(
"karate.embed('<h1>hello world</h1>', 'text/html')"
);
List<StepResult> results = sr.result.getStepResults();
assertEquals(1, results.size());
List<Embed> embeds = results.get(0).getEmbeds();
assertEquals(1, embeds.size())... |
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception {
Http2HeadersSink sink = new Http2HeadersSink(
streamId, headers, maxHeaderListSize, validateHeaders);
// Check for dynamic table size updates, which must occur at the beginning:
... | @Test
public void testLiteralWithoutIndexingWithLargeValue() throws Http2Exception {
// Ignore header that exceeds max header size
final StringBuilder sb = new StringBuilder();
sb.append("0004");
sb.append(hex("name"));
sb.append("7F813F");
for (int i = 0; i < 8192; i... |
@Override
public BasicTypeDefine<MysqlType> reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.<MysqlType>builder()
.name(column.getName())
.nullable(column.isNullable())
.comment... | @Test
public void testReconvertFloat() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.FLOAT_TYPE).build();
BasicTypeDefine<MysqlType> typeDefine =
MySqlTypeConverter.DEFAULT_INSTANCE.reconvert(column);
Assertions.assertEquals(colum... |
@Override
public int getNumberOfQueuedBuffers() {
if (findCurrentNettyPayloadQueue()) {
return getBacklog();
}
return 0;
} | @Test
void testGetNumberOfQueuedBuffers() {
assertThat(tieredStorageResultSubpartitionView.getNumberOfQueuedBuffers()).isEqualTo(1);
assertThat(tieredStorageResultSubpartitionView.unsynchronizedGetNumberOfQueuedBuffers())
.isEqualTo(1);
} |
@Override
public Iterator<Record> iterator() {
return iterator(BufferSupplier.NO_CACHING);
} | @Test
public void testZStdCompressionTypeWithV0OrV1() {
SimpleRecord[] simpleRecords = new SimpleRecord[] {
new SimpleRecord(1L, "a".getBytes(), "1".getBytes()),
new SimpleRecord(2L, "b".getBytes(), "2".getBytes()),
new SimpleRecord(3L, "c".getBytes(), "3".getBytes())
... |
@VisibleForTesting
MailTemplateDO validateMailTemplate(String templateCode) {
// 获得邮件模板。考虑到效率,从缓存中获取
MailTemplateDO template = mailTemplateService.getMailTemplateByCodeFromCache(templateCode);
// 邮件模板不存在
if (template == null) {
throw exception(MAIL_TEMPLATE_NOT_EXISTS);
... | @Test
public void testValidateMailTemplateValid_notExists() {
// 准备参数
String templateCode = RandomUtils.randomString();
// mock 方法
// 调用,并断言异常
assertServiceException(() -> mailSendService.validateMailTemplate(templateCode),
MAIL_TEMPLATE_NOT_EXISTS);
} |
public static IpAddress valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new IpAddress(Version.INET, bytes);
} | @Test
public void testEqualityIPv4() {
new EqualsTester()
.addEqualityGroup(IpAddress.valueOf("1.2.3.4"),
IpAddress.valueOf("1.2.3.4"))
.addEqualityGroup(IpAddress.valueOf("1.2.3.5"),
IpAddress.valueOf("1.2.3.5"))
... |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testNotEqualToNull() {
String col = "col";
NamedReference namedReference = FieldReference.apply(col);
LiteralValue value = new LiteralValue(null, DataTypes.IntegerType);
org.apache.spark.sql.connector.expressions.Expression[] attrAndValue =
new org.apache.spark.sql.connector... |
public static List<String> parseAddressList(String addressInfo) {
if (StringUtils.isBlank(addressInfo)) {
return Collections.emptyList();
}
List<String> addressList = new ArrayList<>();
String[] addresses = addressInfo.split(ADDRESS_SEPARATOR);
for (String address : addresses) {
URI uri = URI.create(add... | @Test
public void testEmptyStr() {
List<String> result = AddressUtils.parseAddressList("");
assertThat(result).isNotNull();
assertThat(result).isEmpty();
} |
public <OutputT extends @NonNull Object> CsvIOParse<T> withCustomRecordParsing(
String fieldName, SerializableFunction<String, OutputT> customRecordParsingFn) {
Map<String, SerializableFunction<String, Object>> customProcessingMap =
getConfigBuilder().getOrCreateCustomProcessingMap();
customProc... | @Test
public void givenCustomParsingError_emits() {
PCollection<String> records =
csvRecords(pipeline, "instant,instantList", "2024-01-23T10:00:05.000Z,BAD CELL");
CsvIOParse<TimeContaining> underTest =
underTest(
TIME_CONTAINING_SCHEMA,
CSVFormat.DEFAULT
... |
@Override
public int run(String[] args) throws Exception {
YarnConfiguration yarnConf =
getConf() == null ? new YarnConfiguration() : new YarnConfiguration(
getConf());
boolean isHAEnabled =
yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED,
YarnConfiguration.DEFAULT_... | @Test
public void testRemoveLabelsOnNodes() throws Exception {
// Successfully replace labels
dummyNodeLabelsManager
.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y"));
String[] args = { "-replaceLabelsOnNode", "node1=x node2=y",
"-directlyAccessNodeLabelStore" };
... |
@Override
public void search(K q, double radius, List<Neighbor<K, V>> neighbors) {
if (radius <= 0 || radius != (int) radius) {
throw new IllegalArgumentException("The parameter radius has to be an integer: " + radius);
}
long fpq = simhash.hash(q);
Set<Integer> candidat... | @Test
public void test() throws IOException {
System.out.println("SNLSH");
SNLSH<String[], String> lsh = createLSH(texts);
ArrayList<Neighbor<String[], String>> neighbors = new ArrayList<>();
lsh.search(tokenize(texts[0]), 3, neighbors);
assertEquals(2, neighbors.size());
... |
@Override
@Deprecated
public ByteOrder order() {
return unwrap().order();
} | @Test
public void shouldHaveSameByteOrder() {
ByteBuf buf = buffer(1);
assertSame(BIG_ENDIAN, unmodifiableBuffer(buf).order());
buf = buf.order(LITTLE_ENDIAN);
assertSame(LITTLE_ENDIAN, unmodifiableBuffer(buf).order());
} |
public String decode(String s) throws CannotDecodeException
{
if (s == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
int len = s.length();
for (int i = 0; i < len; i++)
{
char c = s.charAt(i);
if (c == _encodingChar)
{
if (i + 3 > len)
... | @Test
public void testSingleCharDecode() throws Exception
{
Assert.assertEquals(TEST_ENCODING_1.decode("~2E"), ".");
Assert.assertEquals(TEST_ENCODING_1.decode("~5B"), "[");
Assert.assertEquals(TEST_ENCODING_1.decode("~5D"), "]");
Assert.assertEquals(TEST_ENCODING_1.decode("~7E"), "~");
Assert.a... |
@Override
public String getModuleName() {
return Modules.Encrypt.MODULE_NAME;
} | @Test
public void getModuleName() {
SAHelper.initSensors(mApplication);
SAEncryptProtocolImpl encryptProtocol = new SAEncryptProtocolImpl();
encryptProtocol.install(SensorsDataAPI.sharedInstance(mApplication).getSAContextManager());
Assert.assertEquals(encryptProtocol.getModuleName()... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testWithRegexpCondition() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.conditionType(REGEX)
.conditionValue("^hello")
.build();
// Extractor runs if the message matches the condition regexp.
... |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException {
/*
* Creates a new instance because the object is not immutable.
*/
new Latin1StringsParser().doParse(stream, ha... | @Test
public void testParse() throws Exception {
String testStr =
"These are Latin1 accented scripts: \u00C2 \u00C3 \u00C9 \u00DC \u00E2 " +
"\u00E3 \u00E9 \u00FC";
String smallStr = "ab";
byte[] iso8859Bytes = testStr.getBytes(ISO_8859_1);
b... |
public void createView(View view, boolean replace, boolean ifNotExists) {
if (ifNotExists) {
relationsStorage.putIfAbsent(view.name(), view);
} else if (replace) {
relationsStorage.put(view.name(), view);
} else if (!relationsStorage.putIfAbsent(view.name(), view)) {
... | @Test
public void when_createsViewIfNotExists_then_succeeds() {
// given
View view = view();
given(relationsStorage.putIfAbsent(view.name(), view)).willReturn(true);
// when
catalog.createView(view, false, true);
// then
verify(relationsStorage).putIfAbsent(... |
public static String md5Hex(byte[] bytes) throws NoSuchAlgorithmException {
try {
MessageDigest messageDigest = MESSAGE_DIGEST_LOCAL.get();
if (messageDigest != null) {
return encodeHexString(messageDigest.digest(bytes));
}
throw new NoSuchAlgorith... | @Test
public void assertMd5Hex2() {
String md5 = "503840dc3af3cdb39749cd099e4dfeff";
String message = "dynamic-threadpool-example";
Assert.isTrue(md5.equals(Md5Util.md5Hex(message, "UTF-8")));
} |
@ExceptionHandler(RuntimeException.class)
protected ResponseEntity<?> handleRuntimeException(final RuntimeException runtimeException) {
CustomError customError = CustomError.builder()
.httpStatus(HttpStatus.NOT_FOUND)
.header(CustomError.Header.API_ERROR.getName())
... | @Test
void givenRuntimeException_whenHandleRuntimeException_thenRespondWithNotFound() {
// Given
RuntimeException ex = new RuntimeException("Runtime exception message");
CustomError expectedError = CustomError.builder()
.httpStatus(HttpStatus.NOT_FOUND)
.hea... |
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) {
final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace();
final String importerDMNName = ((Definitions) importElement.getParent()).getName(... | @Test
void nSnoModelNameWithAlias() {
final Import i = makeImport("ns1", "mymodel", null);
final List<QName> available = Arrays.asList(new QName("ns1", "m1"),
new QName("ns2", "m2"),
new QName("ns... |
static public Entry buildMenuStructure(String xml) {
final Reader reader = new StringReader(xml);
return buildMenuStructure(reader);
} | @Test
public void givenXmlWithSameChildLevels_createsStructure() {
String xmlWithoutContent = "<FreeplaneUIEntries><Entry name='level1'/>"
+ "<Entry name='level2'/>"
+ "</FreeplaneUIEntries>";
Entry builtMenuStructure = XmlEntryStructureBuilder.buildMenuStructure(xmlWithoutContent);
Entry menuStructure... |
public Set<MessageQueue> fetchSubscribeMessageQueues(String topic) throws MQClientException {
Set<MessageQueue> result = this.rebalanceImpl.getTopicSubscribeInfoTable().get(topic);
if (null == result) {
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
result = this... | @Test
public void testFetchSubscribeMessageQueues() throws MQClientException {
Set<MessageQueue> actual = defaultMQPushConsumerImpl.fetchSubscribeMessageQueues(defaultTopic);
assertNotNull(actual);
Assert.assertEquals(1, actual.size());
MessageQueue next = actual.iterator().next();
... |
@VisibleForTesting
void updateValueMeta() throws KettleException {
List<ValueMetaInterface> outputValueMetaList = data.outputRowMeta.getValueMetaList();
List<ValueMetaInterface> aggMetaValueMetaList = data.aggMeta.getValueMetaList();
for ( int outputIndex = 0; outputIndex < outputValueMetaList.size(); ++... | @Test
public void updateValueMetaNoMatchTest() throws KettleException {
ValueMetaString stringMetaFromOutput = new ValueMetaString( "stringMeta" );
ValueMetaBinary binaryMetaFromOutput = new ValueMetaBinary( "binaryMeta" );
ValueMetaBinary binaryMetaFromAgg = new ValueMetaBinary( "binaryMeta2" );
Valu... |
@Override
public void run() {
MetricsContainerImpl metricsContainer = new MetricsContainerImpl(transform.getFullName());
try (Closeable metricsScope = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) {
Collection<ModelEnforcement<T>> enforcements = new ArrayList<>();
for (ModelEnforcem... | @Test
public void callWithNullInputBundleFinishesBundleAndCompletes() throws Exception {
final TransformResult<Object> result = StepTransformResult.withoutHold(createdProducer).build();
final AtomicBoolean finishCalled = new AtomicBoolean(false);
TransformEvaluator<Object> evaluator =
new Transfor... |
@Nullable
static Boolean minIsrBasedConcurrencyAdjustment(CruiseControlRequestContext requestContext) {
String parameterString = caseSensitiveParameterName(requestContext.getParameterMap(), MIN_ISR_BASED_CONCURRENCY_ADJUSTMENT_PARAM);
if (parameterString == null) {
return null;
}
return Boolean.... | @Test
public void testMinIsrBasedConcurrencyAdjustment() {
String firstResponse = Boolean.TRUE.toString();
String secondResponse = Boolean.FALSE.toString();
// Mock for (1) default response (2) response for valid input with true/false.
CruiseControlRequestContext mockRequest = EasyMock.mock(CruiseCon... |
public boolean contains(double latitude, double longitude) {
return this.minLatitude <= latitude && this.maxLatitude >= latitude
&& this.minLongitude <= longitude && this.maxLongitude >= longitude;
} | @Test
public void containsCoordinatesTest() {
BoundingBox boundingBox = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE);
Assert.assertTrue(boundingBox.contains(MIN_LATITUDE, MIN_LONGITUDE));
Assert.assertTrue(boundingBox.contains(MAX_LATITUDE, MAX_LONGITUDE));
... |
DnsOverXmppMiniDnsResolver(DnsClient dnsClient, DnssecClient dnssecClient) {
this.dnsClient = dnsClient;
this.dnssecClient = dnssecClient;
} | @Test
public void dnsOverXmppMiniDnsResolverTest() throws IOException {
TestDnsDataSource dnsSource = new TestDnsDataSource();
TestDnsDataSource dnssecSource = new TestDnsDataSource();
DnsClient dnsClient = new DnsClient(NoopDnsCache.INSTANCE);
dnsClient.setDataSource(dnsSource);
... |
public FEELFnResult<Object> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern,
@ParameterName( "replacement" ) String replacement ) {
return invoke(input, pattern, replacement, null);
} | @Test
void invokeWithoutFlagsPatternMatches() {
FunctionTestUtil.assertResult(replaceFunction.invoke("testString", "^test", "ttt"), "tttString");
FunctionTestUtil.assertResult(replaceFunction.invoke("testStringtest", "^test", "ttt"), "tttStringtest");
} |
public boolean isObjectExists(String objectName) {
try {
minioClient.statObject(StatObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build()
);
return true;
} catch (Exception e) {
r... | @Test
void isObjectExists() {
boolean exists = minioService.isObjectExists("fuck-you.jpeg");
System.out.println("exists = " + exists);
assert !exists;
} |
@Override
public void open(Configuration parameters) throws Exception {
this.rateLimiterTriggeredCounter =
getRuntimeContext()
.getMetricGroup()
.addGroup(
TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT)
.counter(TableMain... | @Test
void testLockCheckDelay() throws Exception {
TableLoader tableLoader = sql.tableLoader(TABLE_NAME);
TriggerManager manager = manager(tableLoader, 1, DELAY);
try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness =
harness(manager)) {
testHarness.open();
... |
public void analyze(ConnectContext context) {
dbName = AnalyzerUtils.getOrDefaultDatabase(dbName, context);
FeNameFormat.checkLabel(labelName);
} | @Test(expected = SemanticException.class)
public void testNoDb() throws SemanticException {
new Expectations() {
{
analyzer.getDefaultDb();
minTimes = 0;
result = null;
}
};
LabelName label = new LabelName("", "testLabe... |
@Config("function-implementation-type")
public SqlFunctionLanguageConfig setFunctionImplementationType(String implementationType)
{
this.functionImplementationType = FunctionImplementationType.valueOf(implementationType.toUpperCase());
return this;
} | @Test
public void testDefault()
{
assertRecordedDefaults(recordDefaults(SqlFunctionLanguageConfig.class)
.setFunctionImplementationType("SQL"));
} |
@Override
public void writeBytes(Slice source)
{
writeBytes(source, 0, source.length());
} | @Test
public void testWriteBytes()
{
DataSize chunkSize = new DataSize(700, BYTE);
DataSize maxCompressionSize = new DataSize(chunkSize.toBytes() + 3, BYTE); // 3 accounts for the chunk header size
DataSize dataSize = new DataSize(2 * 700 + 10, BYTE);
byte[] testData = createTest... |
@Override
public NSImage documentIcon(final String extension, final Integer size) {
NSImage image = this.load(extension, size);
if(null == image) {
return this.cache(extension,
this.convert(extension, workspace.iconForFileType(extension), size), size);
}
... | @Test
public void testDocumentIconNoExtension() {
final NSImage icon = new NSImageIconCache().documentIcon("", 64);
assertNotNull(icon);
assertTrue(icon.isValid());
assertFalse(icon.isTemplate());
assertEquals(64, icon.size().width.intValue());
assertEquals(64, icon.s... |
@Override
public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterReplicaMap() {
Iterable<RedisClusterNode> res = clusterGetNodes();
Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>();
for (Iterator<RedisClusterNode> iterator = res.iterator(); iterato... | @Test
public void testClusterGetMasterSlaveMap() {
Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterReplicaMap();
assertThat(map).hasSize(3);
for (Collection<RedisClusterNode> slaves : map.values()) {
assertThat(slaves).hasSize(1);
}
... |
public static <E, K, U> Map<K, Map<U, List<E>>> groupBy2Key(Collection<E> collection, Function<E, K> key1, Function<E, U> key2) {
return groupBy2Key(collection, key1, key2, false);
} | @Test
public void testGroupBy2Key() {
Map<Long, Map<Long, List<Student>>> map = CollStreamUtil.groupBy2Key(null, Student::getTermId, Student::getClassId);
assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>();
map = CollStreamUtil.groupBy2Key(list, Student::getTermId, Student::getCla... |
public void setFlags(String flagsAsString) {
String[] flagsArray = flagsAsString.split(",");
this.flags = new Flag[flagsArray.length];
for (int i = 0; i < flagsArray.length; i++) {
this.flags[i] = Flag.valueOf(flagsArray[i]);
}
} | @Test
public void embeddedCacheWithFlagsTest() throws Exception {
InfinispanEmbeddedConfiguration configuration = new InfinispanEmbeddedConfiguration();
configuration.setFlags(Flag.IGNORE_RETURN_VALUES);
try (InfinispanEmbeddedManager manager = new InfinispanEmbeddedManager(configuration)) ... |
public static Map<String, String> getProps(String properties) {
Map<String, String> configs = new HashMap<>();
if (StringUtils.isNotEmpty(properties)) {
for (String property : properties.split(";")) {
if (StringUtils.isNotEmpty(property)) {
int delimiterPo... | @Test
void givenNullOrEmpty_whenGetConfig_thenEmptyMap() {
assertThat(PropertyUtils.getProps(null)).as("null property").isEmpty();
assertThat(PropertyUtils.getProps("")).as("empty property").isEmpty();
assertThat(PropertyUtils.getProps(";")).as("ends with ;").isEmpty();
} |
@PostConstruct
public void synchronize() throws IOException {
try {
synchronizeConfig();
} catch (NonTransientDataAccessException | StaleStateException e) {
logger.error("Database exception while synchronizing configurations", e);
}
} | @Test
public void test() throws IOException {
Configuration conf1 = new Configuration();
conf1.setName("1");
conf1.setValue("1");
conf1.setDefaultValue("2"); // updated defaultValue
Configuration conf2 = new Configuration();
conf2.setName("2");
conf2.setValue(... |
public ClosestPointOfApproach closestPointOfApproach() {
checkState(
point1.time().equals(point2.time()),
"This function can only be applied to points at the same Instant"
);
Vector initialVectorBetweenPoints = vectorBetweenPointsInNm();
Vector velocityDifference... | @Test
public void closestPointOfApproachRequiresPointsFromTheSameTime() {
Point p1 = Point.builder().latLong(0.0, 0.0).time(EPOCH).build();
Point p2 = Point.builder().latLong(0.0, 0.0).time(EPOCH.plusSeconds(1)).build();
PointPair points = new PointPair(p1, p2);
assertThrows(
... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetName() {
assertEquals("pip Analyzer", analyzer.getName());
} |
DistributedHerderRequest addRequest(Callable<Void> action, Callback<Void> callback) {
return addRequest(0, action, callback);
} | @Test
public void testRequestProcessingOrder() {
Callable<Void> action = mock(Callable.class);
Callback<Void> callback = mock(Callback.class);
final DistributedHerder.DistributedHerderRequest req1 = herder.addRequest(100, action, callback);
final DistributedHerder.DistributedHerderR... |
@Udf(description = "Returns Euler's number e raised to the power of an INT value.")
public Double exp(
@UdfParameter(
value = "exponent",
description = "the exponent to raise e to."
) final Integer exponent
) {
return exp(exponent == null ? null : exponent.doubleValue());
} | @Test
public void shouldHandlePositive() {
assertThat(udf.exp(1), is(2.718281828459045));
assertThat(udf.exp(1L), is(2.718281828459045));
assertThat(udf.exp(1.0), is(2.718281828459045));
} |
public Properties getProperties()
{
return properties;
} | @Test
public void testUriWithClientTags()
throws SQLException
{
String clientTags = "c1,c2";
PrestoDriverUri parameters = createDriverUri("presto://localhost:8080?clientTags=" + clientTags);
Properties properties = parameters.getProperties();
assertEquals(properties.g... |
@Override
public String getHelpMessage() {
return HELP;
} | @Test
public void shouldGetHelp() {
assertThat(command.getHelpMessage(),
containsString("server:" + System.lineSeparator() + "\tShow the current server"));
assertThat(command.getHelpMessage(),
containsString("server <server>:" + System.lineSeparator()
+ "\tChange the current server... |
public static String truncateMessageLineLength(Object message) {
return truncateMessageLineLength(message, MAX_TRUNCATED_LENGTH);
} | @Test
public void truncateShortLines() throws Exception {
for (int i = 0; i < 20; i++) {
String s = "";
for (int lines = 0; lines < ThreadLocalRandom.current().nextInt(5, 10); lines++) {
s += "\n";
s += CommonUtils.randomAlphaNumString(
ThreadLocalRandom.current().nextInt(1... |
@SuppressWarnings("deprecation")
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> left,
final KStreamHolder<K> right,
final StreamStreamJoin<K> join,
final RuntimeBuildContext buildContext,
final StreamJoinedFactory streamJoinedFactory) {
final QueryContext queryConte... | @Test
public void shouldDoInnerJoinWithGrace() {
// Given:
givenInnerJoin(L_KEY, Optional.of(GRACE));
// When:
final KStreamHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
verify(leftKStream).join(
same(rightKStream),
eq(new KsqlValueJoiner(LEFT_SCHEMA.val... |
@Override
public DelayMeasurementCreate decode(ObjectNode json,
CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
JsonNode dmNode = json.get(DM);
Version version = Version.Y17312011;
if (dmNode.get(VERSION) != null) {
... | @Test
public void testDecodeObjectNodeCodecContext1()
throws JsonProcessingException, IOException {
String moStr = "{\"dm\": {}}";
InputStream input = new ByteArrayInputStream(
moStr.getBytes(StandardCharsets.UTF_8));
JsonNode cfg = mapper.readTree(input);
... |
@Override
public void onRemovedJobGraph(JobID jobId) {
runIfStateIs(State.RUNNING, () -> handleRemovedJobGraph(jobId));
} | @Test
void onRemovedJobGraph_terminatesRunningJob() throws Exception {
jobGraphStore =
TestingJobGraphStore.newBuilder()
.setInitialJobGraphs(Collections.singleton(JOB_GRAPH))
.build();
final CompletableFuture<JobID> terminateJobFuture... |
@Override
public AssessmentResult verify(
final String siteKey,
final Action action,
final String token,
final String ip)
throws IOException {
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
final String body =... | @Test
public void errorResponse() throws IOException, InterruptedException {
final FaultTolerantHttpClient httpClient = mockResponder(503, "");
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
assertThrows(IOException.class, () -> client.verify(SITE_KEY, Action.... |
public Buffer copyTo(OutputStream out) throws IOException {
return copyTo(out, 0, size);
} | @Test public void copyTo() throws Exception {
Buffer source = new Buffer();
source.writeUtf8("party");
Buffer target = new Buffer();
source.copyTo(target, 1, 3);
assertEquals("art", target.readUtf8());
assertEquals("party", source.readUtf8());
} |
ObjectFactory loadObjectFactory() {
Class<? extends ObjectFactory> objectFactoryClass = options.getObjectFactoryClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class, classLoader);
if (objectFactoryClass... | @Test
void test_case_7() {
io.cucumber.core.backend.Options options = () -> OtherFactory.class;
ObjectFactoryServiceLoader loader = new ObjectFactoryServiceLoader(
() -> new ServiceLoaderTestClassLoader(ObjectFactory.class,
DefaultObjectFactory.class,
Othe... |
public void onChange(Multimap<QProfileName, ActiveRuleChange> changedProfiles, long startDate, long endDate) {
if (config.getBoolean(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES).orElse(false)) {
return;
}
BuiltInQPChangeNotificationBuilder builder = new BuiltInQPChangeNotificationBuilder();
change... | @Test
public void avoid_notification_if_configured_in_settings() {
settings.setProperty(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES, true);
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
addProfile(profiles, languages, ACTIVATED);
... |
@Override
public OAuth2AccessTokenDO refreshAccessToken(String refreshToken, String clientId) {
// 查询访问令牌
OAuth2RefreshTokenDO refreshTokenDO = oauth2RefreshTokenMapper.selectByRefreshToken(refreshToken);
if (refreshTokenDO == null) {
throw exception0(GlobalErrorCodeConstants.BAD... | @Test
public void testRefreshAccessToken_null() {
// 准备参数
String refreshToken = randomString();
String clientId = randomString();
// mock 方法
// 调用,并断言
assertServiceException(() -> oauth2TokenService.refreshAccessToken(refreshToken, clientId),
new Erro... |
@Override
protected void removeRange(int fromIndex, int toIndex) {
if (fromIndex == toIndex) {
return;
}
notifyRemoval(fromIndex, toIndex - fromIndex);
super.removeRange(fromIndex, toIndex);
} | @Test
public void testRemoveEmptyRange() {
modelList.removeRange(1, 1);
verifyNoMoreInteractions(observer);
} |
@Override
public List<MailAccountDO> getMailAccountList() {
return mailAccountMapper.selectList();
} | @Test
public void testGetMailAccountList() {
// mock 数据
MailAccountDO dbMailAccount01 = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount01);
MailAccountDO dbMailAccount02 = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount02);
... |
public static synchronized ShowResultSet process(List<AlterClause> alterClauses, Database db,
OlapTable olapTable) throws UserException {
Preconditions.checkArgument(alterClauses.size() == 1);
AlterClause alterClause = alterClauses.get(0);
Pre... | @Test(expected = IllegalStateException.class)
public void testProcessNonCompactionClause() {
AlterClause nonCompactionClause = mock(AlterClause.class);
List<AlterClause> alterList = Collections.singletonList((nonCompactionClause));
try {
compactionHandler.process(alterList, db, o... |
public Collection<SimpleTableSegment> extractNotExistTableFromRoutineBody(final RoutineBodySegment routineBody) {
Collection<SimpleTableSegment> result = new LinkedList<>();
for (ValidStatementSegment each : routineBody.getValidStatements()) {
Optional<CreateTableStatement> createTable = eac... | @Test
void assertNotExistTableFromRoutineBody() {
RoutineBodySegment routineBodySegment = new RoutineBodySegment(0, 3);
ValidStatementSegment validStatement = new ValidStatementSegment(0, 1);
validStatement.setSqlStatement(mock(SQLStatement.class));
routineBodySegment.getValidStateme... |
public static boolean isClientException(SofaRpcException exception) {
int errorType = exception.getErrorType();
return errorType >= 200 && errorType < 300;
} | @Test
public void isClientException() throws Exception {
SofaRpcException exception = new SofaRpcException(RpcErrorType.SERVER_BUSY, "111");
Assert.assertFalse(ExceptionUtils.isClientException(exception));
exception = new SofaRpcException(RpcErrorType.CLIENT_TIMEOUT, "111");
Assert.a... |
@Override
public void putAll(final List<KeyValue<Bytes, byte[]>> entries) {
wrapped().putAll(entries);
for (final KeyValue<Bytes, byte[]> entry : entries) {
final byte[] valueAndTimestamp = entry.value;
log(entry.key, rawValue(valueAndTimestamp), valueAndTimestamp == null ? c... | @Test
public void shouldLogChangesOnPutAll() {
store.putAll(Arrays.asList(KeyValue.pair(hi, rawThere),
KeyValue.pair(hello, rawWorld)));
assertThat(collector.collected().size(), equalTo(2));
assertThat(collector.collected().get(0).key(), equalTo(hi));
... |
@Override
public Optional<ComputationConfig> fetchConfig(String computationId) {
Preconditions.checkArgument(
!computationId.isEmpty(),
"computationId is empty. Cannot fetch computation config without a computationId.");
GetConfigResponse response =
applianceComputationConfigFetcher.f... | @Test
public void testGetComputationConfig_onFetchConfigError() {
StreamingApplianceComputationConfigFetcher configLoader =
createStreamingApplianceConfigLoader();
RuntimeException e = new RuntimeException("something bad happened.");
when(mockWindmillServer.getConfig(any())).thenThrow(e);
Thro... |
public static HKDF extractedFrom(byte[] salt, byte[] ikm) {
validateExtractionParams(salt, ikm);
/*
RFC-5869, Step 2.2, Extract:
HKDF-Extract(salt, IKM) -> PRK
Options:
Hash a hash function; HashLen denotes the length of the
hash fun... | @Test
void missing_salt_to_salted_factory_function_throws_exception() {
var ikm = unhex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
assertThrows(NullPointerException.class, () -> HKDF.extractedFrom(null, ikm));
assertThrows(IllegalArgumentException.class, () -> HKDF.extractedFrom(new b... |
static Schema getSchema(Class<? extends Message> clazz) {
return getSchema(ProtobufUtil.getDescriptorForClass(clazz));
} | @Test
public void testEmptySchema() {
assertEquals(
TestProtoSchemas.EMPTY_SCHEMA,
ProtoSchemaTranslator.getSchema(Proto3SchemaMessages.Empty.class));
} |
@Nullable public String linkLocalIp() {
// uses synchronized variant of double-checked locking as getting the endpoint can be expensive
if (linkLocalIp != null) return linkLocalIp;
synchronized (this) {
if (linkLocalIp == null) {
linkLocalIp = produceLinkLocalIp();
}
}
return lin... | @Test void linkLocalIp_sameInstance() {
Platform platform = new Platform.Jre7();
assertThat(platform.linkLocalIp()).isSameAs(platform.linkLocalIp());
} |
@Override
protected void requestSubpartitions() throws IOException {
boolean retriggerRequest = false;
boolean notifyDataAvailable = false;
// The lock is required to request only once in the presence of retriggered requests.
synchronized (requestLock) {
checkState(!isR... | @Test
void testRetriggerPartitionRequestWhilePartitionNotFound() throws Exception {
final SingleInputGate inputGate = createSingleInputGate(1);
final LocalInputChannel localChannel =
createLocalInputChannel(inputGate, new ResultPartitionManager(), 1, 1);
inputGate.setInputCh... |
public int getQueueInfoFailedRetrieved() {
return numGetQueueInfoFailedRetrieved.value();
} | @Test
public void testGetQueueInfoFailed() {
long totalBadBefore = metrics.getQueueInfoFailedRetrieved();
badSubCluster.getQueueInfo();
Assert.assertEquals(totalBadBefore + 1,
metrics.getQueueInfoFailedRetrieved());
} |
public static void bindEnvironment(ScriptEngine engine, String requestContent, Map<String, Object> requestContext,
StateStore stateStore) {
// Build a map of header values.
bindEnvironment(engine, requestContent, requestContext, stateStore, null);
} | @Test
void testRequestContentIsBound() {
String script = """
return mockRequest.requestContent;
""";
ScriptEngineManager sem = new ScriptEngineManager();
String body = "content";
try {
// Evaluating request with script coming from operation dispatcher rules.... |
public static <T> T getFirst(Iterable<T> iterable) {
if (iterable instanceof List) {
final List<T> list = (List<T>) iterable;
return CollUtil.isEmpty(list) ? null: list.get(0);
}
return getFirst(getIter(iterable));
} | @Test
public void getFirstTest() {
assertNull(IterUtil.getFirst((Iterable<Object>) null));
assertNull(IterUtil.getFirst(CollUtil.newArrayList()));
assertEquals("1", IterUtil.getFirst(CollUtil.newArrayList("1", "2", "3")));
final ArrayDeque<String> deque = new ArrayDeque<>();
deque.add("3");
deque.add("4")... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMultimap(k0, v0, rest));
} | @Test
public void containsAtLeastFailureWithEmptyStringMissing() {
expectFailureWhenTestingThat(ImmutableMultimap.of("key", "value")).containsAtLeast("", "a");
assertFailureKeys("missing", "---", "expected to contain at least", "but was");
assertFailureValue("missing", "{\"\" (empty String)=[a]}");
} |
public String getNetworkAddress() {
return this.startAddress.getHostAddress();
} | @Test
public void getNetworkAddress() {
assertThat(ipSubnet.getNetworkAddress()).isEqualTo(networkAddress);
} |
public int available() {
return buffer != null ? buffer.length - pos : 0;
} | @Test
public void testAvailable() {
int available = out.available();
out.buffer = null;
int availableWhenBufferNull = out.available();
assertEquals(10, available);
assertEquals(0, availableWhenBufferNull);
} |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFu... | @Test
void assertCreateWithOtherSelectStatementForNoResource() {
initProxyContext(Collections.emptyMap());
MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class);
when(selectStatement.getFrom()).thenReturn(Optional.empty());
ProjectionsSegment projectionsSegment = mo... |
public Iterable<TimestampedValue<T>> read() {
checkState(
!isClosed,
"OrderedList user state is no longer usable because it is closed for %s",
requestTemplate.getStateKey());
return readRange(Instant.ofEpochMilli(Long.MIN_VALUE), Instant.ofEpochMilli(Long.MAX_VALUE));
} | @Test
public void testNoPersistedValues() throws Exception {
FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient(Collections.emptyMap());
OrderedListUserState<String> userState =
new OrderedListUserState<>(
Caches.noop(),
fakeClient,
"instructionId",
... |
Collection<IndexRelationType> getRelations() {
return relations.values();
} | @Test
@UseDataProvider("indexWithAndWithoutRelations")
public void getRelations_returns_empty_if_no_relation_added(Index index) {
NewIndex<?> newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
assertThat(newIndex.getRelations()).isEmpty();
} |
@VisibleForTesting
static ExternalResourceInfoProvider createStaticExternalResourceInfoProvider(
Map<String, Long> externalResourceAmountMap,
Map<String, ExternalResourceDriver> externalResourceDrivers) {
final Map<String, Set<? extends ExternalResourceInfo>> externalResources = new ... | @Test
public void testGetExternalResourceInfoProvider() {
final Map<String, Long> externalResourceAmountMap = new HashMap<>();
final Map<String, ExternalResourceDriver> externalResourceDrivers = new HashMap<>();
externalResourceAmountMap.put(RESOURCE_NAME_1, RESOURCE_AMOUNT_1);
exter... |
@Override
public UserSession authenticate(HttpRequest request, HttpResponse response) {
UserAuthResult userAuthResult = loadUser(request, response);
if (nonNull(userAuthResult.getUserDto())) {
if (TOKEN.equals(userAuthResult.getAuthType())) {
return userSessionFactory.create(userAuthResult.getUs... | @Test
public void authenticate_from_basic_token() {
when(request.getHeader("Authorization")).thenReturn("Basic dGVzdDo=");
when(userTokenAuthentication.getUserToken("test")).thenReturn(A_USER_TOKEN);
when(userTokenAuthentication.authenticate(request)).thenReturn(Optional.of(new UserAuthResult(A_USER, A_US... |
public GsonAzureRepoList getRepos(String serverUrl, String token, @Nullable String projectName) {
String url = Stream.of(getTrimmedUrl(serverUrl), projectName, "_apis/git/repositories?" + API_VERSION_3)
.filter(StringUtils::isNotBlank)
.collect(joining("/"));
return doGet(token, url, r -> buildGson(... | @Test
public void get_repos_without_project_name() throws InterruptedException {
enqueueResponse(200, "{ \"value\": [], \"count\": 0 }");
GsonAzureRepoList repos = underTest.getRepos(server.url("").toString(), "token", null);
RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
Stri... |
@VisibleForTesting
ZonedDateTime parseZoned(final String text, final ZoneId zoneId) {
final TemporalAccessor parsed = formatter.parse(text);
final ZoneId parsedZone = parsed.query(TemporalQueries.zone());
ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply(
ObjectUtils.defaultIfNull(parsedZone... | @Test
public void shouldParseLeapDay() {
// Given
final String format = "yyyy-MM-dd'T'HH:mm:ss.SSS";
final String timestamp = "2012-12-31T23:59:58.660";
// When
final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID);
// Then
assertThat(ts, is(sameInstant(... |
@VisibleForTesting
String importSingleAlbum(UUID jobId, TokensAndUrlAuthData authData, PhotoAlbum inputAlbum)
throws IOException, InvalidTokenException, PermissionDeniedException, UploadErrorException {
// Set up album
GoogleAlbum googleAlbum = new GoogleAlbum();
googleAlbum.setTitle(GooglePhotosImp... | @Test
public void importAlbumWithITString()
throws PermissionDeniedException, InvalidTokenException, IOException, UploadErrorException {
String albumId = "Album Id";
String albumName = "Album Name";
String albumDescription = "Album Description";
PhotoAlbum albumModel = new PhotoAlbum(albumId, a... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if(directory.isRoot()) {
final AttributedList<Path> list = new AttributedList<>();
list.add(MYFILES_NAME);
list.add(SHARED_NAME);
... | @Test
public void testListMyFiles() throws Exception {
final AttributedList<Path> list = new OneDriveListService(session, fileid).list(OneDriveListService.MYFILES_NAME, new DisabledListProgressListener());
assertFalse(list.isEmpty());
for(Path f : list) {
assertEquals(OneDriveLis... |
static List<InetAddress> resolve(String host, HostResolver hostResolver) throws UnknownHostException {
InetAddress[] addresses = hostResolver.resolve(host);
List<InetAddress> result = filterPreferredAddresses(addresses);
if (log.isDebugEnabled())
log.debug("Resolved host {} as {}", h... | @Test
public void testResolveDnsLookup() throws UnknownHostException {
InetAddress[] addresses = new InetAddress[] {
InetAddress.getByName("198.51.100.0"), InetAddress.getByName("198.51.100.5")
};
HostResolver hostResolver = new AddressChangeHostResolver(addresses, addresses);
... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Check the request path and set the cache-control header if we find
// it matches what we're looking for.
if (request instanceof HttpServletRequest) {
... | @Test
public void test_cache_control_not_set() throws IOException, ServletException {
Mockito.when(servletRequest.getPathInfo()).thenReturn("/a/bc.js");
resourceCacheControl.doFilter(servletRequest, servletResponse, filterChain);
Mockito.verify(servletResponse, Mockito.never()).setHeader("Ca... |
@Override
public int partition(RowData row, int numPartitions) {
// reuse the sortKey and rowDataWrapper
sortKey.wrap(rowDataWrapper.wrap(row));
return SketchUtil.partition(sortKey, numPartitions, rangeBounds, comparator);
} | @Test
public void testRangePartitioningWithRangeBounds() {
SketchRangePartitioner partitioner =
new SketchRangePartitioner(TestFixtures.SCHEMA, SORT_ORDER, RANGE_BOUNDS);
GenericRowData row =
GenericRowData.of(StringData.fromString("data"), 0L, StringData.fromString("2023-06-20"));
for (lo... |
public DataTableDiff calculateDiffs() {
Map<Integer, Delta> deltasByLine = createDeltasByLine();
return createTableDiff(deltasByLine);
} | @Test
void should_not_fail_with_out_of_memory() {
DataTable expected = TableParser.parse("" +
"| I'm going to work |\n");
List<List<String>> actual = new ArrayList<>();
actual.add(singletonList("I just woke up"));
actual.add(singletonList("I'm going to work"));
... |
@Override
public RowData nextRecord(RowData reuse) {
// return the next row
row.setRowId(this.nextRow++);
return row;
} | @Test
void testReadFileWithSelectFields() throws IOException {
FileInputSplit[] splits = createSplits(testFileFlat, 4);
long cnt = 0;
long totalF0 = 0;
Map<String, Object> partSpec = new HashMap<>();
partSpec.put("f1", 1);
partSpec.put("f3", 3L);
partSpec.pu... |
public static Set<Integer> mapColumnToNode(Set<Integer> columnIndexes, List<OrcType> orcTypes)
{
requireNonNull(columnIndexes, "columnIndexes is null");
requireNonNull(orcTypes, "orcTypes is null");
if (columnIndexes.isEmpty()) {
return ImmutableSet.of();
}
OrcT... | @Test
public void testMapColumnToNodeEmpty()
{
Set<Integer> actual = mapColumnToNode(ImmutableSet.of(), ImmutableList.of());
assertTrue(actual.isEmpty());
} |
@Override
public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) {
ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id);
if (errorLog == null) {
throw exception(API_ERROR_LOG_NOT_FOUND);
}
if (!ApiErrorLogProcessStatusEnum.INIT.getSt... | @Test
public void testUpdateApiErrorLogProcess_processed() {
// 准备参数
ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class,
o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()));
apiErrorLogMapper.insert(apiErrorLogDO);
// 准备参数
Long id... |
public Set<String> getReferencedSearchFiltersIds(final Collection<UsesSearchFilters> searchFiltersOwners) {
return searchFiltersOwners
.stream()
.map(UsesSearchFilters::filters)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
... | @Test
void testGetReferencedSearchFiltersIdsReturnsEmptyCollectionOnEmptyOwners() {
final Set<String> referencedSearchFiltersIds = toTest.getReferencedSearchFiltersIds(ImmutableSet.of());
assertTrue(referencedSearchFiltersIds.isEmpty());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.