focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void writeFloat(final float v) throws IOException {
writeInt(Float.floatToIntBits(v));
} | @Test
public void testWriteFloatForPositionVByteOrder() throws Exception {
float v = 1.1f;
out.writeFloat(1, v, LITTLE_ENDIAN);
int expected = Float.floatToIntBits(v);
int actual = Bits.readIntL(out.buffer, 1);
assertEquals(actual, expected);
} |
@Override
public ExportResult<PhotosContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation)
throws CopyExceptionWithFailureReason {
Preconditions.checkNotNull(authData);
if (!exportInformation.isPresent()) {
// No export informati... | @Test
public void testExportAlbum() throws CopyExceptionWithFailureReason {
ExportResult<PhotosContainerResource> result =
facebookPhotosExporter.export(
uuid, new TokensAndUrlAuthData("accessToken", null, null), Optional.empty());
assertEquals(ExportResult.ResultType.CONTINUE, result.get... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testDisplayDataIncludedForDisjointInterfaceHierarchies() {
FooOptions fooOptions = PipelineOptionsFactory.as(FooOptions.class);
fooOptions.setFoo("foo");
BarOptions barOptions = fooOptions.as(BarOptions.class);
barOptions.setBar("bar");
DisplayData data = DisplayData.from(barOp... |
void wakeup() {
wokenup.set(true);
try {
lock.lock();
notEmptyCondition.signalAll();
} finally {
lock.unlock();
}
} | @Test
public void testWakeup() throws Exception {
try (FetchBuffer fetchBuffer = new FetchBuffer(logContext)) {
final Thread waitingThread = new Thread(() -> {
final Timer timer = time.timer(Duration.ofMinutes(1));
fetchBuffer.awaitNotEmpty(timer);
});... |
@Restricted(NoExternalUse.class)
public static Icon tryGetIcon(String iconGuess) {
// Jenkins Symbols don't have metadata so return null
if (iconGuess == null || iconGuess.startsWith("symbol-")) {
return null;
}
Icon iconMetadata = IconSet.icons.getIconByClassSpec(iconGu... | @Test
public void tryGetIcon_shouldReturnNullForUnknown() throws Exception {
assertThat(Functions.tryGetIcon("icon-nosuchicon"), is(nullValue()));
} |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
doHttpFilter((HttpServletRequest) req, (HttpServletResponse) resp, chain);
} | @Test
public void do_not_set_frame_protection_on_integration_resources_with_context() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getMethod()).thenReturn("GET");
when(request.getRequestURI()).thenReturn("/sonarqube/integration/github");
when(request.get... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final Instant lower = calculateLowerBound(windowSt... | @Test
@SuppressWarnings("unchecked")
public void shouldReturnValuesForOpenStartBounds() {
// Given:
final Range<Instant> start = Range.open(
NOW,
NOW.plusSeconds(10)
);
final StateQueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> partitionResult =
new StateQueryRes... |
public static <F extends Future<Void>> Mono<Void> from(F future) {
Objects.requireNonNull(future, "future");
if (future.isDone()) {
if (!future.isSuccess()) {
return Mono.error(FutureSubscription.wrapError(future.cause()));
}
return Mono.empty();
}
return new ImmediateFutureMono<>(future);
} | @SuppressWarnings("FutureReturnValueIgnored")
@Test
void testImmediateFutureMonoLater() {
ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE;
Promise<Void> promise = eventExecutor.newPromise();
StepVerifier.create(FutureMono.from(promise))
.expectSubscription()
.... |
@Override
public Time getTime(final int columnIndex) throws SQLException {
return (Time) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Time.class), Time.class);
} | @Test
void assertGetTimeWithColumnIndex() throws SQLException {
when(mergeResultSet.getValue(1, Time.class)).thenReturn(new Time(0L));
assertThat(shardingSphereResultSet.getTime(1), is(new Time(0L)));
} |
public boolean matchesBeacon(Beacon beacon) {
// All identifiers must match, or the corresponding region identifier must be null.
for (int i = mIdentifiers.size(); --i >= 0; ) {
final Identifier identifier = mIdentifiers.get(i);
Identifier beaconIdentifier = null;
if ... | @Test
public void testBeaconMatchesRegionWithSingleNullIdentifierList() {
Beacon beacon = new AltBeacon.Builder().setId1("1").setId2("2").setId3("3").setRssi(4)
.setBeaconTypeCode(5).setTxPower(6).setBluetoothAddress("1:2:3:4:5:6").build();
ArrayList<Identifier> identifiers=new Array... |
@ProcessElement
public ProcessContinuation processElement(
@Element byte[] element,
RestrictionTracker<OffsetRange, Long> tracker,
WatermarkEstimator<Instant> watermarkEstimator,
OutputReceiver<V> receiver) {
if (tracker.currentRestriction() != null) {
LOG.info(
"Start pro... | @Test
public void testProcessElement() {
MockOutputReceiver receiver = new MockOutputReceiver();
DoFn.ProcessContinuation result =
dofnInstance.processElement(
TEST_ELEMENT,
dofnInstance.restrictionTracker(
TEST_ELEMENT, dofnInstance.initialRestriction(TEST_ELEM... |
@Override
public Map<ExecutionAttemptID, ExecutionDeploymentState> getExecutionsOn(ResourceID host) {
return executionsByHost.getOrDefault(host, Collections.emptySet()).stream()
.collect(
Collectors.toMap(
x -> x,
... | @Test
void testGetExecutionsReturnsEmptySetForUnknownHost() {
final DefaultExecutionDeploymentTracker tracker = new DefaultExecutionDeploymentTracker();
assertThat(tracker.getExecutionsOn(ResourceID.generate()).entrySet()).isEmpty();
} |
static CompositeParser of(Parser... parsers) {
if (parsers == null || parsers.length == 0)
throw new IllegalArgumentException("Unable to create CompositeParser");
return new CompositeParser(Arrays.asList(parsers));
} | @Test
public void fails_when_no_successful_parsers() {
assertScheduleNotPresent(
CompositeParser.of(NON_MATCHING_PARSER, ANOTHER_NON_MATCHING_PARSER), ANY_SCHEDULE_STRING);
} |
public String migrate(String oldJSON, int targetVersion) {
LOGGER.debug("Migrating to version {}: {}", targetVersion, oldJSON);
Chainr transform = getTransformerFor(targetVersion);
Object transformedObject = transform.transform(JsonUtils.jsonToMap(oldJSON), getContextMap(targetVersion));
... | @Test
void migrateV3ToV4_shouldAddADefaultDisplayOrderWeightToPipelines() {
ConfigRepoDocumentMother documentMother = new ConfigRepoDocumentMother();
String oldJSON = documentMother.v3Comprehensive();
String newJSON = documentMother.v4ComprehensiveWithDisplayOrderWeightOfMinusOneForBothPipel... |
@Override
public Config build() {
return build(new Config());
} | @Override
@Test
public void testConfigurationURL()
throws Exception {
URL configURL = getClass().getClassLoader().getResource("hazelcast-default.yaml");
Config config = new YamlConfigBuilder(configURL).build();
assertEquals(configURL, config.getConfigurationUrl());
as... |
@Override
public Optional<FunctionDefinition> getFunctionDefinition(String name) {
final String normalizedName = name.toUpperCase(Locale.ROOT);
return Optional.ofNullable(normalizedFunctions.get(normalizedName));
} | @Test
void testGetFunction() {
assertThat(CoreModule.INSTANCE.getFunctionDefinition("CAST"))
.hasValueSatisfying(
def ->
assertThat(def)
.asInstanceOf(type(BuiltInFunctionDefinition.class))
... |
@Nullable
public ResolvedAddressTypes resolvedAddressTypes() {
return resolvedAddressTypes;
} | @Test
void resolvedAddressTypes() {
assertThat(builder.build().resolvedAddressTypes()).isNull();
builder.resolvedAddressTypes(ResolvedAddressTypes.IPV4_ONLY);
assertThat(builder.build().resolvedAddressTypes()).isEqualTo(ResolvedAddressTypes.IPV4_ONLY);
} |
public SignatureResponse getDigitalSignatureRestService(SignatureRequest request, String clientIp) {
SignatureResponse response = new SignatureResponse();
EidSession session = initSession(request, clientIp, response);
if (session == null) return response;
// 1. create the digital signat... | @Test
public void getDigitalSignatureRestServiceTest() {
EidSession session = new EidSession();
session.setAtReference("SSSSSSSSSSSSSSSS");
session.setEphemeralKey(ephemeralKey);
session.setIdpicc(ByteArray.fromBase64("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"));
... |
public StringSetData combine(StringSetData other) {
if (this.stringSet().isEmpty()) {
return other;
} else if (other.stringSet().isEmpty()) {
return this;
} else {
ImmutableSet.Builder<String> combined = ImmutableSet.builder();
combined.addAll(this.stringSet());
combined.addAll... | @Test
public void testCombine() {
StringSetData singleElement = StringSetData.create(ImmutableSet.of("ab"));
StringSetData multipleElement = StringSetData.create(ImmutableSet.of("cd", "ef"));
StringSetData result = singleElement.combine(multipleElement);
assertEquals(result.stringSet(), ImmutableSet.o... |
public void union(Block block)
{
currentBlockIndex++;
ensureBlocksCapacity(currentBlockIndex + 1);
blocks[currentBlockIndex] = block;
int positionCount = block.getPositionCount();
int[] positions = new int[positionCount];
// Add the elements to the hash table. Since... | @Test
public void testIntersectWithDistinctValues()
{
OptimizedTypedSet typedSet = new OptimizedTypedSet(BIGINT, BIGINT_DISTINCT_METHOD_HANDLE, POSITIONS_PER_PAGE);
Block block = createLongSequenceBlock(0, POSITIONS_PER_PAGE - 1).appendNull();
typedSet.union(block);
testInterse... |
public static int nextInt(final int startInclusive, final int endExclusive) {
checkParameters(startInclusive, endExclusive);
int diff = endExclusive - startInclusive;
if (diff == 0) {
return startInclusive;
}
return startInclusive + RANDOM.nextInt(diff);
} | @Test
void testNextInt() {
final int result = RandomUtils.nextInt(1, 199);
assertTrue(result >= 1 && result < 199);
} |
@Override
public Map<String, T> members() {
List<ChildData<T>> children = getActiveChildren();
children.sort(sequenceComparator);
Map<String, T> members = new LinkedHashMap<>();
for (ChildData<T> child : children) {
members.put(child.getPath(), child.getNode());
}... | @Test
public void testMembersWithStaleNodes() throws Exception {
putChildData(group, PATH + "/001", "container1"); // stale
putChildData(group, PATH + "/002", "container1");
putChildData(group, PATH + "/003", "container2"); // stale
putChildData(group, PATH + "/004", "container3"); /... |
public static ScalarType createUnifiedDecimalType() {
// for mysql compatibility
return createUnifiedDecimalType(10, 0);
} | @Test
public void testCreateUnifiedDecimalType() {
Config.enable_decimal_v3 = false;
Assert.assertEquals(
ScalarType.createUnifiedDecimalType(27, 3),
ScalarType.createDecimalV2Type(27, 3));
Assert.assertEquals(
ScalarType.createUnifiedDecimalTy... |
public static String decode(String s)
{
final int n = s.length();
StringBuilder result = new StringBuilder(n);
for (int i = 0; i < n; i++)
{
char c = s.charAt(i);
if (c == '%')
{
int numCharsConsumed = decodeConsecutiveOctets(result, s, i);
i += numCharsConsumed - 1;
... | @Test(dataProvider = "validEncodedText")
public void testDecodeValidStrings(String encoded, String expected)
{
String actual = URIDecoderUtils.decode(encoded);
Assert.assertEquals(actual, expected, "Encoded string was incorrectly decoded.");
} |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeShort() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.SHORT), instanceOf(MySQLInt2BinaryProtocolValue.class));
} |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull13() {
// Arrange
final int type = 15;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Format_desc", actual);
} |
@Override
public Collection<DatabasePacket> execute() {
connectionSession.getServerPreparedStatementRegistry().<MySQLServerPreparedStatement>getPreparedStatement(packet.getStatementId()).getLongData().clear();
return Collections.singleton(new MySQLOKPacket(ServerStatusFlagCalculator.calculateFor(con... | @Test
void assertExecute() {
ConnectionSession connectionSession = mock(ConnectionSession.class);
when(connectionSession.getServerPreparedStatementRegistry()).thenReturn(new ServerPreparedStatementRegistry());
when(connectionSession.getTransactionStatus()).thenReturn(new TransactionStatus())... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testDifferentLevelDoesNotCauseRecompression() {
List<byte[]> records = Arrays.asList(
String.join("", Collections.nCopies(256, "some")).getBytes(),
String.join("", Collections.nCopies(256, "data")).getBytes()
);
// Records from the producer ... |
public static Node build(final List<JoinInfo> joins) {
Node root = null;
for (final JoinInfo join : joins) {
if (root == null) {
root = new Leaf(join.getLeftSource());
}
if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) {
throw new K... | @Test
public void outputsCorrectJoinTreeString() {
// Given:
when(j1.getLeftSource()).thenReturn(a);
when(j1.getRightSource()).thenReturn(b);
when(j2.getLeftSource()).thenReturn(a);
when(j2.getRightSource()).thenReturn(c);
final List<JoinInfo> joins = ImmutableList.of(j1, j2);
// When:
... |
@Override
public long currentSystemTimeMs() {
throw new UnsupportedOperationException("StateStores can't access system time.");
} | @Test
public void shouldThrowOnCurrentSystemTime() {
assertThrows(UnsupportedOperationException.class, () -> context.currentSystemTimeMs());
} |
@Override
public int hashCode() {
return value.hashCode();
} | @Test
public void testHashCode() {
LazilyParsedNumber n1 = new LazilyParsedNumber("1");
LazilyParsedNumber n1Another = new LazilyParsedNumber("1");
assertThat(n1Another.hashCode()).isEqualTo(n1.hashCode());
} |
static Optional<ExecutorService> lookupExecutorServiceRef(
CamelContext camelContext, String name, Object source, String executorServiceRef) {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ObjectHelper.notNull(manager, ESM_NAME);
ObjectHelper.notNull(exec... | @Test
void testLookupExecutorServiceRefWithNullManager() {
String name = "ThreadPool";
Object source = new Object();
String executorServiceRef = "ThreadPoolRef";
when(camelContext.getExecutorServiceManager()).thenReturn(null);
Exception ex = assertThrows(IllegalArgumentExcept... |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test
public void of_equalityDifferentSchedulers() {
String urnA = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208 -1 Scheduler Task";
String urnB = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208 -1 Scheduler2 Task";
assertNotEquals(ScheduledTaskHandler.of(... |
@Override
public void sessionDidActivate(HttpSessionEvent event) {
if (!instanceEnabled) {
return;
}
// pour getSessionCount
SESSION_COUNT.incrementAndGet();
// pour invalidateAllSession
addSession(event.getSession());
} | @Test
public void testSessionDidActivate() {
sessionListener.sessionDidActivate(createSessionEvent());
if (SessionListener.getSessionCount() != 1) {
fail("sessionDidActivate");
}
if (SessionListener.getAllSessionsInformations().isEmpty()) {
fail("sessionDidActivate");
}
} |
@Override
public void run() {
try {
cleanup();
} catch (Exception e) {
log.warn("Caught exception during Intent cleanup", e);
}
} | @Test
public void corruptPoll() {
IntentStoreDelegate mockDelegate = new IntentStoreDelegate() {
@Override
public void process(IntentData intentData) {
intentData.setState(CORRUPT);
store.write(intentData);
}
@Override
... |
@Override
public String toString() {
return "Permission{" + "resource='" + resource + '\'' + ", action='" + action + '\'' + '}';
} | @Test
void testToString() {
assertEquals("Permission{resource='Resource{namespaceId='', group='', name='', type='', properties=null}', action='w'}",
permission.toString());
} |
public boolean hasMethod(String name) {
for (String mn : getMethodNames()) {
if (mn.equals(name)) {
return true;
}
}
return false;
} | @Test
void testHasMethod() throws Exception {
Wrapper w = Wrapper.getWrapper(I1.class);
Assertions.assertTrue(w.hasMethod("setName"));
Assertions.assertTrue(w.hasMethod("hello"));
Assertions.assertTrue(w.hasMethod("showInt"));
Assertions.assertTrue(w.hasMethod("getFloat"));
... |
public static SelectorConditionVO buildSelectorConditionVO(final SelectorConditionDO selectorConditionDO) {
ParamTypeEnum paramTypeEnum = ParamTypeEnum.getParamTypeEnumByName(selectorConditionDO.getParamType());
OperatorEnum operatorEnum = OperatorEnum.getOperatorEnumByAlias(selectorConditionDO.getOpera... | @Test
public void testBuildSelectorConditionVO() {
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
assertNotNull(SelectorConditionVO.buildSelectorConditionVO(SelectorConditionDO.builder()
.paramType(ParamTypeEnum.POST.getName())
.operator(OperatorEn... |
public void isNull() {
standardIsEqualTo(null);
} | @Test
public void isNullFail() {
Object o = new Object();
expectFailure.whenTesting().that(o).isNull();
assertFailureKeys("expected", "but was");
assertFailureValue("expected", "null");
} |
public int getNumberOfPendingCheckpoints() {
synchronized (lock) {
return this.pendingCheckpoints.size();
}
} | @Test
void testPeriodicSchedulingWithInactiveTasks() throws Exception {
CheckpointCoordinator checkpointCoordinator =
setupCheckpointCoordinatorWithInactiveTasks(new MemoryStateBackend());
// the coordinator should start checkpointing now
manuallyTriggeredScheduledExecutor.t... |
@Override
public Page download(Request request, Task task) {
if (task == null || task.getSite() == null) {
throw new NullPointerException("task or site can not be null");
}
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient = getHttpClient(task.getS... | @Test
public void test_set_site_cookie() throws Exception {
HttpServer server = httpServer(13423);
server.get(eq(cookie("cookie"), "cookie-webmagic")).response("ok");
Runner.running(server, new Runnable() {
@Override
public void run() throws Exception {
... |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testGetAllTTL() throws InterruptedException {
RMapCacheNative<Integer, Integer> map = redisson.getMapCacheNative("getAll");
map.put(1, 100);
map.put(2, 200, Duration.ofSeconds(1));
map.put(3, 300, Duration.ofSeconds(1));
map.put(4, 400);
Map<Integer... |
@Override public void require(long byteCount) throws IOException {
if (!request(byteCount)) throw new EOFException();
} | @Test public void requireInsufficientData() throws Exception {
Buffer source = new Buffer();
source.writeUtf8("a");
BufferedSource bufferedSource = new RealBufferedSource(source);
try {
bufferedSource.require(2);
fail();
} catch (EOFException expected) {
}
} |
@Override
public Object decode(Response response, Type type) throws IOException {
JsonAdapter<Object> jsonAdapter = moshi.adapter(type);
if (response.status() == 404 || response.status() == 204)
return Util.emptyValueOf(type);
if (response.body() == null)
return null;
try (BufferedSource... | @Test
void customObjectDecoder() throws Exception {
final JsonAdapter<VideoGame> videoGameJsonAdapter =
new Moshi.Builder().build().adapter(VideoGame.class);
MoshiDecoder decoder = new MoshiDecoder(Collections.singleton(videoGameJsonAdapter));
VideoGame videoGame = new VideoGame("Super Mario", "... |
public JobState getState() {
return state;
} | @Test
public void testUpdateNumOfDataErrorRowMoreThanMax(@Mocked GlobalStateMgr globalStateMgr) {
RoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob();
Deencapsulation.setField(routineLoadJob, "maxErrorNum", 0);
Deencapsulation.setField(routineLoadJob, "maxBatchRows", 0);
Deenca... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 1, 1, HELP);
final String filePath = args.get(0);
final String content = loadScript(filePath);
requestExecutor.makeKsqlRequest(content);
} | @Test
public void shouldThrowIfDirectory() throws Exception {
// Given:
final File dir = TMP.newFolder();
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> cmd.execute(ImmutableList.of(dir.toString()), terminal)
);
// Then:
assertThat(e.getMessage(), c... |
@GetInitialRestriction
public OffsetRange initialRestriction(@Element byte[] element) {
return new OffsetRange(startOffset, Long.MAX_VALUE);
} | @Test
public void testInitialRestriction() {
long expectedStartOffset = 0L;
OffsetRange result = dofnInstance.initialRestriction(TEST_ELEMENT);
assertEquals(new OffsetRange(expectedStartOffset, Long.MAX_VALUE), result);
} |
@ApiOperation(value = "Delete User (deleteUser)",
notes = "Deletes the User, it's credentials and all the relations (from and to the User). " +
"Referencing non-existing User Id will cause an error. " + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN',... | @Test
public void testDeleteUser() throws Exception {
loginSysAdmin();
User user = createTenantAdminUser();
User savedUser = doPost("/api/user", user, User.class);
User foundUser = doGet("/api/user/" + savedUser.getId().getId().toString(), User.class);
Assert.assertNotNull(... |
@Override
public LookupResult<BrokerKey> handleResponse(Set<BrokerKey> keys, AbstractResponse abstractResponse) {
validateLookupKeys(keys);
MetadataResponse response = (MetadataResponse) abstractResponse;
MetadataResponseData.MetadataResponseBrokerCollection brokers = response.data().broker... | @Test
public void testHandleResponse() {
AllBrokersStrategy strategy = new AllBrokersStrategy(logContext);
MetadataResponseData response = new MetadataResponseData();
response.brokers().add(new MetadataResponseData.MetadataResponseBroker()
.setNodeId(1)
.setHost("hos... |
public boolean isValid() {
if (mIntervals.isEmpty()) {
return false;
}
if (mIntervals.size() == 1 && mIntervals.get(0).equals(Interval.NEVER)) {
return false;
}
return true;
} | @Test
public void isValid() {
Assert.assertTrue(IntervalSet.ALWAYS.isValid());
Assert.assertFalse(IntervalSet.NEVER.isValid());
Assert.assertTrue(new IntervalSet(Interval.between(1, 2)).isValid());
Assert.assertTrue(new IntervalSet(Interval.before(10)).isValid());
Assert.assertTrue(new IntervalSe... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal number) {
if ( number == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "number", "cannot be null"));
}
return FEELFnResult.ofResult( number.abs() );
} | @Test
void absFunctionDuration() {
FunctionTestUtil.assertResult(absFunction.invoke(Duration.ofSeconds(100, 50 )),
Duration.ofSeconds(100, 50));
FunctionTestUtil.assertResult(absFunction.invoke(Duration.ofSeconds(-100, 50 )),
Duration.ofSeconds(100, -50));
Fun... |
static Timestamp parseTimeStamp(final String value) {
try {
// JDK format in Timestamp.valueOf is compatible with TIMESTAMP_FORMAT
return Timestamp.valueOf(value);
} catch (IllegalArgumentException e) {
return throwRuntimeParseException(value, new ParseException(e.get... | @Test
public void testTimestampWithTrailingZeros() throws Exception {
// Given
Timestamp expectedTimestamp = new Timestamp(new SimpleDateFormat(TIMESTAMP_FORMAT)
.parse("2010-10-20 10:20:30.040")
.getTime());
// When
Timestamp actualTimestamp = DateHe... |
public static double lgamma(double x) {
double xcopy = x;
double fg;
double first = x + LANCZOS_SMALL_GAMMA + 0.5;
double second = LANCZOS_COEFF[0];
if (x >= 0.0) {
if (x >= 1.0 && x - (int) x == 0.0) {
fg = lfactorial((int) x - 1);
} else... | @Test
public void testLogGamma() {
System.out.println("lgamma");
assertTrue(Double.isInfinite(Gamma.lgamma(0)));
assertEquals(0.0, Gamma.lgamma(1), 1E-7);
assertEquals(0, Gamma.lgamma(2), 1E-7);
assertEquals(Math.log(2.0), Gamma.lgamma(3), 1E-7);
assertEquals(Math.lo... |
@Override
public String doLayout(ILoggingEvent event) {
StringWriter output = new StringWriter();
try (JsonWriter json = new JsonWriter(output)) {
json.beginObject();
if (!"".equals(nodeName)) {
json.name("nodename").value(nodeName);
}
json.name("process").value(processKey);
... | @Test
public void test_log_with_throwable_and_cause() {
Throwable rootCause = new IllegalArgumentException("Root cause");
Throwable exception = new IllegalStateException("BOOM", rootCause);
LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level... |
@Override
public void validate() throws TelegramApiValidationException {
if (inlineQueryId.isEmpty()) {
throw new TelegramApiValidationException("InlineQueryId can't be empty", this);
}
for (InlineQueryResult result : results) {
result.validate();
}
i... | @Test
void testSwitchPmParameterIsMandatoryIfSwitchPmTextIsPresent() {
answerInlineQuery.setInlineQueryId("RANDOMEID");
answerInlineQuery.setResults(new ArrayList<>());
answerInlineQuery.setButton(InlineQueryResultsButton
.builder()
.text("Test Text")
... |
public boolean initAndAddIssue(Issue issue) {
DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent();
if (noSonar(inputComponent, issue)) {
return false;
}
ActiveRule activeRule = activeRules.find(issue.ruleKey());
if (activeRule == null) {
... | @Test
public void ignore_null_rule_of_active_rule() {
initModuleIssues();
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(JAVA_RULE_KEY);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat... |
@Override
public boolean equals(final Object o) {
if (o == this)
return true;
if (o == null || o.getClass() != getClass())
return false;
final MonetaryFormat other = (MonetaryFormat) o;
if (!Objects.equals(this.negativeSign, other.negativeSign))
re... | @Test
public void testEquals() {
MonetaryFormat mf1 = new MonetaryFormat(true);
MonetaryFormat mf2 = new MonetaryFormat(true);
assertEquals(mf1, mf2);
} |
public static Comparator<StructLike> forType(Types.StructType struct) {
return new StructLikeComparator(struct);
} | @Test
public void testString() {
assertComparesCorrectly(Comparators.forType(Types.StringType.get()), "a", "b");
} |
@SuppressWarnings("unchecked")
public <T extends Expression> T rewrite(final T expression, final C context) {
return (T) rewriter.process(expression, context);
} | @Test
public void shouldRewriteIsNullPredicate() {
// Given:
final IsNullPredicate parsed = parseExpression("col0 IS NULL");
when(processor.apply(parsed.getValue(), context)).thenReturn(expr1);
// When:
final Expression rewritten = expressionRewriter.rewrite(parsed, context);
// Then:
as... |
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 setLocation() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.SetLocation("location")));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
... |
public void setInputFile( String file ) {
this.inputFile = file;
} | @Test
public void setInputFile() {
JobScheduleRequest jobScheduleRequest = mock( JobScheduleRequest.class );
doCallRealMethod().when( jobScheduleRequest ).setInputFile( any() );
String inputFile = "hitachi";
jobScheduleRequest.setInputFile( inputFile );
Assert.assertEquals( inputFile, ReflectionTe... |
@Override
public List<String> getTenantIdList(int page, int pageSize) {
ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO);
int from = (page - 1) * pageSize;
MapperResult mapperResult = configInfoMapp... | @Test
void testGetTenantIdList() {
int page = 10;
int pageSize = 100;
//mock select config state
List<String> tenantStrings = Arrays.asList("tenant1", "tenant2", "tenant3");
when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {}), eq(String.class))).thenRetur... |
@Override
public String[] split(String text) {
if (splitContraction) {
text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not");
text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not");
text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not");
f... | @Test
public void testTokenizeVariousSpaces() {
System.out.println("tokenize words separated by various kinds of space");
// No-break space and em-space
String text = "the\u00A0cat\u2003the_cat";
String[] expResult = {"the", "cat", "the_cat"};
SimpleTokenizer instance = new ... |
@Override
public Object adapt(final HttpAction action, final WebContext context) {
if (action != null) {
var code = action.getCode();
val response = ((JEEContext) context).getNativeResponse();
if (code < 400) {
response.setStatus(code);
} else... | @Test(expected = TechnicalException.class)
public void testNullAction() {
JEEHttpActionAdapter.INSTANCE.adapt(null, context);
} |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void format_sets_subject_with_project_name_of_first_issue_in_set_when_change_from_Analysis() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" +... |
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(
RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString())
.trim();
if (ConfigUtils.isEmpty(value)) {
... | @Test
void testMockInvokerInvoke_failmock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return null"))
... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final ReadOnlySessionStore<GenericKey, GenericRow> store = sta... | @Test
public void shouldIgnoreSessionsThatStartAtUpperBoundIfUpperBoundOpen() {
// Given:
final Range<Instant> startBounds = Range.closedOpen(
LOWER_INSTANT,
UPPER_INSTANT
);
givenSingleSession(UPPER_INSTANT, UPPER_INSTANT.plusMillis(1));
// When:
final Iterator<WindowedRow> ... |
public static int decodeConsecutiveOctets(StringBuilder dest, String s, int start)
{
final int n = s.length();
if (start >= n)
{
throw new IllegalArgumentException("Cannot decode from index " + start + " of a length-" + n + " string");
}
if (s.charAt(start) != '%')
{
throw new Il... | @Test(dataProvider = "invalidConsecutiveOctetData")
public void testDecodeInvalidConsecutiveOctets(String encoded, int startIndex, String expectedErrorMessage)
{
IllegalArgumentException exception = null;
try
{
URIDecoderUtils.decodeConsecutiveOctets(new StringBuilder(), encoded, startIndex);
... |
public static ImmutableList<String> glob(final String glob) {
Path path = getGlobPath(glob);
int globIndex = getGlobIndex(path);
if (globIndex < 0) {
return of(glob);
}
return doGlob(path, searchPath(path, globIndex));
} | @Test
public void should_glob_absolute_files(@TempDir final File folder) {
File file = new File(folder, "glob-absolute.json");
String path = file.getAbsolutePath();
ImmutableList<String> files = Globs.glob(path);
assertThat(files.contains(path), is(true));
} |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetFunction() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("functionType", Function.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getSchemaFromType(type);
assertThat(schema, instanceOf(LambdaType.class));
assert... |
@Override
protected boolean hasLeadership(String componentId, UUID leaderSessionId) {
synchronized (lock) {
if (leaderElectionDriver != null) {
if (leaderContenderRegistry.containsKey(componentId)) {
return leaderElectionDriver.hasLeadership()
... | @Test
void testHasLeadershipWithLeadershipLostButNoRevokeEventProcessed() throws Exception {
new Context() {
{
runTestWithManuallyTriggeredEvents(
executorService -> {
final UUID expectedSessionID = UUID.randomUUID();
... |
public FEELFnResult<String> invoke(@ParameterName("from") Object val) {
if ( val == null ) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) );
}
} | @Test
void invokeOffsetDateTime() {
final OffsetDateTime offsetDateTime = OffsetDateTime.now();
FunctionTestUtil.assertResult(stringFunction.invoke(offsetDateTime),
DateAndTimeFunction.FEEL_DATE_TIME.format(offsetDateTime));
} |
public CreateTableBuilder withPkConstraintName(String pkConstraintName) {
this.pkConstraintName = validateConstraintName(pkConstraintName);
return this;
} | @Test
public void withPkConstraintName_throws_IAE_if_name_is_more_than_30_char_long() {
assertThatThrownBy(() -> underTest.withPkConstraintName("abcdefghijklmnopqrstuvwxyzabcdf"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Constraint name length can't be more than 30");
} |
@SuppressWarnings("unchecked")
public static <E extends Enum<E>> EnumSet<E> parseEnumSet(final String key,
final String valueString,
final Class<E> enumClass,
final boolean ignoreUnknown) throws IllegalArgumentException {
// build a map of lower case string to enum values.
final Map<String,... | @Test
public void testCaseConflictingEnumNotSupported() throws Throwable {
intercept(IllegalArgumentException.class,
ERROR_MULTIPLE_ELEMENTS_MATCHING_TO_LOWER_CASE_VALUE,
() ->
parseEnumSet("key", "c, unrecognized",
CaseConflictingEnum.class, false));
} |
@Override
public BlueRun getLatestRun() {
Run run = job.getLastBuild();
if(run instanceof FreeStyleBuild){
BlueRun blueRun = new FreeStyleRunImpl((FreeStyleBuild) run, this, organization);
return new FreeStyleRunSummary(blueRun, run, this, organization);
}
ret... | @Test
@Issue("JENKINS-51716")
public void findNonNumericRun() throws Exception {
FreeStyleProject freestyle = Mockito.spy(j.createProject(FreeStyleProject.class, "freestyle"));
FreeStyleBuild build1 = Mockito.mock(FreeStyleBuild.class);
FreeStyleBuild build2 = Mockito.mock(FreeStyleBuil... |
boolean isCollection( BeanInjectionInfo.Property property ) {
if ( property == null ) { // not sure if this is necessary
return false;
}
BeanLevelInfo beanLevelInfo = getFinalPath( property );
return ( beanLevelInfo != null ) ? isCollection( beanLevelInfo ) : null;
} | @Test
public void isCollection_False() {
BeanInjector bi = new BeanInjector(null );
BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class );
BeanInjectionInfo.Property seperatorProperty = bii.getProperties().values().stream()
.filter( p -> p.getName().equals( "SEPARATOR" ) ).findFirst(... |
public void start() throws Exception {
AuthenticationService authenticationService = new AuthenticationService(
PulsarConfigurationLoader.convertFrom(config));
if (config.getBrokerClientAuthenticationPlugin() != null) {
proxyClientAuthentication = AuthenticationFactory.creat... | @Test
public void testProduceAndConsumeMessageWithWebsocket() throws Exception {
@Cleanup("stop")
HttpClient producerClient = new HttpClient();
@Cleanup("stop")
WebSocketClient producerWebSocketClient = new WebSocketClient(producerClient);
producerWebSocketClient.start();
... |
public static TableIdentifier toIcebergTableIdentifier(SnowflakeIdentifier identifier) {
Preconditions.checkArgument(
identifier.type() == SnowflakeIdentifier.Type.TABLE,
"SnowflakeIdentifier must be type TABLE, got '%s'",
identifier);
return TableIdentifier.of(
identifier.databa... | @Test
public void testToIcebergTableIdentifier() {
assertThat(
NamespaceHelpers.toIcebergTableIdentifier(
SnowflakeIdentifier.ofTable("DB1", "SCHEMA1", "TABLE1")))
.isEqualTo(TableIdentifier.of("DB1", "SCHEMA1", "TABLE1"));
} |
public List<String> getRequestNames() {
return requestNames;
} | @Test
public void testDatabase() {
for (final Database database : Database.values()) {
final List<String> requestNames = database.getRequestNames();
assertTrue("getRequestNames", requestNames != null && !requestNames.isEmpty());
for (final String requestName : requestNames) {
assertNotNull("getRequestBy... |
public HealthCheckResponse checkHealth() {
final Map<String, HealthCheckResponseDetail> results = DEFAULT_CHECKS.stream()
.collect(Collectors.toMap(
Check::getName,
check -> check.check(this)
));
final boolean allHealthy = results.values().stream()
.allMatch(Healt... | @Test
public void shouldReturnUnhealthyIfKafkaCheckFails() {
// Given:
givenDescribeTopicsThrows(KafkaResponseGetFailedException.class);
// When:
final HealthCheckResponse response = healthCheckAgent.checkHealth();
// Then:
assertThat(response.getDetails().get(KAFKA_CHECK_NAME).getIsHealthy(... |
public void addPoint(Point p) {
mPoints.add(p);
} | @Test
public void json() throws Exception {
IOTaskResult result = new IOTaskResult();
result.addPoint(new IOTaskResult.Point(IOTaskResult.IOMode.READ, 100L, 20));
result.addPoint(new IOTaskResult.Point(IOTaskResult.IOMode.WRITE, 100L, 5));
ObjectMapper mapper = new ObjectMapper();
String json = ma... |
public Optional<InstantAndValue<T>> getAndSet(MetricKey metricKey, Instant now, T value) {
InstantAndValue<T> instantAndValue = new InstantAndValue<>(now, value);
InstantAndValue<T> valueOrNull = counters.put(metricKey, instantAndValue);
// there wasn't already an entry, so return empty.
... | @Test
public void testGetAndSetDoubleWithTrackedValue() {
LastValueTracker<Double> lastValueTracker = new LastValueTracker<>();
lastValueTracker.getAndSet(METRIC_NAME, instant1, 1d);
Optional<InstantAndValue<Double>> result = lastValueTracker
.getAndSet(METRIC_NAME, instant2, 10... |
public static Builder builder(String testId) {
return new Builder(testId);
} | @Test
public void testCreateResourceManagerThrowsCustomPortErrorWhenUsingStaticContainer() {
assertThat(
assertThrows(
SplunkResourceManagerException.class,
() ->
SplunkResourceManager.builder(TEST_ID)
.setHost... |
@Override
public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting put task configuration request {}", connName);
if (requestNotSignedProperly(requestSignature, callbac... | @Test
public void testPutTaskConfigsValidRequiredSignature() {
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V2);
InternalRequestSignature signature = mock(InternalRequestSignature.class);
when(signature.keyAlgorithm()).thenReturn("HmacSHA256");
when(signature.is... |
public ReportEntry createEntry(
final long initialBytesLost,
final long timestampMs,
final int sessionId,
final int streamId,
final String channel,
final String source)
{
ReportEntry reportEntry = null;
final int requiredCapacity =
CHANNEL... | @Test
void shouldUpdateEntry()
{
final long initialBytesLost = 32;
final int timestampMs = 7;
final int sessionId = 3;
final int streamId = 1;
final String channel = "aeron:udp://stuff";
final String source = "127.0.0.1:8888";
final ReportEntry entry = lo... |
@Override
public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity)
throws Exception {
while (interceptors.hasNext()) {
HttpClientRequestInterceptor nextInterceptor = interceptors.next();
if (nextInterceptor.isIntercept(uri, httpMe... | @Test
void testExecuteNotIntercepted() throws Exception {
HttpClientResponse response = clientRequest.execute(URI.create("http://example.com"), "GET",
new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
assertEquals(httpClientResponse, response);
} |
@Override
public boolean tableExists(String dbName, String tblName) {
return deltaOps.tableExists(dbName, tblName);
} | @Test
public void testTableExists() {
Assert.assertTrue(deltaLakeMetadata.tableExists("db1", "table1"));
} |
public static String getDataSourceUnitNode(final String databaseName, final String dataSourceName) {
return String.join("/", getDataSourceUnitsNode(databaseName), dataSourceName);
} | @Test
void assertGetMetaDataDataSourceNode() {
assertThat(DataSourceMetaDataNode.getDataSourceUnitNode("foo_db", "foo_ds"), is("/metadata/foo_db/data_sources/units/foo_ds"));
} |
public static Expression appendNewLambdaToOld(LambdaExpr l1, LambdaExpr l2) {
ExpressionStmt l1ExprStmt = (ExpressionStmt) l1.getBody();
ExpressionStmt l2ExprStmt = (ExpressionStmt) l2.getBody();
DrlxParseUtil.RemoveRootNodeResult removeRootNodeResult = DrlxParseUtil.removeRootNode(l2ExprStmt.g... | @Test
public void appendTwoMethodsToLambda() {
LambdaExpr l1 = parseExpression("(_this) -> _this.getDueDate()");
LambdaExpr l2 = parseExpression("(_this) -> _this.getTime().getTime()");
Expression expected = parseExpression("(_this) -> _this.getDueDate().getTime().getTime()");
Exp... |
public boolean isBuiltIn() {
return mIsBuiltIn;
} | @Test
public void isBuiltIn() {
assertTrue(mTestProperty.isBuiltIn());
} |
@Override
public boolean fastPut(K key, V value, long ttl, TimeUnit ttlUnit) {
return get(fastPutAsync(key, value, ttl, ttlUnit));
} | @Test
public void testFastPutExpiration() throws Exception {
RMapCache<String, Object> mapCache = redisson.getMapCache("testFastPutExpiration");
mapCache.fastPut("k1", "v1", 1, TimeUnit.SECONDS);
Thread.sleep(1000);
mapCache.fastPut("k1", "v2");
assertThat(mapCache.get("k1"))... |
public static void print(Object obj) {
print(TEMPLATE_VAR, obj);
} | @Test
public void printTest(){
String[] a = {"abc", "bcd", "def"};
Console.print(a);
Console.log("This is Console print for {}.", "test");
} |
public long bytesAfter(SegmentPointer mark) {
assert mark.samePage(this.end);
return end.distance(mark);
} | @Test
public void testBytesAfter() throws IOException {
final MappedByteBuffer pageBuffer = Utils.createPageFile();
final SegmentPointer begin = new SegmentPointer(0, 0);
final SegmentPointer end = new SegmentPointer(0, 1023);
final Segment segment = new Segment(pageBuffer, begin, e... |
@Override
public void getConfig(StorServerConfig.Builder builder) {
super.getConfig(builder);
provider.getConfig(builder);
} | @Test
void testSplitAndJoin() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <redundancy>3</redundancy>" +
" <documents/>" +
" <tuning>\n" +
" ... |
@Override
public byte[] serialize(final String topic, final List<?> values) {
if (values == null) {
return null;
}
final T single = extractOnlyColumn(values, topic);
return inner.serialize(topic, single);
} | @Test
public void shouldSerializeNewStyle() {
// Given:
final List<?> values = ImmutableList.of(DATA);
// When:
final byte[] result = serializer.serialize(TOPIC, HEADERS, values);
// Then:
verify(inner).serialize(TOPIC, HEADERS, DATA);
assertThat(result, is(SERIALIZED));
} |
public void rebuildNode(String fullPath) throws Exception {
Preconditions.checkArgument(
ZKPaths.getPathAndNode(fullPath).getPath().equals(path), "Node is not part of this cache: " + fullPath);
Preconditions.checkState(state.get() == State.STARTED, "cache has been closed");
ensu... | @Test
public void testRebuildNode() throws Exception {
Timing timing = new Timing();
PathChildrenCache cache = null;
CuratorFramework client = CuratorFrameworkFactory.newClient(
server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
tr... |
public static void setCurator(CuratorFramework curator) {
CURATOR_TL.set(curator);
} | @Test
public void testCreatingParentContainersIfNeeded() throws Exception {
String connectString = zkServer.getConnectString();
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
Configuration conf = getSecretConf(connectString);
CuratorFramework curatorFramework =
CuratorFramewo... |
public static String decodeUsername(String username) {
if (username.contains("CN=")) {
try {
return new LdapName(username).getRdns().stream()
.filter(rdn -> rdn.getType().equalsIgnoreCase("cn"))
.map(rdn -> rdn.getValue().toString()).... | @Test
public void testDecodeUsername() {
assertThat(KafkaUserModel.decodeUsername("CN=my-user"), is("my-user"));
assertThat(KafkaUserModel.decodeUsername("CN=my-user,OU=my-org"), is("my-user"));
assertThat(KafkaUserModel.decodeUsername("OU=my-org,CN=my-user"), is("my-user"));
} |
@Override
public Upstream doSelect(final List<Upstream> upstreamList, final String ip) {
final ConcurrentSkipListMap<Long, Upstream> treeMap = new ConcurrentSkipListMap<>();
upstreamList.forEach(upstream -> IntStream.range(0, VIRTUAL_NODE_NUM).forEach(i -> {
long addressHash = hash("SHEN... | @Test
void doSelectWithSuccess() {
final HashLoadBalancer hashLoadBalancer = new HashLoadBalancer();
final List<Upstream> upstreamList = new ArrayList<>();
upstreamList.add(Upstream.builder().url("http://1.1.1.1/api").build());
upstreamList.add(Upstream.builder().url("http://2.2.2.2/... |
public final ResponseReceiver<?> get() {
return request(HttpMethod.GET);
} | @Test
void serverInfiniteClientClose() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
disposableServer =
createServer()
.handle((req, resp) -> {
req.withConnection(cn -> cn.onDispose(latch::countDown));
return Flux.interval(Duration.ofSecond... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.