focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <K, V extends OrderedSPI<?>> Map<K, V> getServices(final Class<V> serviceInterface, final Collection<K> types) {
return getServices(serviceInterface, types, Comparator.naturalOrder());
} | @SuppressWarnings("rawtypes")
@Test
void assertGetServices() {
OrderedInterfaceFixtureImpl key = new OrderedInterfaceFixtureImpl();
Map<OrderedInterfaceFixtureImpl, OrderedSPIFixture> actual = OrderedSPILoader.getServices(OrderedSPIFixture.class, Collections.singleton(key));
assertThat(a... |
@Override
public boolean isInputConsumable(
SchedulingExecutionVertex executionVertex,
Set<ExecutionVertexID> verticesToDeploy,
Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) {
for (ConsumedPartitionGroup consumedPartitionGroup :
executionVert... | @Test
void testNotFinishedHybridInput() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
final List<TestingSchedulingExecutionVertex> producers =
topology.addExecutionVertices().withParallelism(2).finish();
final List<TestingSchedulingExecutionV... |
public StateMachine<T> next(T nextState) throws IllegalStateException {
Set<T> allowed = transitions.get(currentState);
checkNotNull(allowed, "No transitions from state " + currentState);
checkState(allowed.contains(nextState), "Transition not allowed from state " + currentState + " to " + nextS... | @Test(expected = IllegalStateException.class)
public void testThrowsException_whenTransitionInvalid() {
machine.next(State.C);
} |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void literal() throws ScanException {
Tokenizer tokenizer = new Tokenizer("abc");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.LITERAL, "abc");
assertEquals(witness, node);
} |
@Description("removes whitespace from the beginning of a string")
@ScalarFunction("ltrim")
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice leftTrim(@SqlType("varchar(x)") Slice slice)
{
return SliceUtf8.leftTrim(slice);
} | @Test
public void testLeftTrim()
{
assertFunction("LTRIM('')", createVarcharType(0), "");
assertFunction("LTRIM(' ')", createVarcharType(3), "");
assertFunction("LTRIM(' hello ')", createVarcharType(9), "hello ");
assertFunction("LTRIM(' hello')", createVarcharType(7), "hel... |
@Override
public YamlUserConfiguration swapToYamlConfiguration(final ShardingSphereUser data) {
if (null == data) {
return null;
}
YamlUserConfiguration result = new YamlUserConfiguration();
result.setUser(data.getGrantee().toString());
result.setPassword(data.get... | @Test
void assertSwapToNullYamlConfiguration() {
assertNull(new YamlUserSwapper().swapToYamlConfiguration(null));
} |
@Override
public Capabilities getCapabilities(String pluginId) {
String resolvedExtensionVersion = pluginManager.resolveExtensionVersion(pluginId, CONFIG_REPO_EXTENSION, goSupportedVersions);
if (resolvedExtensionVersion.equals("1.0")) {
return new Capabilities(false, false, false, false... | @Test
public void shouldRequestCapabilitiesV1() {
Capabilities capabilities = new Capabilities(false, false, false, false);
Capabilities res = extension.getCapabilities(PLUGIN_ID);
assertThat(capabilities, is(res));
} |
@Udf(description = "Returns the INT base raised to the INT exponent.")
public Double power(
@UdfParameter(
value = "base",
description = "the base of the power."
) final Integer base,
@UdfParameter(
value = "exponent",
... | @Test
public void shouldHandleZeroExponent() {
assertThat(udf.power(15, 0), closeTo(1.0, 0.000000000000001));
assertThat(udf.power(15L, 0L), closeTo(1.0, 0.000000000000001));
assertThat(udf.power(15.0, 0.0), closeTo(1.0, 0.000000000000001));
assertThat(udf.power(0, 0), closeTo(1.0, 0.000000000000001))... |
@Override
public void fail(Throwable failureCause) {
synchronized (lock) {
if (isFailed) {
return;
}
isFailed = true;
BufferIndexOrError bufferIndexOrError;
// empty from tail, in-case subpartition view consumes concurrently and get... | @Test
void testFail() throws Exception {
AtomicInteger numOfNotify = new AtomicInteger(0);
subpartitionOperation.setNotifyDataAvailableRunnable(numOfNotify::incrementAndGet);
HsSubpartitionFileReaderImpl subpartitionFileReader = createSubpartitionFileReader();
Deque<BufferIndexOrErro... |
public static SignalNoiseRatio[] fit(DataFrame data, String clazz) {
BaseVector<?, ?, ?> y = data.column(clazz);
ClassLabels codec = ClassLabels.fit(y);
if (codec.k != 2) {
throw new UnsupportedOperationException("Signal Noise Ratio is applicable only to binary classification");
... | @Test
public void testDefault() {
System.out.println("Default");
SignalNoiseRatio[] s2n = SignalNoiseRatio.fit(Default.data, "default");
assertEquals(2, s2n.length);
assertEquals(1.1832, s2n[0].s2n, 1E-4);
assertEquals(0.0545, s2n[1].s2n, 1E-4);
} |
@Override
public boolean isTracked(String key) {
return OpType.fromSymbol(key) != null;
} | @Test
public void testIsTracked() {
assertFalse(statistics.isTracked(null));
assertFalse(statistics.isTracked(NO_SUCH_OP));
final Iterator<LongStatistic> iter = statistics.getLongStatistics();
while (iter.hasNext()) {
final LongStatistic longStatistic = iter.next();
assertTrue(statistics.... |
public static void delete(File fileOrDir) throws IOException {
if (fileOrDir == null) {
return;
}
if (fileOrDir.isDirectory()) {
cleanDirectory(fileOrDir);
} else {
if (fileOrDir.exists()) {
boolean isDeleteOk = fileOrDir.delet... | @Test
void testDeleteSuccess() throws IOException {
File file = null;
try {
file = File.createTempFile("test_deleteForFile", ".txt");
assertTrue(file.exists());
IoUtils.delete(file);
assertFalse(file.exists());
} finally {
if (null ... |
public String format(Date then)
{
if (then == null)
then = now();
Duration d = approximateDuration(then);
return format(d);
} | @Test
public void testNullDate() throws Exception
{
PrettyTime t = new PrettyTime();
Date date = null;
Assert.assertEquals("moments from now", t.format(date));
} |
public static String getParent(String url) {
String ensUrl = url != null ? url.trim() : "";
if (ensUrl.equals(".") || !ensUrl.contains(".")) {
return null;
}
return ensUrl.substring(ensUrl.indexOf(".") + 1);
} | @Test
void getParentWhenUrlWithoutParent() {
assertNull(EnsUtils.getParent("parent"));
} |
@Override
public Map<String, StepTransition> translate(WorkflowInstance workflowInstance) {
WorkflowInstance instance = objectMapper.convertValue(workflowInstance, WorkflowInstance.class);
if (instance.getRunConfig() != null) {
if (instance.getRunConfig().getPolicy() == RunPolicy.RESTART_FROM_INCOMPLET... | @Test
public void testTranslateForRestartFromIncompleteWithNotCreatedSteps() {
instance
.getAggregatedInfo()
.getStepAggregatedViews()
.put("job3", StepAggregatedView.builder().status(StepInstance.Status.NOT_CREATED).build());
instance.getRunConfig().setPolicy(RunPolicy.RESTART_FROM_IN... |
public GroupForbidden updateAndGetGroupForbidden(String addr, UpdateGroupForbiddenRequestHeader requestHeader,
long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.... | @Test
public void assertUpdateAndGetGroupForbidden() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
GroupForbidden responseBody = new GroupForbidden();
responseBody.setGroup(group);
responseBody.setTopic(defaultTopic);
setResponseBody(re... |
public static Guess performGuess(List<Date> releaseDates) {
if (releaseDates.size() <= 1) {
return new Guess(Schedule.UNKNOWN, null, null);
} else if (releaseDates.size() > MAX_DATA_POINTS) {
releaseDates = releaseDates.subList(releaseDates.size() - MAX_DATA_POINTS, releaseDates.... | @Test
public void testDaily() {
ArrayList<Date> releaseDates = new ArrayList<>();
releaseDates.add(makeDate("2024-01-01 16:30")); // Monday
releaseDates.add(makeDate("2024-01-02 16:25"));
releaseDates.add(makeDate("2024-01-03 16:35"));
releaseDates.add(makeDate("2024-01-04 16... |
public List<Map<String, Object>> run(String query) {
return this.run(query, Collections.emptyMap());
} | @Test
public void testRunShouldThrowErrorIfDriverFailsToRunQuery() {
doThrow(ClientException.class).when(session).run(anyString(), anyMap());
assertThrows(
Neo4jResourceManagerException.class,
() ->
testManager.run(
"MATCH (n) WHERE n < $val RETURN n LIMIT 1", Coll... |
@Override
public void startWatching() {
if (settings.getProps().valueAsBoolean(ENABLE_STOP_COMMAND.getKey())) {
super.startWatching();
}
} | @Test
public void watch_stop_command_if_stop_command_is_enabled() {
TestAppSettings appSettings = new TestAppSettings(of(ENABLE_STOP_COMMAND.getKey(), "true"));
StopRequestWatcherImpl underTest = new StopRequestWatcherImpl(appSettings, scheduler, commands);
underTest.startWatching();
assertThat(under... |
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) {
final String storeName = storeQueryParameters.storeName();
final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType();
final List<T> globalStore = globalStoreProvider.stores(storeName, que... | @Test
public void shouldThrowExceptionWhenLookingForWindowStoreWithDifferentType() {
assertThrows(InvalidStateStoreException.class, () -> storeProvider.getStore(StoreQueryParameters.fromNameAndType(windowStore,
QueryableStoreTypes.keyValueStore())).get("1"));
} |
public static boolean validateCSConfiguration(
final Configuration oldConfParam, final Configuration newConf,
final RMContext rmContext) throws IOException {
// ensure that the oldConf is deep copied
Configuration oldConf = new Configuration(oldConfParam);
QueueMetrics.setConfigurationVa... | @Test
public void testValidateCSConfigDominantRCAbsoluteModeParentMaxMemoryExceeded()
throws Exception {
setUpMockRM(true);
RMContext rmContext = mockRM.getRMContext();
CapacitySchedulerConfiguration oldConfiguration = cs.getConfiguration();
CapacitySchedulerConfiguration newConfiguration =
... |
@VisibleForTesting
List<String> getFuseInfo() {
return mFuseInfo;
} | @Test
public void UnderFileSystemS3A() {
try (FuseUpdateChecker checker = getUpdateCheckerWithUfs("s3a://alluxio-test/")) {
Assert.assertTrue(containsTargetInfo(checker.getFuseInfo(), "s3a"));
}
} |
public static boolean urlEquals(String string1, String string2) {
Uri url1 = Uri.parse(string1);
Uri url2 = Uri.parse(string2);
if (url1 == null || url2 == null || url1.getHost() == null || url2.getHost() == null) {
return string1.equals(string2); // Unable to parse url properly
... | @Test
public void testUrlEqualsDifferent() {
assertFalse(UrlChecker.urlEquals("https://www.example.com/test", "https://www.example2.com/test"));
assertFalse(UrlChecker.urlEquals("https://www.example.com/test", "https://www.example.de/test"));
assertFalse(UrlChecker.urlEquals("https://example... |
@Override
public DistroData getDatumSnapshot() {
List<ClientSyncData> datum = new LinkedList<>();
for (String each : clientManager.allClientId()) {
Client client = clientManager.getClient(each);
if (null == client || !client.isEphemeral()) {
continue;
... | @Test
void testGetDatumSnapshot() {
when(clientManager.allClientId()).thenReturn(Collections.singletonList(CLIENT_ID));
DistroData actual = distroClientDataProcessor.getDatumSnapshot();
assertEquals(DataOperation.SNAPSHOT.name(), actual.getDistroKey().getResourceKey());
assertEquals(... |
@Override
public int messageSize() {
boolean useSegwit = hasWitnesses() && allowWitness(protocolVersion);
int size = 4; // version
if (useSegwit)
size += 2; // marker, flag
size += VarInt.sizeOf(inputs.size());
for (TransactionInput in : inputs)
size +... | @Test
public void testMessageSize() {
Transaction tx = new Transaction();
int length = tx.messageSize();
// add fake transaction input
TransactionInput input = new TransactionInput(null, ScriptBuilder.createEmpty().program(),
new TransactionOutPoint(0, Sha256Hash.ZER... |
@Override
public Processor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>> get() {
return new ContextualProcessor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>>() {
private KT... | @Test
public void shouldDeleteKeyAndPropagateFKV0() {
final MockProcessorContext<String, SubscriptionResponseWrapper<String>> context = new MockProcessorContext<>();
processor.init(context);
final SubscriptionWrapper<String> newValue = new SubscriptionWrapper<>(
new long[]{1L},
... |
private void printSourceDescription(final SourceDescription source) {
final boolean isTable = source.getType().equalsIgnoreCase("TABLE");
writer().println(String.format("%-20s : %s", "Name", source.getName()));
if (!source.isExtended()) {
printSchema(source.getWindowType(), source.getFields(), isTabl... | @Test
public void testPrintSourceDescription() {
// Given:
final List<FieldInfo> fields = buildTestSchema(
SqlTypes.BOOLEAN,
SqlTypes.INTEGER,
SqlTypes.BIGINT,
SqlTypes.DOUBLE,
SqlTypes.STRING,
SqlTypes.array(SqlTypes.STRING),
SqlTypes.map(SqlTypes.STRIN... |
public boolean saveToRepository( EngineMetaInterface meta ) throws KettleException {
return saveToRepository( meta, meta.getObjectId() == null );
} | @Test
public void saveToRepository() throws Exception {
JobMeta mockJobMeta = mock( JobMeta.class );
prepareSetSaveTests( spoon, log, mockSpoonPerspective, mockJobMeta, false, false, "NotMainSpoonPerspective", true,
true, "filename", null, true, false );
RepositoryDirectoryInterface dirMock = mock... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.for... | @Test
void dryrun_does_not_block() {
RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder()
.dryrun(true)
.defaultRule(new DefaultRule.Builder()
.action(DefaultRule.Action.Enum.BLOCK))
.build();
Metric metric = mock... |
@Override
public void updateNamespace(Namespace namespace) {
checkNotNull(namespace, ERR_NULL_NAMESPACE);
checkArgument(!Strings.isNullOrEmpty(namespace.getMetadata().getUid()),
ERR_NULL_NAMESPACE_UID);
k8sNamespaceStore.updateNamespace(namespace);
log.info(String.f... | @Test(expected = IllegalArgumentException.class)
public void testUpdateUnregisteredNamespace() {
target.updateNamespace(NAMESPACE);
} |
@Override
public Table getTable(String dbName, String tblName) {
JDBCTableName jdbcTable = new JDBCTableName(null, dbName, tblName);
return tableInstanceCache.get(jdbcTable,
k -> {
try (Connection connection = getConnection()) {
ResultSet c... | @Test
public void testGetTable2() {
// user/password are optional fields for jdbc.
properties.put(JDBCResource.USER, "");
properties.put(JDBCResource.PASSWORD, "");
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
Table table = jdbcMetadata.get... |
public Map<String, Object> convertToMap(final String json) {
Map<String, Object> map = GSON_MAP.fromJson(json, new TypeToken<Map<String, Object>>() {
}.getType());
if (MapUtils.isEmpty(map)) {
return map;
}
for (Map.Entry<String, Object> entry : map.... | @Test
public void testConvertToMap() {
List<Integer> innerList = ImmutableList.of(1, 2, 3);
Map<String, Object> innerMap = ImmutableMap.of("id", 123, "name", "shenyu");
Map<String, Object> map = ImmutableMap.of("code", 200, "message", "test",
"data", innerMap, "list", innerLi... |
@Override
public String name() {
return name;
} | @Test
public void testNotExposeTableProperties() {
Configuration conf = new Configuration();
conf.set("iceberg.hive.table-property-max-size", "0");
HiveTableOperations ops = new HiveTableOperations(conf, null, null, catalog.name(), DB_NAME, "tbl");
TableMetadata metadata = mock(TableMetadata.class);
... |
@Override
public double logp(double x) {
if (x <= 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
return (0.5 * nu1 - 1.0) * Math.log(x) - 0.5 * (nu1 + nu2) * Math.log(nu2 + nu1 * x) + fac;
} | @Test
public void testLogP() {
System.out.println("logP");
FDistribution instance = new FDistribution(10, 20);
instance.rand();
assertEquals(-12.74989, instance.logp(0.01), 1E-5);
assertEquals(-4.196589, instance.logp(0.1), 1E-6);
assertEquals(-2.121800, instance.logp... |
public static Optional<Class<?>> findPowerSerialize(Class<?>[] parameterTypes) {
if (ArrayUtils.isEmpty(parameterTypes)) {
return Optional.empty();
}
for (Class<?> clz : parameterTypes) {
final Class<?>[] interfaces = clz.getInterfaces();
if (ArrayUtils.isEm... | @Test
void findPowerSerialize() {
Class<?>[] contains = {AlarmConfig.class, ServerScheduleJobReq.class};
Class<?>[] notContains = {AlarmConfig.class};
final Optional<Class<?>> notContainsResult = RemoteUtils.findPowerSerialize(notContains);
log.info("[RemoteUtilsTest] notContainsRe... |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testAllFromPipelineOptions() {
// TODO: Java core test failing on windows, https://github.com/apache/beam/issues/20466
assumeFalse(SystemUtils.IS_OS_WINDOWS);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"All inherited interfaces ... |
public static LeaderElectionManagerConfig fromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(LeaderElectionManagerConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return ne... | @Test
public void testMissingAllRequired() {
Map<String, String> envVars = new HashMap<>();
envVars.put(LeaderElectionManagerConfig.ENV_VAR_LEADER_ELECTION_LEASE_NAMESPACE.key(), null);
envVars.put(LeaderElectionManagerConfig.ENV_VAR_LEADER_ELECTION_IDENTITY.key(), null);
envVars.put... |
public static boolean equal(String str1, String str2) {
if (str1 == null && str2 == null) {
return true;
}
if (str1 == null || str2 == null) {
return false;
}
return str1.equals(str2);
} | @Test
public void testEqual() {
String key = "test";
Assert.assertTrue(StringUtils.equal(key, key));
Assert.assertTrue(StringUtils.equalIgnoreCase(key, "Test"));
Assert.assertTrue(StringUtils.equalIgnoreCase(key, "teST"));
Assert.assertTrue(StringUtils.isEmpty(""));
A... |
public static Iterator<TransferableBlock> splitBlock(TransferableBlock block, DataBlock.Type type, int maxBlockSize) {
List<TransferableBlock> blockChunks = new ArrayList<>();
if (type == DataBlock.Type.ROW) {
// Use estimated row size, this estimate is not accurate and is used to estimate numRowsPerChunk... | @Test(dataProvider = "splitRowCountProvider")
public void testSplitBlockUtils(int splitRowCount)
throws Exception {
DataSchema dataSchema = getDataSchema();
// compare serialized split
int estRowSizeInBytes = dataSchema.size() * TEST_EST_BYTES_PER_COLUMN;
List<Object[]> rows = DataBlockTestUtils... |
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
this.jsonPath = jsonPath;
this.resultMatcher = resultMatcher;
} | @Test
public void shouldDescribeMismatchOfEvaluation() {
Matcher<? super ReadContext> matcher = withJsonPath("expensive", equalTo(3));
Description description = new StringDescription();
matcher.describeMismatch(BOOKS_JSON, description);
assertThat(description.toString(), containsStri... |
@Override
public boolean sendElectionMessage(int currentId, String content) {
var candidateList = findElectionCandidateInstanceList(currentId);
if (candidateList.isEmpty()) {
return true;
} else {
var electionMessage = new Message(MessageType.ELECTION_INVOKE, "");
candidateList.forEach((... | @Test
void testSendElectionMessageNotAccepted() {
try {
var instance1 = new BullyInstance(null, 1, 1);
var instance2 = new BullyInstance(null, 1, 2);
var instance3 = new BullyInstance(null, 1, 3);
var instance4 = new BullyInstance(null, 1, 4);
Map<Integer, Instance> instanceMap = Map... |
@CheckReturnValue
@NonNull public static Observable<Boolean> observePowerSavingState(
@NonNull Context context, @StringRes int enablePrefResId, @BoolRes int defaultValueResId) {
final RxSharedPrefs prefs = AnyApplication.prefs(context);
return Observable.combineLatest(
prefs
... | @Test
@Config(sdk = Build.VERSION_CODES.LOLLIPOP)
public void testWhenLowPowerSavingModeWithDevicePowerSavingState() {
Context context = Mockito.spy(getApplicationContext());
final PowerManager powerManager =
(PowerManager) getApplicationContext().getSystemService(Service.POWER_SERVICE);
Mockito... |
@Override
public void revert(final Path file) throws BackgroundException {
new B2CopyFeature(session, fileid).copy(file, file, new TransferStatus(), new DisabledLoginCallback(), new DisabledStreamListener());
} | @Test
public void testRevert() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path room = new B2DirectoryFeature(session, fileid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.v... |
public Map<Endpoint, CompletableFuture<Void>> futures() {
return futures;
} | @Test
public void testAddReadinessFutures() {
Map<Endpoint, CompletableFuture<Void>> bazFutures = new HashMap<>();
bazFutures.put(EXTERNAL, new CompletableFuture<>());
bazFutures.put(INTERNAL, new CompletableFuture<>());
EndpointReadyFutures readyFutures = new EndpointReadyFutures.Bu... |
@Override
public Supplier<Predicate> compilePredicate(SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, RowExpression predicate)
{
if (predicateCache == null) {
return compilePredicateInternal(sqlFunctionProperties, sessionFunctions, predic... | @Test
public void testCache()
{
// a * 2 < 10
RowExpression predicate = call(
"=",
functionResolution.comparisonFunction(LESS_THAN, BIGINT, BIGINT),
BOOLEAN,
call("a * 2", functionResolution.arithmeticFunction(MULTIPLY, BIGINT, BIGI... |
@HighFrequencyInvocation
public Optional<EncryptAlgorithm> findEncryptor(final String logicColumnName) {
return columns.containsKey(logicColumnName) ? Optional.of(columns.get(logicColumnName).getCipher().getEncryptor()) : Optional.empty();
} | @Test
void assertNotFindEncryptorName() {
assertFalse(encryptTable.findEncryptor("notExistLogicColumn").isPresent());
} |
@Override
public LeaderElection createLeaderElection(String componentId) {
synchronized (lock) {
Preconditions.checkState(
!leadershipOperationExecutor.isShutdown(),
"The service was already closed and cannot be reused.");
Preconditions.checkSt... | @Test
void testLazyDriverInstantiation() throws Exception {
final AtomicBoolean driverCreated = new AtomicBoolean();
try (final DefaultLeaderElectionService testInstance =
new DefaultLeaderElectionService(
listener -> {
driverCreate... |
public static DataSource createDataSource(final ModeConfiguration modeConfig) throws SQLException {
return createDataSource(DefaultDatabase.LOGIC_NAME, modeConfig);
} | @Test
void assertCreateDataSourceWithAllParametersForSingleDataSourceWithDefaultDatabaseName() throws SQLException {
assertDataSource(ShardingSphereDataSourceFactory.createDataSource(
new ModeConfiguration("Standalone", null), new MockedDataSource(), new LinkedList<>(), new Properties()), De... |
@Override
public OverlayData createOverlayData(ComponentName remoteApp) {
final OverlayData original = mOriginal.createOverlayData(remoteApp);
if (original.isValid() || mFixInvalid) {
final int backgroundLuminance = luminance(original.getPrimaryColor());
final int diff = backgroundLuminance - lumi... | @Test
public void testReturnsFixedToWhiteIfDarkIfTextIsTooClose() {
OverlayData original = setupOriginal(Color.DKGRAY, Color.DKGRAY, Color.GRAY);
final OverlayData fixed = mUnderTest.createOverlayData(mTestComponent);
Assert.assertSame(original, fixed);
Assert.assertTrue(fixed.isValid());
Assert.a... |
static int readDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
// copy all the bytes that return immediately, stopping at the first
// read that doesn't return a full buffer.
int nextReadLength = Math.min(buf.remaining(), temp.length);
int totalBytesRead = 0;
int bytesR... | @Test
public void testDirectSmallTempBufferWithPositionAndLimit() throws Exception {
byte[] temp = new byte[2]; // this will cause readDirectBuffer to loop
ByteBuffer readBuffer = ByteBuffer.allocateDirect(20);
readBuffer.position(5);
readBuffer.limit(13);
readBuffer.mark();
MockInputStream ... |
@Udf
public String elt(
@UdfParameter(description = "the nth element to extract") final int n,
@UdfParameter(description = "the strings of which to extract the nth") final String... args
) {
if (args == null) {
return null;
}
if (n < 1 || n > args.length) {
return null;
}
... | @Test
public void shouldHandleNullArgs() {
// When:
String[] array = null;
final String el = elt.elt(2, array);
// Then:
assertThat(el, is(nullValue()));
} |
@Override
public ByteBuf setInt(int index, int value) {
throw new ReadOnlyBufferException();
} | @Test
public void testSetInt() throws IOException {
final ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try {
assertThrows(ReadOnlyBufferException.class, new Executable() {
@Override
public void execute() {
buf.setInt(0, 1);
... |
public static RuleDescriptionSectionContextDto of(String key, String displayName) {
return new RuleDescriptionSectionContextDto(key, displayName);
} | @Test
void equals_with_different_display_names_should_return_false() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
RuleDescriptionSectionContextDto context2 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME + "2");
... |
public long elapsedNanos() {
if (running) {
return this.ticks.ticks() - start;
} else {
if (elapsed == -1)
throw new IllegalStateException();
return elapsed;
}
} | @Test
void notStarted1() {
assertThrows(IllegalStateException.class, () -> {
FakeTicks f = new FakeTicks();
Stopwatch s = new Stopwatch(f);
s.elapsedNanos();
});
} |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @Test
public void parseJDkTest() {
final String dateStr = "Thu May 16 17:57:18 GMT+08:00 2019";
final DateTime time = DateUtil.parse(dateStr);
assertEquals("2019-05-16 17:57:18", Objects.requireNonNull(time).toString());
} |
@Override
public void upgrade() {
if (clusterConfigService.get(V202406260800_MigrateCertificateAuthority.MigrationCompleted.class) != null) {
LOG.debug("Migration already completed.");
return;
}
readExistingKeystore().ifPresent(keystore -> clusterConfigService.write(n... | @Test
void testMigration() {
mongodb.importFixture("V202406260800_MigrateCertificateAuthorityTest.json", V202406260800_MigrateCertificateAuthorityTest.class);
final ClusterConfigService clusterConfigService = Mockito.mock(ClusterConfigService.class);
final V202406260800_MigrateCertificateAut... |
public ApplicationReport getReport() {
return report;
} | @Test
public void testParseToReport() {
try {
YarnApplicationReport yarnReport = new YarnApplicationReport(runningReport);
ApplicationReport report = yarnReport.getReport();
Assert.assertEquals("application_15888888888_0088", report.getApplicationId().toString());
... |
@Override
public Graph<EntityDescriptor> resolveNativeEntity(EntityDescriptor entityDescriptor) {
final MutableGraph<EntityDescriptor> mutableGraph = GraphBuilder.directed().build();
mutableGraph.addNode(entityDescriptor);
final ModelId modelId = entityDescriptor.id();
try {
... | @Test
@MongoDBFixtures("PipelineFacadeTest/pipelines.json")
public void resolveEntityDescriptor() {
final Stage stage = Stage.builder()
.stage(0)
.match(Stage.Match.EITHER)
.ruleReferences(Collections.singletonList("no-op"))
.build();
... |
public <T> Future<Iterable<T>> bagFuture(
ByteString encodedTag, String stateFamily, Coder<T> elemCoder) {
// First request has no continuation position.
StateTag<Long> stateTag = StateTag.of(StateTag.Kind.BAG, encodedTag, stateFamily);
// Convert the ValuesAndContPosition<T> to Iterable<T>.
retur... | @Test
public void testReadBag() throws Exception {
Future<Iterable<Integer>> future = underTest.bagFuture(STATE_KEY_1, STATE_FAMILY, INT_CODER);
Mockito.verifyNoMoreInteractions(mockWindmill);
Windmill.KeyedGetDataRequest.Builder expectedRequest =
Windmill.KeyedGetDataRequest.newBuilder()
... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchSessionIdError() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
client.prepareResponse(fetchResponseWithTopLevelError(tidp0, Errors.FETCH_SESSION_TOPIC_ID_ERROR, 0));
networkCli... |
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
try {
List<Address> addressList = ConnectUtils.parse(config.getHostPort());
List<HostAndPort> hostAndPorts = new ArrayList<>();
for (Address address : addressList) {
... | @Test
public void prepareWithNonHost() throws Exception {
assertThrows(ModuleStartException.class, () -> provider.prepare());
} |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void petstoreBootstrap() throws Exception {
JwtClaims claims = ClaimsUtil.getTestCcClaimsScopeService("f7d42348-c647-4efb-a52d-4c5787421e72", "portal.r portal.w", "com.networknt.petstore-3.0.1");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jwt = JwtIssuer.getJwt(... |
@Override
public ExtensionMappingAddress mapLcafAddress(LispLcafAddress lcafAddress) {
switch (lcafAddress.getType()) {
case LIST:
LispListLcafAddress lcafListAddress = (LispListLcafAddress) lcafAddress;
MappingAddress ipv4Ma =
afi2mapping... | @Test
public void testMapLcafAddress() {
new EqualsTester()
.addEqualityGroup(listExtAddress, interpreter.mapLcafAddress(listLcafAddress))
.addEqualityGroup(segmentExtAddress, interpreter.mapLcafAddress(segmentLcafAddress))
.addEqualityGroup(asExtAddress, int... |
public static File load(String name) {
try {
if (name == null) {
throw new IllegalArgumentException("name can't be null");
}
String decodedPath = URLDecoder.decode(name, StandardCharsets.UTF_8.name());
return getFileFromFileSystem(decodedPath);
... | @Test
public void testLoadException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> FileLoader.load(null));
} |
public boolean hasRemainingEncodedBytes() {
// We delete an array after fully consuming it.
return encodedArrays != null && encodedArrays.size() != 0;
} | @Test
public void testHasRemainingEncodedBytes() {
byte[] bytes = {'a', 'b', 'c'};
long number = 12345;
// Empty
OrderedCode orderedCode = new OrderedCode();
assertFalse(orderedCode.hasRemainingEncodedBytes());
// First and only field of each type.
orderedCode.writeBytes(bytes);
asse... |
@Override
public boolean apply(InputFile f) {
if (path == null) {
return false;
}
return path.equals(f.relativePath());
} | @Test
public void returns_false_if_doesnt_match() {
RelativePathPredicate predicate = new RelativePathPredicate("path1");
InputFile inputFile = mock(InputFile.class);
when(inputFile.relativePath()).thenReturn("path2");
assertThat(predicate.apply(inputFile)).isFalse();
} |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldThrowWhenPartitionCountUnknown() {
setupTopicInMockAdminClient(topic1, repartitionTopicConfig());
final InternalTopicConfig internalTopicConfig = new RepartitionTopicConfig(topic1, Collections.emptyMap());
assertThrows(
IllegalStateException.class,
... |
@Udf
public <T> List<T> mapValues(final Map<String, T> input) {
if (input == null) {
return null;
}
return Lists.newArrayList(input.values());
} | @SuppressWarnings("unchecked")
@Test
public void shouldHandleComplexValueTypes() {
final Map<String, Map<String, List<Double>>> input = Maps.newHashMap();
final Map<String, List<Double>> entry1 = Maps.newHashMap();
entry1.put("apple", Arrays.asList(Double.valueOf(12.34), Double.valueOf(56.78)));
en... |
public Optional<String> getNodeName(String nodeId) {
return nodeNameCache.getUnchecked(nodeId);
} | @Test
public void getNodeNameUsesCache() {
when(cluster.nodeIdToName("node_id")).thenReturn(Optional.of("Node Name"));
nodeInfoCache.getNodeName("node_id");
nodeInfoCache.getNodeName("node_id");
verify(cluster, times(1)).nodeIdToName("node_id");
} |
public static Builder builder() {
return new AutoValue_HttpHeaders.Builder();
} | @Test
public void builderAddHeader_withIllegalHeaderValue_throwsIllegalArgumentException() {
assertThrows(
IllegalArgumentException.class,
() -> HttpHeaders.builder().addHeader("test_header", String.valueOf((char) 11)));
} |
@Override
public String toString() {
DdlResult ddlResult = this;
StringBuilder sb = new StringBuilder();
do {
sb.append(String.format("DdlResult [schemaName=%s , tableName=%s , oriSchemaName=%s , oriTableName=%s , type=%s ];",
ddlResult.schemaName,
... | @Test
public void toStringOutputNotNull() {
// Arrange
final DdlResult objectUnderTest = new DdlResult();
// Act
final String actual = objectUnderTest.toString();
// Assert result
Assert.assertEquals(
"DdlResult [schemaName=null , tableName=null , oriSchemaName=null , oriTableName=n... |
public static boolean isEntropyInjecting(FileSystem fs, Path target) {
final EntropyInjectingFileSystem entropyFs = getEntropyFs(fs);
return entropyFs != null
&& entropyFs.getEntropyInjectionKey() != null
&& target.getPath().contains(entropyFs.getEntropyInjectionKey());
... | @Test
void testIsEntropyFsWithNullEntropyKey() throws Exception {
final FileSystem efs = new TestEntropyInjectingFs(null, "ignored");
final File folder = TempDirUtils.newFolder(tempFolder);
assertThat(EntropyInjector.isEntropyInjecting(efs, Path.fromLocalFile(folder))).isFalse();
} |
@NonNull
public static String fullEncode(@NonNull String s) {
return encode(s, fullUriMap);
} | @Test
public void testFullEncode() {
String[] data = {
"abcdefghijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"01234567890!@$&*()-_=+',.",
"0123456... |
@Override
public BooleanPredicate clone() throws CloneNotSupportedException {
return (BooleanPredicate)super.clone();
} | @Test
void requireThatCloneIsImplemented() throws CloneNotSupportedException {
BooleanPredicate node1 = new BooleanPredicate(true);
BooleanPredicate node2 = node1.clone();
assertEquals(node1, node2);
assertNotSame(node1, node2);
} |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
trackTime(nowNs);
int workCount = 0;
workCount += processTimers(nowNs);
if (!asyncClientCommandInFlight)
{
workCount += clientCommandAdapter.receive();
}
workCount += drainComm... | @Test
void shouldRemoveCounterOnClientTimeout()
{
final long registrationId = driverProxy.addCounter(
COUNTER_TYPE_ID,
counterKeyAndLabel,
COUNTER_KEY_OFFSET,
COUNTER_KEY_LENGTH,
counterKeyAndLabel,
COUNTER_LABEL_OFFSET,
... |
@Override
public void close() throws InterruptedException {
beginShutdown();
for (Thread t : threads) {
t.join();
}
log.info("Event processor closed.");
} | @Test
public void testCreateAndClose() throws Exception {
CoordinatorEventProcessor eventProcessor = new MultiThreadedEventProcessor(
new LogContext(),
"event-processor-",
2,
Time.SYSTEM,
mock(CoordinatorRuntimeMetrics.class)
);
eve... |
public void handleMessage(
MessageExt messageExt) throws MQClientException, RemotingException, InterruptedException {
if (rocketMQListener != null) {
rocketMQListener.onMessage(doConvertMessage(messageExt));
} else if (rocketMQReplyListener != null) {
Object replyContent ... | @Test
public void testHandleMessage() throws Exception {
DefaultRocketMQListenerContainer listenerContainer = new DefaultRocketMQListenerContainer();
Method handleMessage = DefaultRocketMQListenerContainer.class.getDeclaredMethod("handleMessage", MessageExt.class);
handleMessage.setAccessibl... |
public synchronized void setSslTrustLevel(TrustLevel sslTrustLevel) {
if (sslTrustLevel != this.sslTrustLevel) {
this.sslTrustLevel = sslTrustLevel;
// force sslContext to be reinitialized with new trust level
sslContext = null;
}
} | @Test
public void testSslTrustLevel() throws Exception {
// default "open" trust level
CrawlURI curi = makeCrawlURI("https://localhost:7443/");
fetcher().process(curi);
runDefaultChecks(curi, "hostHeader");
// "normal" trust level
curi = makeCrawlURI("https:/... |
@Override
public MetadataStore create(String metadataURL, MetadataStoreConfig metadataStoreConfig,
boolean enableSessionWatcher) throws MetadataStoreException {
return new LocalMemoryMetadataStore(metadataURL, metadataStoreConfig);
} | @Test
public void testIsIgnoreEvent() throws Exception {
TestMetadataEventSynchronizer sync = new TestMetadataEventSynchronizer();
@Cleanup
AbstractMetadataStore store1 = (AbstractMetadataStore) MetadataStoreFactory.create("memory:local",
MetadataStoreConfig.builder().synchr... |
public static LatLong interpolateLatLong(LatLong p1, LatLong p2, double fraction) {
double maxLat = max(p1.latitude(), p2.latitude());
double minLat = min(p1.latitude(), p2.latitude());
checkArgument(maxLat - minLat <= 90.0, "Interpolation is unsafe at this distance (latitude)");
doubl... | @Test
public void testInterpolateLatLong() {
LatLong p1 = new LatLong(0.0, 5.0);
LatLong p2 = new LatLong(5.0, 0.0);
double TOLERANCE = 0.0001;
assertEquals(
0.0,
interpolateLatLong(p1, p2, 0.0).latitude(),
TOLERANCE
);
assertEqu... |
@Override
public <T> Task<T> synchronize(Task<T> task, long deadline) {
return PlanLocal.get(getPlanLocalKey(), LockInternal.class)
.flatMap(lockInternal -> {
if (lockInternal != null) {
// we already acquire the lock, add count only.
lockInternal._lockCount++;
... | @Test
public void testMultiLocks()
throws InterruptedException {
int loopCount = 100;
final long deadline = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS);
MultiLocks multiLocks1 = new MultiLocks(_zkClient, _acls, "/locks/l1", "/locks/l2", "/locks/l3");
MultiLoc... |
public static Optional<ESEventOriginContext> parseESContext(String url) {
if (url.startsWith(ES_EVENT) || url.startsWith(ES_MESSAGE)) {
final String[] tokens = url.split(":");
if (tokens.length != 6) {
return Optional.empty();
}
return Optional.of(... | @Test
public void parseShortESContext() {
assertThat(EventOriginContext.parseESContext("urn:graylog:message:es:ind")).isEmpty();
} |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldAddSourceStream() {
// Given:
final CreateStreamCommand cmd = buildCreateStream(
SourceName.of("t1"),
SCHEMA,
false,
true
);
// When:
cmdExec.execute(SQL_TEXT, cmd, true, NO_QUERY_SOURCES);
// Then:
final KsqlStream ksqlTable = (Ksq... |
public static MapperReference getMapper() {
return MAPPER_REFERENCE.get();
} | @Test
public void testResourceQuotaMixIn() {
ObjectMapper objectMapper = ObjectMapperFactory.getMapper().getObjectMapper();
try {
ResourceQuota resourceQuota = new ResourceQuota();
String json = objectMapper.writeValueAsString(resourceQuota);
Assert.assertFalse(js... |
public static L3ModificationInstruction decNwTtl() {
return new ModTtlInstruction(L3SubType.DEC_TTL);
} | @Test
public void testDecNwTtlOutMethod() {
final Instruction instruction = Instructions.decNwTtl();
final L3ModificationInstruction.ModTtlInstruction modTtlInstruction =
checkAndConvert(instruction,
Instruction.Type.L3MODIFICATION,
... |
public static String toString(String[] line, boolean quote) {
return toString(line, quote, " ");
} | @Test
void testToStringWithSeparator() {
final String separator = "], [";
assertEquals("", CommandLine.toString(null, false, separator));
assertEquals(ARG_SPACES_NOQUOTES,
CommandLine.toString(new String[]{ARG_SPACES_NOQUOTES}, false, separator));
assertEquals(ARG_S... |
public static ProtoOverrides.TransformReplacement createSizedReplacement() {
return SizedReplacement.builder().setDrain(false).build();
} | @Test
public void testSizedReplacement() {
Pipeline p = Pipeline.create();
p.apply(Create.of("1", "2", "3"))
.apply("TestSDF", ParDo.of(new PairStringWithIndexToLengthBase()));
RunnerApi.Pipeline proto = PipelineTranslation.toProto(p);
String transformName =
Iterables.getOnlyElement(
... |
@Override
public GenericRow transform(GenericRow record) {
for (Map.Entry<String, FunctionEvaluator> entry : _expressionEvaluators.entrySet()) {
String column = entry.getKey();
FunctionEvaluator transformFunctionEvaluator = entry.getValue();
Object existingValue = record.getValue(column);
... | @Test
public void testTransformFunctionWithWrongInput() {
Schema pinotSchema = new Schema();
DimensionFieldSpec dimensionFieldSpec = new DimensionFieldSpec("x", FieldSpec.DataType.INT, true);
pinotSchema.addField(dimensionFieldSpec);
List<TransformConfig> transformConfigs = Collections.singletonList(
... |
public ImmutableList<GlobalSetting> parse(final InputStream is) {
return Jsons.toObjects(is, GlobalSetting.class);
} | @Test
public void should_parse_setting_file_with_env() {
InputStream stream = getResourceAsStream("settings/env-settings.json");
ImmutableList<GlobalSetting> globalSettings = parser.parse(stream);
assertThat(globalSettings.get(0).includes().get(0), is(join("src", "test", "resources", "setti... |
public static Projection<Entry<Object, Object>, JetSqlRow> toProjection(
KvRowProjector.Supplier rightRowProjectorSupplier,
ExpressionEvalContext evalContext
) {
return new JoinProjection(rightRowProjectorSupplier, UntrustedExpressionEvalContext.from(evalContext));
} | @Test
public void when_serializedObject_then_deserializedCorrect() {
AbstractSerializationService service = (AbstractSerializationService) TestUtil.getNode(instance()).getSerializationService();
var evalContextMock = mock(ExpressionEvalContext.class);
when(evalContextMock.getSerializationSe... |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetBiFunction() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("biFunctionType", BiFunction.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getSchemaFromType(type);
assertThat(schema, instanceOf(LambdaType.class));
... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(!session.getClient().setFileType(FTP.BINARY_FILE_TYPE)) {
throw new FTPException(session.getClient().getReplyCode(), session.ge... | @Test(expected = NotfoundException.class)
public void testReadNotFound() throws Exception {
final TransferStatus status = new TransferStatus();
new FTPReadFeature(session).read(new Path(new FTPWorkdirService(session).find(), "nosuchname", EnumSet.of(Path.Type.file)), status, new DisabledConnectionCa... |
@Override
@MethodNotAvailable
public CompletionStage<V> putAsync(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testPutAsyncWithTtl() {
adapter.putAsync(42, "value", 1, TimeUnit.MILLISECONDS);
} |
static int run(Collection<URI> namenodes, final BalancerParameters p,
Configuration conf) throws IOException, InterruptedException {
return run(namenodes, null, p, conf);
} | @Test(timeout = 100000)
public void testManyBalancerSimultaneously() throws Exception {
final Configuration conf = new HdfsConfiguration();
initConf(conf);
// add an empty node with half of the capacities(4 * CAPACITY) & the same
// rack
long[] capacities = new long[] { 4 * CAPACITY };
String[... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Condition condition = (Condition) o;
return Objects.equals(metricKey, condition.metricKey) &&
operator == condition.operator &&
Obj... | @Test
public void equals_is_based_on_all_fields() {
assertThat(underTest)
.isEqualTo(underTest)
.isNotNull()
.isNotEqualTo(new Object())
.isEqualTo(new Condition(METRIC_KEY, OPERATOR, ERROR_THRESHOLD))
.isNotEqualTo(new Condition("other_metric_key", OPERATOR, ERROR_THRESHOLD));
A... |
@Override
public boolean skip(final ServerWebExchange exchange) {
return skipExcept(exchange, RpcTypeEnum.SPRING_CLOUD);
} | @Test
public void skip() {
final boolean result = springCloudPlugin.skip(exchange);
assertFalse(result);
} |
public Rule<FilterNode> filterNodeRule()
{
return new PullUpExpressionInLambdaFilterNodeRule();
} | @Test
public void testFilter()
{
tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).filterNodeRule())
.setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true")
.on(p ->
{
p.variable("idmap", new MapType(BI... |
@Override
public UrlPattern doGetPattern() {
return UrlPattern.builder()
.includes("/*")
.excludes(StaticResources.patterns())
.excludes(SKIPPED_URLS)
.build();
} | @Test
public void doGetPattern_excludesNotEmpty() {
PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession);
UrlPattern urlPattern = consentFilter.doGetPattern();
assertThat(urlPattern.getExclusions()).isNotEmpty();
} |
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception {
return newGetter(object, parent, modifier, method.getReturnType(), method::invoke,
(t, et) -> new MethodGetter(parent, method, modifier, t, et));
} | @Test
public void newMethodGetter_whenExtractingFromNonEmpty_Array_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", new InnerObject("inner", 0, 1, 2, 3));
Getter parentGetter = GetterFactory.newMethodGetter(object,... |
@Override
public boolean syncData(DistroData data, String targetServer) {
if (isNoExistTarget(targetServer)) {
return true;
}
DistroDataRequest request = new DistroDataRequest(data, data.getType());
Member member = memberManager.find(targetServer);
if (checkTarget... | @Test
void testSyncDataFailure() throws NacosException {
when(memberManager.hasMember(member.getAddress())).thenReturn(true);
when(memberManager.find(member.getAddress())).thenReturn(member);
member.setState(NodeState.UP);
response.setErrorInfo(ResponseCode.FAIL.getCode(), "TEST");
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.