focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId,
Http2Headers headers, int padding, boolean endStream, ChannelPromise promise) {
return writeHeadersInternal(ctx, streamId, headers, padding, endStream,
false, 0, (short) 0, false, promise);
} | @Test
public void writeHeaders() throws Exception {
int streamId = 1;
Http2Headers headers = new DefaultHttp2Headers()
.method("GET").path("/").authority("foo.com").scheme("https");
frameWriter.writeHeaders(ctx, streamId, headers, 0, true, promise);
byte[] expectedP... |
@Override
protected TableRecords getUndoRows() {
return super.getUndoRows();
} | @Test
public void getUndoRows() {
Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage());
} |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final java.nio.file.Path p = session.toPath(file);
final Set<OpenOption> options = new HashSet<>();
options.... | @Test
public void testWriteSymlink() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
if(session.isPosixFilesystem()) {
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new Dis... |
public static void assertThatClassIsImmutable(Class<?> clazz) {
final ImmutableClassChecker checker = new ImmutableClassChecker();
if (!checker.isImmutableClass(clazz, false)) {
final Description toDescription = new StringDescription();
final Description mismatchDescription = new... | @Test
public void testFinalProtectedMember() throws Exception {
boolean gotException = false;
try {
assertThatClassIsImmutable(FinalProtectedMember.class);
} catch (AssertionError assertion) {
assertThat(assertion.getMessage(),
containsString("a... |
@Override
public V get(K key) {
return map.get(key);
} | @Test
public void testGet() {
map.put(42, "foobar");
String result = adapter.get(42);
assertEquals("foobar", result);
} |
public V put(final K key, final V value)
{
final Object val = mapNullValue(value);
requireNonNull(val, "value cannot be null");
final Object[] entries = this.entries;
final int mask = entries.length - 1;
int keyIndex = Hashing.evenHash(key.hashCode(), mask);
Object ... | @Test
void shouldCopyConstructAndBeEqual()
{
final int[] testEntries = { 3, 1, 19, 7, 11, 12, 7 };
final Object2ObjectHashMap<String, Integer> map = new Object2ObjectHashMap<>();
for (final int testEntry : testEntries)
{
map.put(String.valueOf(testEntry), testEntry);... |
@Override
public AttributedList<Path> run(final Session<?> session) throws BackgroundException {
// Run recursively
final Search feature = session.getFeature(Search.class);
if(log.isDebugEnabled()) {
log.debug(String.format("Run with feature %s", feature));
}
retu... | @Test
public void testRun() throws Exception {
final PathCache cache = new PathCache(Integer.MAX_VALUE);
final AttributedList<Path> root = new AttributedList<>();
root.add(new Path("/t1.png", EnumSet.of(Path.Type.file)));
root.add(new Path("/t1.gif", EnumSet.of(Path.Type.file)));
... |
@Override
public boolean publishConfigCas(String key, String group, String content, Object ticket) {
try {
if (ticket != null && !(ticket instanceof Stat)) {
throw new IllegalArgumentException("zookeeper publishConfigCas requires stat type ticket");
}
Stri... | @Test
void testPublishConfigCas() {
String key = "user-service-cas";
String group = "org.apache.dubbo.service.UserService";
String content = "test";
ConfigItem configItem = configuration.getConfigItem(key, group);
assertTrue(configuration.publishConfigCas(key, group, content,... |
public static String normalize(final String path) {
return normalize(path, true);
} | @Test
public void testNormalize() {
assertEquals(PathNormalizer.normalize("relative/path", false), "relative/path");
assertEquals(PathNormalizer.normalize("/absolute/path", true), "/absolute/path");
assertEquals(PathNormalizer.normalize("/absolute/path", false), "/absolute/path");
} |
public boolean hasReadPermissionForWholeCollection(final Subject subject,
final String collection) {
return readPermissionForCollection(collection)
.map(rp -> rp.equals(DbEntity.ALL_ALLOWED) || subject.isPermitted(rp + ":*"))
... | @Test
void hasReadPermissionForWholeCollectionReturnsTrueWhenCatalogHasAllAllowedPermission() {
doReturn(Optional.of(
new DbEntityCatalogEntry("streams", "title", StreamImpl.class, DbEntity.ALL_ALLOWED))
).when(catalog)
.getByCollectionName("streams");
final ... |
@Override
@Deprecated
@SuppressWarnings("unchecked")
public <T extends Number> Counter<T> counter(String name, Class<T> type, Unit unit) {
if (Integer.class.equals(type)) {
return (Counter<T>) new DefaultCounter(unit).asIntCounter();
}
if (Long.class.equals(type)) {
return (Counter<T>) ne... | @Test
public void longCounter() {
MetricsContext metricsContext = new DefaultMetricsContext();
MetricsContext.Counter<Long> counter =
metricsContext.counter("longCounter", Long.class, MetricsContext.Unit.COUNT);
counter.increment(5L);
assertThat(counter.value()).isEqualTo(5L);
assertThat(c... |
public static ExternalSorter create(Options options) {
return options.getSorterType() == Options.SorterType.HADOOP
? HadoopExternalSorter.create(options)
: NativeExternalSorter.create(options);
} | @Test
public void testRandom() throws Exception {
SorterTestUtils.testRandom(
() ->
ExternalSorter.create(
new ExternalSorter.Options()
.setTempLocation(getTmpLocation().toString())
.setSorterType(sorterType)),
1,
1000000)... |
public Connection getConnection() {
return getConfig().isShared() ? pooledConnection() : singleUseConnection();
} | @Test
public void should_return_same_connection_when_shared() throws Exception {
DataConnectionConfig config = new DataConnectionConfig(SHARED_DATA_CONNECTION_CONFIG)
.setProperty("maximumPoolSize", "1");
jdbcDataConnection = new JdbcDataConnection(config);
connection1 = jd... |
@Override
public Map<String, String> contextLabels() {
return Collections.unmodifiableMap(contextLabels);
} | @Test
public void testCreationWithNullNamespaceAndLabels() {
context = new KafkaMetricsContext(null, labels);
assertEquals(2, context.contextLabels().size());
assertNull(context.contextLabels().get(MetricsContext.NAMESPACE));
assertEquals(LABEL_A_VALUE, context.contextLabels().get(L... |
public static void checkTdg(String tenant, String dataId, String group) throws NacosException {
checkTenant(tenant);
if (StringUtils.isBlank(dataId) || !ParamUtils.isValid(dataId)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, DATAID_INVALID_MSG);
}
if (Stri... | @Test
void testCheckTdgFail1() throws NacosException {
Throwable exception = assertThrows(NacosException.class, () -> {
String tenant = "a";
String dataId = "";
String group = "c";
ParamUtils.checkTdg(tenant, dataId, group);
});
as... |
public ConfigCheckResult checkConfig() {
Optional<Long> appId = getAppId();
if (appId.isEmpty()) {
return failedApplicationStatus(INVALID_APP_ID_STATUS);
}
GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDe... | @Test
public void checkConfig_whenInstallationsDoesntHaveOrgMembersPermissions_shouldReturnFailedAppAutoProvisioningCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
mockGithubAppWithValidConfig(appCo... |
static JSONArray parseFirstEntries(final InputStream inputStream, final int count) throws ExecutionException, InterruptedException
{
final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
final JSONArray result = new JSONArray();
final Docu... | @Test
public void testRssParsing() throws Exception
{
// Setup test fixture.
try (final InputStream rssStream = BlogPostServlet.class.getResourceAsStream("/rss/ignite-blog.rss")) {
// Execute system under test.
final JSONArray result = BlogPostServlet.parseFirstEntries(r... |
public static <T> RestResult<T> failed() {
return RestResult.<T>builder().withCode(500).build();
} | @Test
void testFailedWithDefault() {
RestResult<Object> restResult = RestResultUtils.failed();
assertRestResult(restResult, 500, null, null, false);
} |
@Override
public String decrypt(String cipherText) throws CryptoException {
return decrypt(cipherProvider.getKey(), cipherText);
} | @Test
public void shouldDecryptText() throws CryptoException {
String plainText = desEncrypter.decrypt("mvcX9yrQsM4iPgm1tDxN1A==");
assertThat(plainText).isEqualTo("user-password!");
} |
@Override
public boolean putIfAbsent(K key, V value) {
return map.putIfAbsent(key, value) == null;
} | @Test
public void testPutIfAbsent() {
map.put(42, "oldValue");
assertTrue(adapter.putIfAbsent(23, "newValue"));
assertFalse(adapter.putIfAbsent(42, "newValue"));
assertEquals("newValue", map.get(23));
assertEquals("oldValue", map.get(42));
} |
@Override
public ServerSocketEndpointConfig setName(String name) {
super.setName(name);
return this;
} | @Test
public void testEndpointConfig_defaultConstructor() {
endpointConfig = new ServerSocketEndpointConfig();
endpointConfig.setName(endpointName);
assertEquals(endpointName, endpointConfig.getName());
// assertNull(endpointConfig.getMemberAddressProviderConfig());
assertNull... |
@Override
public KvMetadata resolveMetadata(
boolean isKey,
List<MappingField> resolvedFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe... | @Test
public void test_resolveMetadata() {
KvMetadata metadata = INSTANCE.resolveMetadata(
isKey,
List.of(
field("string", QueryDataType.VARCHAR),
field("boolean", QueryDataType.BOOLEAN),
field("byte", Qu... |
@Override
public Future<Void> notifyCheckpointAbortAsync(
long checkpointId, long latestCompletedCheckpointId) {
return notifyCheckpointOperation(
() -> {
if (latestCompletedCheckpointId > 0) {
notifyCheckpointComplete(latestCompletedCh... | @Test
void testSavepointTerminateAbortedAsync() {
assertThatThrownBy(
() ->
testSyncSavepointWithEndInput(
(streamTask, abortCheckpointId) ->
streamTask.notifyCheck... |
@Override
public boolean removeProperties(Namespace namespace, Set<String> properties)
throws NoSuchNamespaceException {
if (!namespaceExists(namespace)) {
throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace);
}
Preconditions.checkNotNull(properties, "Invalid properti... | @Test
public void testRemoveProperties() {
Namespace testNamespace = Namespace.of("testDb", "ns1", "ns2");
Map<String, String> testMetadata =
ImmutableMap.of(
"key_1", "value_1", "key_2", "value_2", "key_3", "value_3", "key_4", "value_4");
catalog.createNamespace(testNamespace, testMet... |
static void validateConnectors(KafkaMirrorMaker2 kafkaMirrorMaker2) {
if (kafkaMirrorMaker2.getSpec() == null) {
throw new InvalidResourceException(".spec section is required for KafkaMirrorMaker2 resource");
} else {
if (kafkaMirrorMaker2.getSpec().getClusters() == null ||... | @Test
public void testValidation() {
assertDoesNotThrow(() -> KafkaMirrorMaker2Connectors.validateConnectors(KMM2));
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.OAUTH_CLIENT,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 key,不好清理
public void deleteOAuth2Client(Long id) {
// 校验存在
validateOAuth2ClientExists(id);
// 删除
oauth2ClientMapper.deleteById(id);
} | @Test
public void testDeleteOAuth2Client_success() {
// mock 数据
OAuth2ClientDO dbOAuth2Client = randomPojo(OAuth2ClientDO.class);
oauth2ClientMapper.insert(dbOAuth2Client);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbOAuth2Client.getId();
// 调用
oauth2ClientServic... |
public QProfileChangeDto toDto(@Nullable String userUuid) {
QProfileChangeDto dto = new QProfileChangeDto();
dto.setChangeType(type.name());
dto.setRulesProfileUuid(getKey().getRuleProfileUuid());
dto.setUserUuid(userUuid);
Map<String, String> data = new HashMap<>();
data.put("ruleUuid", getRule... | @Test
public void toDto() {
QProfileDto profile = newQualityProfileDto();
ActiveRuleKey key = ActiveRuleKey.of(profile, RuleKey.of("P1", "R1"));
String ruleUuid = Uuids.createFast();
ActiveRuleChange underTest = new ActiveRuleChange(ACTIVATED, key, new RuleDto().setUuid(ruleUuid));
QProfileChange... |
public String stringify(boolean value) {
throw new UnsupportedOperationException(
"stringify(boolean) was called on a non-boolean stringifier: " + toString());
} | @Test
public void testTimeStringifier() {
for (PrimitiveStringifier stringifier : asList(TIME_STRINGIFIER, TIME_UTC_STRINGIFIER)) {
String timezoneAmendment = (stringifier == TIME_STRINGIFIER ? "" : "+0000");
assertEquals(withZoneString("00:00:00.000", timezoneAmendment), stringifier.stringify(0));
... |
public synchronized boolean doChannelCloseEvent(final String remoteAddr, final Channel channel) {
boolean removed = false;
if (channel != null) {
for (final Map.Entry<String, ConcurrentHashMap<Channel, ClientChannelInfo>> entry : this.groupChannelTable
.entrySet()) {
... | @Test
public void doChannelCloseEvent() throws Exception {
producerManager.registerProducer(group, clientInfo);
AtomicReference<String> groupRef = new AtomicReference<>();
AtomicReference<ClientChannelInfo> clientChannelInfoRef = new AtomicReference<>();
producerManager.appendProduce... |
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) {
if(input.getOptionValues(action.name()).length == 2) {
switch(action) {
case download:
return new DownloadTransferItemFinder().find(input, action... | @Test
public void testDownloadFileToDirectoryTarget() throws Exception {
final CommandLineParser parser = new PosixParser();
final String temp = System.getProperty("java.io.tmpdir");
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--download", "ftps://t... |
public static void main(final String[] args) {
SpringApplication.run(App.class, args);
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
private List<MySQLPreparedStatementParameterType> getNewParameterTypes(final int paramCount) {
List<MySQLPreparedStatementParameterType> result = new ArrayList<>(paramCount);
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
MySQLBinaryColumnType columnType = MySQLBinaryColum... | @Test
void assertNewWithoutParameter() {
byte[] data = {0x01, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00};
MySQLPacketPayload payload = new MySQLPacketPayload(Unpooled.wrappedBuffer(data), StandardCharsets.UTF_8);
MySQLComStmtExecutePacket actual = new MySQLComStmtExecutePacket(payload, ... |
@Override
public void warn(String msg) {
logger.warn(msg);
logWarnToJobDashboard(msg);
} | @Test
void testWarnLoggingWithoutJob() {
jobRunrDashboardLogger.warn("simple message");
verify(slfLogger).warn("simple message");
} |
public String addFilterForChannel(
final String id, final int priority, final Predicate predicate, final String endpoint,
final String channel, final boolean update) {
return addFilterForChannel(createFilter(id, priority, predicate, endpoint, new PrioritizedFilterStatistics(id)),
... | @Test
void testUpdateFilterDoesNotExist() {
String result = filterService.addFilterForChannel(prioritizedFilter, DYNAMIC_ROUTER_CHANNEL, true);
assertEquals("Error: Filter could not be updated -- existing filter found with matching ID: false", result);
} |
@Override
public MaterializedTable nonWindowed() {
return new KsqlMaterializedTable(inner.nonWindowed());
} | @Test
public void shouldFilterNonWindowed_fullScan() {
// Given:
final MaterializedTable table = materialization.nonWindowed();
givenNoopProject();
when(filter.apply(any(), any(), any())).thenReturn(Optional.empty());
// When:
final Iterator<Row> result = table.get(partition);
// Then:
... |
@Operation(summary = "Get single service")
@GetMapping(value = "name/{name}", produces = "application/json")
@ResponseBody
public Service getByName(@PathVariable("name") String name) {
return serviceService.getServiceByName(name);
} | @Test
public void serviceNameNotFound() {
when(serviceServiceMock.getServiceByName(anyString())).thenThrow(NotFoundException.class);
assertThrows(NotFoundException.class, () -> {
controller.getByName("test");
});
} |
@SuppressWarnings("unchecked")
protected final <E> boolean emitFromTraverser(@Nonnull int[] ordinals, @Nonnull Traverser<E> traverser) {
E item;
if (pendingItem != null) {
item = (E) pendingItem;
pendingItem = null;
} else {
item = traverser.next();
... | @Test
public void when_emitFromTraverserTo1_then_emittedTo1() {
// Given
Traverser<Object> trav = Traversers.traverseItems(MOCK_ITEM, MOCK_ITEM);
boolean done;
do {
// When
done = p.emitFromTraverser(ORDINAL_1, trav);
// Then
validateR... |
public static StreamExecutionEnvironment getExecutionEnvironment() {
return getExecutionEnvironment(new Configuration());
} | @Test
void testBufferTimeoutByDefault() {
Configuration config = new Configuration();
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
testBufferTimeout(config, env);
} |
@SqlNullable
@Description("Return the closest points on the two geometries")
@ScalarFunction("geometry_nearest_points")
@SqlType("array(" + GEOMETRY_TYPE_NAME + ")")
public static Block geometryNearestPoints(@SqlType(GEOMETRY_TYPE_NAME) Slice left, @SqlType(GEOMETRY_TYPE_NAME) Slice right)
{
... | @Test
public void testGeometryNearestPoints()
{
assertNearestPoints("POINT (50 100)", "POINT (150 150)", "POINT (50 100)", "POINT (150 150)");
assertNearestPoints("MULTIPOINT (50 100, 50 200)", "POINT (50 100)", "POINT (50 100)", "POINT (50 100)");
assertNearestPoints("LINESTRING (50 100... |
@Override
public int diff(String... names) {
return get(diffAsync(names));
} | @Test
public void testDiff() {
RSet<Integer> set = redisson.getSet("set");
set.add(5);
set.add(6);
RSet<Integer> set1 = redisson.getSet("set1");
set1.add(1);
set1.add(2);
set1.add(3);
RSet<Integer> set2 = redisson.getSet("set2");
set2.add(3);
... |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_SINT24_BE() {
final MutableData data = new MutableData(new byte[3]);
data.setValue(0xfefdfd, Data.FORMAT_UINT24_BE, 0);
assertArrayEquals(new byte[] { (byte) 0xFE, (byte) 0xFD, (byte) 0xFD } , data.getValue());
} |
public void configure(ReadableConfig configuration, ClassLoader classLoader) {
configuration.getOptional(PipelineOptions.GENERIC_TYPES).ifPresent(this::setGenericTypes);
configuration.getOptional(PipelineOptions.FORCE_KRYO).ifPresent(this::setForceKryo);
configuration.getOptional(PipelineOptions... | @Test
void testReadingDefaultConfig() {
SerializerConfig config = new SerializerConfigImpl();
Configuration configuration = new Configuration();
// mutate config according to configuration
config.configure(configuration, SerializerConfigImplTest.class.getClassLoader());
ass... |
public static Pair<List<RowData>, String[]> transposeColumnStatsIndex(List<RowData> colStats, String[] queryColumns, RowType tableSchema) {
Map<String, LogicalType> tableFieldTypeMap = tableSchema.getFields().stream()
.collect(Collectors.toMap(RowType.RowField::getName, RowType.RowField::getType));
//... | @Test
void testTransposeColumnStatsIndex() throws Exception {
final String path = tempFile.getAbsolutePath();
Configuration conf = TestConfigurations.getDefaultConf(path);
conf.setBoolean(FlinkOptions.METADATA_ENABLED, true);
conf.setBoolean(FlinkOptions.READ_DATA_SKIPPING_ENABLED, true);
conf.set... |
public static <T> T[] getCombinationAnnotations(AnnotatedElement annotationEle, Class<T> annotationType) {
return getAnnotations(annotationEle, true, annotationType);
} | @Test
public void getCombinationAnnotationsWithClassTest(){
final AnnotationForTest[] annotations = AnnotationUtil.getCombinationAnnotations(ClassWithAnnotation.class, AnnotationForTest.class);
assertNotNull(annotations);
assertEquals(1, annotations.length);
assertTrue(annotations[0].value().equals("测试") || an... |
public StreamsResponse getKinesisStreamNames(AWSRequest request) throws ExecutionException {
LOG.debug("List Kinesis streams for region [{}]", request.region());
final KinesisClient kinesisClient = awsClientBuilderUtil.buildClient(kinesisClientBuilder, request);
ListStreamsRequest streamsRequ... | @Test
public void testGetStreams() throws ExecutionException {
when(awsClientBuilderUtil.buildClient(any(KinesisClientBuilder.class), any())).thenReturn(kinesisClient);
// Test with two streams and one page. This is the most common case for most AWS accounts.
when(kinesisClient.listStreams... |
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
// tagging like maxweight:conditional=no/none @ destination/delivery/forestry/service
String condValue = way.getTag("maxweight:conditional", "");
if (!condValue.isEmpty()) {
Str... | @Test
public void testSimpleTags() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
ReaderWay readerWay = new ReaderWay(1);
readerWay.setTag("highway", "primary");
readerWay.setTag("maxweight:conditional", "none @delivery");
parser.handleWayTags(edgeId, edgeIntAcces... |
public static TaskExecutorMemoryConfiguration create(Configuration config) {
return new TaskExecutorMemoryConfiguration(
getConfigurationValue(config, FRAMEWORK_HEAP_MEMORY),
getConfigurationValue(config, TASK_HEAP_MEMORY),
getConfigurationValue(config, FRAMEWORK_... | @Test
void testInitialization() {
Configuration config = new Configuration();
config.set(FRAMEWORK_HEAP_MEMORY, new MemorySize(1));
config.set(TASK_HEAP_MEMORY, new MemorySize(2));
config.set(FRAMEWORK_OFF_HEAP_MEMORY, new MemorySize(3));
config.set(TASK_OFF_HEAP_MEMORY, new... |
@Override
public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) {
super.pre(span, exchange, endpoint);
String contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
if (contentType != null) {
span.setTag(SERVICEBUS_CONTENT_TYPE, contentType);
... | @Test
public void testPre() {
String contentType = "application/json";
String correlationId = "1234";
Long deliveryCount = 27L;
Long enqueuedSequenceNumber = 1L;
OffsetDateTime enqueuedTime = OffsetDateTime.now();
OffsetDateTime expiresAt = OffsetDateTime.now();
... |
@Override
public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) {
do {
Token token = tokenQueue.poll();
matchedTokenList.add(token);
if (uptoMatchTokens.contains(token.getValue())) {
return true;
}
} while (tokenQueue.peek() != null);
return false;
... | @Test
public void shouldNotMatch() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token("b", 2, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2)));
List<Token> output = mock(List.class);
UptoTokenMatcher matcher = new UptoTokenMatcher(new String[] { ";" });
assertThat(m... |
ControllerResult<Map<String, ApiError>> updateFeatures(
Map<String, Short> updates,
Map<String, FeatureUpdate.UpgradeType> upgradeTypes,
boolean validateOnly
) {
TreeMap<String, ApiError> results = new TreeMap<>();
List<ApiMessageAndVersion> records =
BoundedL... | @Test
public void testCanUseSafeDowngradeIfMetadataDidNotChange() {
FeatureControlManager manager = new FeatureControlManager.Builder().
setQuorumFeatures(features(MetadataVersion.FEATURE_NAME,
MetadataVersion.IBP_3_0_IV0.featureLevel(), MetadataVersion.IBP_3_3_IV1.fe... |
@Override
public int multiplication(int n1, int n2) {
int n5 = n1 * n2;
return n5;
} | @Test
public void testMultiplication() {
Controlador controlador = new Controlador();
int result = controlador.multiplication(2, 3);
assertEquals(6, result);
} |
public Map<String, String> findTableNames(final Collection<ColumnSegment> columns, final ShardingSphereSchema schema) {
if (1 == simpleTables.size()) {
return findTableNameFromSingleTable(columns);
}
Map<String, String> result = new CaseInsensitiveMap<>();
Map<String, Collect... | @Test
void assertFindTableNameWhenColumnSegmentOwnerAbsentAndSchemaMetaDataContainsColumnInUpperCase() {
SimpleTableSegment tableSegment1 = createTableSegment("TABLE_1", "TBL_1");
SimpleTableSegment tableSegment2 = createTableSegment("TABLE_2", "TBL_2");
ShardingSphereTable table = new Shard... |
public Iterator<T> getBookmark() {
LinkedSetIterator toRet = new LinkedSetIterator();
toRet.next = this.bookmark.next;
this.bookmark = toRet;
return toRet;
} | @Test(timeout=60000)
public void testBookmarkAdvancesOnRemoveOfSameElement() {
LOG.info("Test that the bookmark advances if we remove its element.");
assertTrue(set.add(list.get(0)));
assertTrue(set.add(list.get(1)));
assertTrue(set.add(list.get(2)));
Iterator<Integer> it = set.getBookmark();
... |
public static String toHexStringWithPrefixZeroPadded(BigInteger value, int size) {
return toHexStringZeroPadded(value, size, true);
} | @Test
public void testToHexStringWithPrefixZeroPadded() {
assertEquals(Numeric.toHexStringWithPrefixZeroPadded(BigInteger.ZERO, 5), ("0x00000"));
assertEquals(
Numeric.toHexStringWithPrefixZeroPadded(
new BigInteger("01c52b08330e05d731e38c856c1043288f7d9744",... |
protected FileStatus[] listStatus(JobConf job) throws IOException {
Path[] dirs = getInputPaths(job);
if (dirs.length == 0) {
throw new IOException("No input paths specified in job");
}
// get tokens for all the required FileSystems..
TokenCache.obtainTokensForNamenodes(job.getCredentials(), ... | @Test
public void testListStatusNestedRecursive() throws IOException {
Configuration conf = new Configuration();
conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads);
List<Path> expectedPaths = org.apache.hadoop.mapreduce.lib.input.TestFileInputFormat
.configureTestNestedRecursive(con... |
@CanIgnoreReturnValue
public JsonElement set(int index, JsonElement element) {
return elements.set(index, element == null ? JsonNull.INSTANCE : element);
} | @Test
public void testSet() {
JsonArray array = new JsonArray();
assertThrows(IndexOutOfBoundsException.class, () -> array.set(0, new JsonPrimitive(1)));
JsonPrimitive a = new JsonPrimitive("a");
array.add(a);
JsonPrimitive b = new JsonPrimitive("b");
JsonElement oldValue = array.set(0, b);
... |
@Override
public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff)
throws IOException, InterruptedException {
IOException lastException = null;
do {
try {
// Match inputPath which may contains glob
Collection<Metadata> files =
Iterables.getOnlyElement... | @Test
public void testReadCustomTemplate() throws Exception {
String contents1 = "To be or not to be, ", contents2 = "it is not a question.";
// Customized template: resultSSS-totalNNN
File tmpFile1 = tmpFolder.newFile("result0-total2");
File tmpFile2 = tmpFolder.newFile("result1-total2");
Files.... |
public List<String> getNamingAddrs() {
String namingAddrsKey = String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, NAMING_SERVICE_URL_KEY);
String urlListStr = FILE_CONFIG.getConfig(namingAddrsKey);
if (urlListStr.isEmpty()) {
throw new NamingRegistryException("Na... | @Test
public void getNamingAddrsTest() {
NamingserverRegistryServiceImpl namingserverRegistryService = NamingserverRegistryServiceImpl.getInstance();
List<String> list = namingserverRegistryService.getNamingAddrs();
assertEquals(list.size(), 1);
} |
@Override
public boolean start() throws IOException {
LOG.info("Starting reader using {}", initCheckpoint);
try {
shardSubscribersPool = createPool();
shardSubscribersPool().start(initCheckpoint);
return advance();
} catch (TransientKinesisException e) {
throw new IOException(e);
... | @Test
public void startReturnsTrueIfSomeDataAvailable() throws IOException {
when(subscribersPool.getNextRecord()).thenReturn(a).thenReturn(null);
assertThat(reader.start()).isTrue();
} |
public Span nextSpan(Message message) {
TraceContextOrSamplingFlags extracted =
extractAndClearTraceIdProperties(processorExtractor, message, message);
Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler.
// When an upstream context was not present, lookup keys are unl... | @Test void nextSpan_uses_current_context() {
Span child;
try (Scope scope = tracing.currentTraceContext().newScope(parent)) {
child = jmsTracing.nextSpan(message);
}
assertChildOf(child.context(), parent);
} |
static Set<String> getExpiredTopologyIds(Set<String> toposToClean, Map<String, Object> conf) {
Set<String> idleTopologies = new HashSet<>();
long topologyDeletionDelay = ObjectReader.getInt(
conf.get(DaemonConfig.NIMBUS_TOPOLOGY_BLOBSTORE_DELETION_DELAY_MS), 5 * 60 * 1000);
for (... | @Test
public void uploadedBlobPersistsMinimumTime() {
Set<String> idleTopologies = new HashSet<>();
idleTopologies.add("topology1");
Map<String, Object> conf = new HashMap<>();
conf.put(DaemonConfig.NIMBUS_TOPOLOGY_BLOBSTORE_DELETION_DELAY_MS, 300000);
try (Time.SimulatedTim... |
public void autoConfig() throws JoranException {
autoConfig(Configurator.class.getClassLoader());
} | @Test
public void autoConfigFromServiceLoaderJDK5() throws Exception {
assumeTrue(isJDK5());
ClassLoader mockClassLoader = buildMockServiceLoader(this.getClass().getClassLoader());
assertNull(MockConfigurator.context);
new ContextInitializer(loggerContext).autoConfig(mockClassLoader)... |
@GetMapping("/{id}/{namespaceId}")
public ShenyuAdminResult detailSelector(@PathVariable("id") @Valid
@Existed(provider = SelectorMapper.class, message = "selector is not existed") final String id,
@PathVariable("namespaceId") @... | @Test
public void detailSelector() throws Exception {
SpringBeanUtils.getInstance().setApplicationContext(mock(ConfigurableApplicationContext.class));
when(SpringBeanUtils.getInstance().getBean(NamespaceMapper.class)).thenReturn(namespaceMapper);
when(namespaceMapper.existed(SYS_DEFAULT_NAM... |
@Override
public Endpoint<Http2RemoteFlowController> remote() {
return remoteEndpoint;
} | @Test
public void removeAllStreamsWithJustOneRemoveStream() throws Exception {
client.remote().createStream(2, false);
testRemoveAllStreams();
} |
public static StringUtils.Pair toParentAndLeaf(String path) {
int pos = path.lastIndexOf('.');
int temp = path.lastIndexOf("['");
if (temp != -1 && temp > pos) {
pos = temp - 1;
}
String right = path.substring(pos + 1);
if (right.startsWith("[")) {
... | @Test
void testParsingParentAndLeafName() {
assertEquals(StringUtils.pair("", "$"), Json.toParentAndLeaf("$"));
assertEquals(StringUtils.pair("$", "foo"), Json.toParentAndLeaf("$.foo"));
assertEquals(StringUtils.pair("$", "['foo']"), Json.toParentAndLeaf("$['foo']"));
assertEquals(St... |
public boolean addNewShard(final Shard shard) {
var shardId = shard.getId();
if (!shardMap.containsKey(shardId)) {
shardMap.put(shardId, shard);
return true;
} else {
return false;
}
} | @Test
void testAddNewShard() {
try {
var shard = new Shard(1);
shardManager.addNewShard(shard);
var field = ShardManager.class.getDeclaredField("shardMap");
field.setAccessible(true);
var map = (Map<Integer, Shard>) field.get(shardManager);
assertEquals(1, map.size());
as... |
public static boolean isPojo(Class<?> cls) {
return !ReflectUtils.isPrimitives(cls)
&& !Collection.class.isAssignableFrom(cls)
&& !Map.class.isAssignableFrom(cls);
} | @Test
void testIsPojo() throws Exception {
assertFalse(PojoUtils.isPojo(boolean.class));
assertFalse(PojoUtils.isPojo(Map.class));
assertFalse(PojoUtils.isPojo(List.class));
assertTrue(PojoUtils.isPojo(Person.class));
} |
@Override
public void deleteRewardActivity(Long id) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(id);
if (!dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 未关闭的活动,不能删除噢
throw exception(REWARD_ACTIVITY_DELETE_FA... | @Test
public void testDeleteRewardActivity_success() {
// mock 数据
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()));
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
// 准备参数
... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseNull() {
SchemaAndValue schemaAndValue = Values.parseString("null");
assertNull(schemaAndValue);
} |
public static List<UpdateRequirement> forUpdateTable(
TableMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid table metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Bui... | @Test
public void setDefaultSortOrderFailure() {
int sortOrderId = SortOrder.unsorted().orderId();
when(updated.defaultSortOrderId()).thenReturn(sortOrderId + 1);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.Set... |
@Override
public Hotspots.HotspotLite generateClosedIssueMessage(String uuid) {
return Hotspots.HotspotLite.newBuilder()
.setKey(uuid)
.setClosed(true)
.build();
} | @Test
public void generateClosedIssueMessage_shouldMapClosedHotspotFields() {
HotspotLite result = underTest.generateClosedIssueMessage("uuid");
assertThat(result).extracting(HotspotLite::getKey, HotspotLite::getClosed)
.containsExactly("uuid", true);
} |
public static Cluster bootstrap(List<InetSocketAddress> addresses) {
List<Node> nodes = new ArrayList<>();
int nodeId = -1;
for (InetSocketAddress address : addresses)
nodes.add(new Node(nodeId--, address.getHostString(), address.getPort()));
return new Cluster(null, true, no... | @Test
public void testBootstrap() {
String ipAddress = "140.211.11.105";
String hostName = "www.example.com";
Cluster cluster = Cluster.bootstrap(Arrays.asList(
new InetSocketAddress(ipAddress, 9002),
new InetSocketAddress(hostName, 9002)
));
Set<Strin... |
public static Types.StructType selectNot(Types.StructType struct, Set<Integer> fieldIds) {
Set<Integer> projectedIds = getIdsInternal(struct, false);
projectedIds.removeAll(fieldIds);
return project(struct, projectedIds);
} | @Test
public void testSelectNot() {
Schema schema =
new Schema(
Lists.newArrayList(
required(1, "id", Types.LongType.get()),
required(
2,
"location",
Types.StructType.of(
require... |
public Map<TopicPartition, Long> endOffsets(Set<TopicPartition> partitions) {
if (partitions == null || partitions.isEmpty()) {
return Collections.emptyMap();
}
Map<TopicPartition, OffsetSpec> offsetSpecMap = partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> Off... | @Test
public void endOffsetsShouldFailWithUnsupportedVersionWhenVersionUnsupportedErrorOccurs() {
String topicName = "myTopic";
TopicPartition tp1 = new TopicPartition(topicName, 0);
Set<TopicPartition> tps = Collections.singleton(tp1);
Long offset = null; // response should use erro... |
@Override
public String getBasePath() {
ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
return servlet.getBasePath();
} finally {
Thread.currentThread().setConte... | @Test
public void testWrapper() throws Exception {
AdditionalServlet servlet = mock(AdditionalServlet.class);
NarClassLoader loader = mock(NarClassLoader.class);
AdditionalServletWithClassLoader wrapper = new AdditionalServletWithClassLoader(servlet, loader);
String basePath = "metr... |
public String defaultBranchName() {
return defaultBranchName;
} | @Test
public void defaultBranchName() {
for (int i = 0; i <= nonMainBranches.size(); i++) {
List<BranchInfo> branches = new ArrayList<>(nonMainBranches);
branches.add(i, mainBranch);
assertThat(new ProjectBranches(branches).defaultBranchName()).isEqualTo(mainBranch.name());
}
} |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldRunCtStatement() {
// Given:
final PreparedStatement<CreateTable> ct = PreparedStatement.of("CT",
new CreateTable(SOME_NAME, SOME_ELEMENTS, false, false, JSON_PROPS,
false));
givenQueryFileParsesTo(ct);
// When:
standaloneExecutor.startAsync();
//... |
@Override
public ObjectNode encode(MappingAction action, CodecContext context) {
EncodeMappingActionCodecHelper encoder =
new EncodeMappingActionCodecHelper(action, context);
return encoder.encode();
} | @Test
public void forwardActionTest() {
final ForwardMappingAction action = MappingActions.forward();
final ObjectNode actionJson = actionCodec.encode(action, context);
assertThat(actionJson, matchesAction(action));
} |
public ProviderCert getProviderConnectionConfig(URL localAddress, SocketAddress remoteAddress) {
for (CertProvider certProvider : certProviders) {
if (certProvider.isSupport(localAddress)) {
ProviderCert cert = certProvider.getProviderConnectionConfig(localAddress);
i... | @Test
void testGetProviderConnectionConfig() {
CertManager certManager = new CertManager(frameworkModel);
Assertions.assertNull(certManager.getProviderConnectionConfig(url, null));
ProviderCert providerCert1 = Mockito.mock(ProviderCert.class);
FirstCertProvider.setProviderCert(prov... |
@Override
public Lock lock() {
return locker.lock();
} | @Test
void whileLockedJobCannotBeLockedForOtherSaveAction() {
Job job = anEnqueuedJob().build();
final AtomicBoolean atomicBoolean = new AtomicBoolean();
final Lock lock = job.lock();
await()
.during(1, TimeUnit.SECONDS)
.atMost(2, TimeUnit.SECONDS)
... |
protected void readLine(URL url, String line) {
String[] aliasAndClassName = parseAliasAndClassName(line);
if (aliasAndClassName == null || aliasAndClassName.length != 2) {
return;
}
String alias = aliasAndClassName[0];
String className = aliasAndClassName[1];
... | @Test
public void testReadLine() throws Exception {
ExtensionLoader loader = new ExtensionLoader<Filter>(Filter.class, false, null);
URL url = Filter.class.getResource("/META-INF/sofa-rpc/" + Filter.class.getName());
try {
loader.readLine(url, "com.alipay.sofa.rpc.ext.NotFilter")... |
public static void checkValuesEqual(
long value1,
String value1Name,
long value2,
String value2Name) {
checkArgument(
value1 == value2,
"'%s' (%s) must equal '%s' (%s).",
value1Name,
value1,
value2Name,
value2);
} | @Test
public void testCheckValuesEqual() throws Exception {
// Should not throw.
Validate.checkValuesEqual(1, "arg1", 1, "arg2");
// Verify it throws.
intercept(IllegalArgumentException.class,
"'arg1' (1) must equal 'arg2' (2)",
() -> Validate.checkValuesEqual(1, "arg1", 2, "arg2"));... |
public static SerdeFeatures buildInternal(final Format keyFormat) {
final ImmutableSet.Builder<SerdeFeature> builder = ImmutableSet.builder();
getKeyWrapping(true, keyFormat)
.ifPresent(builder::add);
return SerdeFeatures.from(builder.build());
} | @Test
public void shouldNotSetUnwrappedKeysIfInternalTopicHasKeyFormatsSupportsOnlyWrapping() {
// When:
final SerdeFeatures result = SerdeFeaturesFactory.buildInternal(PROTOBUF);
// Then:
assertThat(result.findAny(SerdeFeatures.WRAPPING_FEATURES), is(Optional.empty()));
} |
public static Configuration unix() {
return UnixHolder.UNIX;
} | @Test
public void testFileSystemWithDefaultWatchService() throws IOException {
FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
WatchService watchService = fs.newWatchService();
assertThat(watchService).isInstanceOf(PollingWatchService.class);
PollingWatchService pollingWatchService = (Pol... |
public String toTypeString() {
// needs a map instead of switch because for some reason switch creates an
// internal class with no annotations that messes up EntityTest
return Optional.ofNullable(TO_TYPE_STRING.getOrDefault(type, si -> si.type.name()))
.orElseThrow(NullPointerException::new).apply(... | @Test
public void shouldCorrectlyFormatDecimalsWithoutParameters() {
final SchemaInfo schemaInfo= new SchemaInfo(
SqlBaseType.DECIMAL,
null,
null
);
assertThat(schemaInfo.toTypeString(), equalTo("DECIMAL"));
} |
@Override
public boolean acquirePermit(String nsId) {
if (contains(nsId)) {
return super.acquirePermit(nsId);
}
return super.acquirePermit(DEFAULT_NS);
} | @Test
public void testAcquireTimeout() {
Configuration conf = createConf(40);
conf.setDouble(DFS_ROUTER_FAIR_HANDLER_PROPORTION_KEY_PREFIX + "ns1", 0.5);
conf.setTimeDuration(DFS_ROUTER_FAIRNESS_ACQUIRE_TIMEOUT, 100, TimeUnit.MILLISECONDS);
RouterRpcFairnessPolicyController routerRpcFairnessPolicyCont... |
public static void main(String[] args) {
MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai");
MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo");
fighter1.fight(fighter2);
MmaHeavyweightFighter... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static Optional<String> convertRegexToLiteral(String s) {
try {
Pattern.compile(s);
} catch (PatternSyntaxException e) {
/* The string is a malformed regular expression which will throw an error at runtime. We will
* preserve this behavior by not rewriting it.
*/
return Op... | @Test
public void positive() {
assertThat(Regexes.convertRegexToLiteral("hello")).hasValue("hello");
assertThat(Regexes.convertRegexToLiteral("\\t\\n\\f\\r")).hasValue("\t\n\f\r");
assertThat(Regexes.convertRegexToLiteral("\\Q.\\E")).hasValue(".");
} |
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) {
if (operation.getOperationResponseHandler() != null) {
throw new IllegalArgumentException("Operation must not have a response handler set");
}
if (!operation.returnsResponse())... | @Test(expected = IllegalArgumentException.class)
public void executeLocallyWithRetryFailsWhenOperationHandlerIsSet() {
final Operation op = new Operation() {
};
op.setOperationResponseHandler(new OperationResponseHandler() {
@Override
public void sendResponse(Operatio... |
@Override
public PartitionContainer getPartitionContainer(int partitionId) {
assert partitionId != GENERIC_PARTITION_ID : "Cannot be called with GENERIC_PARTITION_ID";
return partitionContainers[partitionId];
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testGetPartitionContainer_withGenericPartitionId() {
mapServiceContext.getPartitionContainer(GENERIC_PARTITION_ID);
} |
public static Predicate parse(String expression)
{
final Stack<Predicate> predicateStack = new Stack<>();
final Stack<Character> operatorStack = new Stack<>();
final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll("");
final StringTokenizer tokenizer = new StringTokenizer(tr... | @Test
public void testParen()
{
final Predicate parsed = PredicateExpressionParser.parse("(com.linkedin.data.it.AlwaysTruePredicate)");
Assert.assertEquals(parsed.getClass(), AlwaysTruePredicate.class);
} |
public static MySQLBinlogProtocolValue getBinlogProtocolValue(final MySQLBinaryColumnType columnType) {
Preconditions.checkArgument(BINLOG_PROTOCOL_VALUES.containsKey(columnType), "Cannot find MySQL type '%s' in column type when process binlog protocol value", columnType);
return BINLOG_PROTOCOL_VALUES.... | @Test
void assertGetBinlogProtocolValue() {
assertThat(MySQLBinlogProtocolValueFactory.getBinlogProtocolValue(MySQLBinaryColumnType.TINY), instanceOf(MySQLTinyBinlogProtocolValue.class));
} |
public static void notifyConfigChange(ConfigDataChangeEvent event) {
if (DatasourceConfiguration.isEmbeddedStorage() && !EnvUtil.getStandaloneMode()) {
return;
}
NotifyCenter.publishEvent(event);
} | @Test
void testConfigChangeNotify() throws InterruptedException {
AtomicReference<ConfigDataChangeEvent> reference = new AtomicReference<>();
NotifyCenter.registerToPublisher(ConfigDataChangeEvent.class, NotifyCenter.ringBufferSize);
NotifyCenter.registerSubscriber(new Subs... |
@Override
public void onAddedJobGraph(JobID jobId) {
runIfStateIs(State.RUNNING, () -> handleAddedJobGraph(jobId));
} | @Test
void onAddedJobGraph_failingRecovery_propagatesTheFailure() throws Exception {
final FlinkException expectedFailure = new FlinkException("Expected failure");
jobGraphStore =
TestingJobGraphStore.newBuilder()
.setRecoverJobGraphFunction(
... |
@Override
public boolean databaseExists(SnowflakeIdentifier database) {
Preconditions.checkArgument(
database.type() == SnowflakeIdentifier.Type.DATABASE,
"databaseExists requires a DATABASE identifier, got '%s'",
database);
final String finalQuery = "SHOW SCHEMAS IN DATABASE IDENTIFI... | @Test
public void testDatabaseFailureWithOtherException() throws SQLException {
Exception injectedException = new SQLException("Some other exception", "2000", 2, null);
when(mockResultSet.next()).thenThrow(injectedException);
assertThatExceptionOfType(UncheckedSQLException.class)
.isThrownBy(() -... |
public static <T extends Iterable<E>, E> T filter(T iter, Filter<E> filter) {
if (null == iter) {
return null;
}
filter(iter.iterator(), filter);
return iter;
} | @Test
public void filterTest(){
final List<String> obj2 = ListUtil.toList("3");
final List<String> obj = ListUtil.toList("1", "3");
IterUtil.filter(obj.iterator(), obj2::contains);
assertEquals(1, obj.size());
assertEquals("3", obj.get(0));
} |
public synchronized boolean memberLeave(Collection<Member> members) {
Set<Member> set = new HashSet<>(allMembers());
set.removeAll(members);
return memberChange(set);
} | @Test
void testMemberLeave() {
Member member = Member.builder().ip("1.1.3.3").port(8848).state(NodeState.DOWN).build();
boolean joinResult = serverMemberManager.memberJoin(Collections.singletonList(member));
assertTrue(joinResult);
List<String> ips = serverMemberManager.getS... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void streamStreamLeftJoinTopologyWithDefaultStoresNames() {
final StreamsBuilder builder = new StreamsBuilder();
final KStream<Integer, String> stream1;
final KStream<Integer, String> stream2;
stream1 = builder.stream("input-topic1");
stream2 = builder.stream("... |
@Override
public RFuture<String> scriptLoadAsync(String luaScript) {
List<CompletableFuture<String>> futures = commandExecutor.executeAllAsync(RedisCommands.SCRIPT_LOAD, luaScript);
CompletableFuture<Void> f = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
CompletableFut... | @Test
public void testScriptLoadAsync() {
redisson.getBucket("foo").set("bar");
RFuture<String> r = redisson.getScript().scriptLoadAsync("return redis.call('get', 'foo')");
Assertions.assertEquals("282297a0228f48cd3fc6a55de6316f31422f5d17", r.toCompletableFuture().join());
String r1 ... |
protected static boolean isValidHexQuantity(String value) {
if (value == null) {
return false;
}
if (value.length() < 3) {
return false;
}
if (!value.startsWith(HEX_PREFIX)) {
return false;
}
return value.matches("0[xX][0-9a-... | @Test
void testIsValidHexQuantity() {
assertEquals(true, Numeric.isValidHexQuantity("0x0"));
assertEquals(true, Numeric.isValidHexQuantity("0x9"));
assertEquals(true, Numeric.isValidHexQuantity("0x123f"));
assertEquals(true, Numeric.isValidHexQuantity("0x419E"));
assertEqual... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.