focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String toCsv(List<String> src) {
// return src == null ? null : String.join(", ", src.toArray(new String[0]));
return join(src, ", ");
} | @Test
public void testToCsv() {
assertEquals(toCsv(Collections.<String>emptyList()), (""));
assertEquals(toCsv(Collections.singletonList("a")), ("a"));
assertEquals(toCsv(Arrays.asList("a", "b", "c")), ("a, b, c"));
} |
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | @Test
public void testInvalidJobName() throws IOException {
List<String> invalidNames = Arrays.asList("invalid_name", "0invalid", "invalid-");
List<String> expectedReason =
Arrays.asList("JobName invalid", "JobName invalid", "JobName invalid");
for (int i = 0; i < invalidNames.size(); ++i) {
... |
@Override
public List<FileEntriesLayer> createLayers() throws IOException {
// Clear the exploded-artifact root first
if (Files.exists(targetExplodedJarRoot)) {
MoreFiles.deleteRecursively(targetExplodedJarRoot, RecursiveDeleteOption.ALLOW_INSECURE);
}
// Add dependencies layers.
List<FileE... | @Test
public void testCreateLayers_withoutClassPathInManifest() throws IOException, URISyntaxException {
Path standardJar =
Paths.get(Resources.getResource(STANDARD_JAR_WITHOUT_CLASS_PATH_MANIFEST).toURI());
Path destDir = temporaryFolder.newFolder().toPath();
StandardExplodedProcessor standardExp... |
public Set<String> getClusterList(String topic,
long timeoutMillis) {
return Collections.EMPTY_SET;
} | @Test
public void assertGetClusterList() {
Set<String> actual = mqClientAPI.getClusterList(topic, defaultTimeout);
assertNotNull(actual);
assertEquals(0, actual.size());
} |
public boolean poll(Timer timer, boolean waitForJoinGroup) {
maybeUpdateSubscriptionMetadata();
invokeCompletedOffsetCommitCallbacks();
if (subscriptions.hasAutoAssignedPartitions()) {
if (protocol == null) {
throw new IllegalStateException("User configured " + Cons... | @Test
public void testNotCoordinator() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
// not_coordinator will mark coordinator as unknown
time.sleep(sessionTimeoutMs);
RequestFuture<Void>... |
public static MemberSelector selectorForProcessIds(ProcessId... processIds) {
List<ProcessId> processIdList = asList(processIds);
return member -> {
ProcessId memberProcessId = fromKey(member.getAttribute(PROCESS_KEY.getKey()));
return processIdList.contains(memberProcessId);
};
} | @Test
public void selecting_ce_nodes() {
Member member = mock(Member.class);
MemberSelector underTest = HazelcastMemberSelectors.selectorForProcessIds(COMPUTE_ENGINE);
when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(COMPUTE_ENGINE.getKey());
assertThat(underTest.select(member)).isTrue();
... |
@Override
public boolean remove(K key) {
return cache.remove(key) != null;
} | @Test
public void testRemove() {
Cache<String, String> cache = new LRUCache<>(4);
cache.put("a", "b");
cache.put("c", "d");
cache.put("e", "f");
assertEquals(3, cache.size());
assertTrue(cache.remove("a"));
assertEquals(2, cache.size());
assertNull(c... |
public static IOException maybeExtractIOException(
String path,
Throwable thrown,
String message) {
if (thrown == null) {
return null;
}
// walk down the chain of exceptions to find the innermost.
Throwable cause = getInnermostThrowable(thrown.getCause(), thrown);
// see i... | @Test
public void testUncheckedIOExceptionExtraction() throws Throwable {
intercept(SocketTimeoutException.class, "top",
() -> {
final SdkClientException thrown = sdkException("top",
sdkException("middle",
new UncheckedIOException(
new Socket... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testDodgyCheck()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_DODGY_NECKLACE, 10);
} |
public static void handle(Exception e, RetryContext context) throws Exception {
if (e instanceof RemoteFileNotFoundException) {
handleRemoteFileNotFound((RemoteFileNotFoundException) e, context);
} else if (e instanceof RpcException) {
handleRpcException((RpcException) e, context... | @Test
public void testHandleRemoteFileNotFoundException_2() throws Exception {
ConnectorPlanTestBase.mockHiveCatalog(connectContext);
String sql = "select * from hive0.tpch.customer_view";
StatementBase statementBase = SqlParser.parse(sql, connectContext.getSessionVariable()).get(0);
... |
public BoardsSimpleResponse findAllBoards(final Pageable pageable, final Long memberId) {
Page<BoardSimpleResponse> response = boardRepository.findAllBoardsWithPaging(pageable, memberId);
return BoardsSimpleResponse.of(response, pageable);
} | @Test
void 게시글을_모두_조회한다() {
// when
BoardsSimpleResponse result = boardQueryService.findAllBoards(PageRequest.of(0, 10), 1L);
// then
assertThat(result.nextPage()).isEqualTo(-1);
} |
@Override
public boolean implies(Permission p) {
// By default only supports comparisons with other WildcardPermissions
if (!(p instanceof WildcardPermission)) {
return false;
}
WildcardPermission wp = (WildcardPermission) p;
List<Set<String>> otherParts = getPa... | @Test
public void testNotWildcardPermission() {
ActiveMQWildcardPermission perm = new ActiveMQWildcardPermission("topic:TEST:*");
Permission dummy = new Permission() {
@Override
public boolean implies(Permission p) {
return false;
}
};
... |
public Function.FunctionDetails.ComponentType calculateSubjectType(Function.FunctionDetails functionDetails) {
if (functionDetails.getComponentType() != Function.FunctionDetails.ComponentType.UNKNOWN) {
return functionDetails.getComponentType();
}
Function.SourceSpec sourceSpec = fun... | @Test
public void testCalculateSubjectTypeForSource() {
FunctionDetails.Builder builder = FunctionDetails.newBuilder();
// no input topics mean source
builder.setSource(Function.SourceSpec.newBuilder().build());
assertEquals(InstanceUtils.calculateSubjectType(builder.build()), Functi... |
public boolean evaluateIfActiveVersion(UpdateCenter updateCenter) {
Version installedVersion = Version.create(sonarQubeVersion.get().toString());
if (compareWithoutPatchVersion(installedVersion, updateCenter.getSonar().getLtaVersion().getVersion()) == 0) {
return true;
}
SortedSet<Release> allRel... | @Test
void evaluateIfActiveVersion_whenInstalledVersionIsLatestMinusOne_shouldReturnVersionIsActive() {
when(sonarQubeVersion.get()).thenReturn(parse("10.9"));
when(updateCenter.getSonar().getAllReleases()).thenReturn(getReleases());
assertThat(underTest.evaluateIfActiveVersion(updateCenter)).isTrue();
... |
public static <K, V> Write<K, V> write() {
return new AutoValue_KafkaIO_Write.Builder<K, V>()
.setWriteRecordsTransform(writeRecords())
.build();
} | @Test
public void testSink() throws Exception {
// Simply read from kafka source and write to kafka sink. Then verify the records
// are correctly published to mock kafka producer.
int numElements = 1000;
try (MockProducerWrapper producerWrapper = new MockProducerWrapper(new LongSerializer())) {
... |
public static Optional<String> getTableNameByRowPath(final String rowPath) {
Pattern pattern = Pattern.compile(getShardingSphereDataNodePath() + "/([\\w\\-]+)/schemas/([\\w\\-]+)/tables" + "/([\\w\\-]+)?", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(rowPath);
return matcher.find... | @Test
void assertGetTableNameByRowPathTableNameNotFoundScenario() {
assertThat(ShardingSphereDataNode.getTableNameByRowPath("/statistics/databases/db_name/schemas/db_schema"), is(Optional.empty()));
} |
@Override
public Long createMailAccount(MailAccountSaveReqVO createReqVO) {
MailAccountDO account = BeanUtils.toBean(createReqVO, MailAccountDO.class);
mailAccountMapper.insert(account);
return account.getId();
} | @Test
public void testCreateMailAccount_success() {
// 准备参数
MailAccountSaveReqVO reqVO = randomPojo(MailAccountSaveReqVO.class, o -> o.setMail(randomEmail()))
.setId(null); // 防止 id 被赋值
// 调用
Long mailAccountId = mailAccountService.createMailAccount(reqVO);
/... |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldThrowOnCreateStatementWithNoElements() {
// Given:
final PreparedStatement<CreateStream> cs = PreparedStatement.of("CS",
new CreateStream(SOME_NAME, TableElements.of(), false, false, JSON_PROPS, false));
givenQueryFileParsesTo(cs);
// When:
final Exception e = ass... |
public void appendStandbySnapshot(
final long recordingId,
final long leadershipTermId,
final long termBaseLogPosition,
final long logPosition,
final long timestamp,
final int serviceId,
final String archiveEndpoint)
{
validateRecordingId(recordingId);... | @Test
void shouldRejectSnapshotEntryIfEndpointIsTooLong(@TempDir final File tempDir)
{
final String endpoint = Tests.generateStringWithSuffix("a", "x", 5000);
try (RecordingLog log = new RecordingLog(tempDir, true))
{
final ClusterException exception = assertThrowsExactly(Clu... |
@Override
public KvMetadata resolveMetadata(
boolean isKey,
List<MappingField> resolvedFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe... | @Test
@Parameters({
"true",
"false"
})
public void when_noKeyOrThisPrefixInExternalName_then_usesValue(boolean key) {
Map<String, String> options = Map.of(
(key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT,
(key ? OPTION_KEY_CLASS : ... |
public static Map<String, Object> map(Object... objects) {
if (objects.length % 2 != 0) {
throw new FlowableIllegalArgumentException("The input should always be even since we expect a list of key-value pairs!");
}
Map<String, Object> map = new HashMap<>();
for (int i = 0; i... | @Test
void mapOddNumberOfParameters() {
assertThatThrownBy(() -> CollectionUtil.map("key"))
.isInstanceOf(FlowableIllegalArgumentException.class)
.hasMessage("The input should always be even since we expect a list of key-value pairs!");
assertThatThrownBy(() -> Colle... |
@Override
public boolean init( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) {
Preconditions.checkNotNull( stepMetaInterface );
variablizedStepMeta = (BaseStreamStepMeta) stepMetaInterface;
variablizedStepMeta.setParentStepMeta( getStepMeta() );
variablizedStepMeta.setFile... | @Test
public void testInitFilenameSubstitution() throws IOException {
// verifies that filename resolution uses the parents ${Internal.Entry.Current.Directory}.
// Necessary since the Current.Directory may change when running non-locally.
// Variables should all be set in variableizedStepMeta after init, ... |
public List<String> toBatchTaskArgumentString() {
List<String> res = new ArrayList<>(Arrays.asList(
CLUSTER_LIMIT_FLAG, String.valueOf(mClusterLimit),
CLUSTER_START_DELAY_FLAG, mClusterStartDelay,
BENCH_TIMEOUT, mBenchTimeout,
START_MS_FLAG, String.valueOf(mStartMs)));
if (!mPro... | @Test
public void parseSingleParametersToArgument() throws Exception {
// test single parameter
List<String[]> inputArgs = Arrays.asList(
new String[]{"--cluster-limit", "4"},
new String[]{"--cluster-start-delay", "5s"},
new String[]{"--profile-agent", "TestProfile"},
new Strin... |
@Override
public V getAndExpire(Instant time) {
return get(getAndExpireAsync(time));
} | @Test
public void testGetAndExpire() throws InterruptedException {
RBucket<Integer> al = redisson.getBucket("test");
al.set(1);
assertThat(al.getAndExpire(Duration.ofSeconds(1))).isEqualTo(1);
Thread.sleep(500);
assertThat(al.get()).isEqualTo(1);
Thread.sleep(600);
... |
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) {
String urlPath = "apps/" + appName + '/' + id;
Response response = null;
try {
WebTarget webResource = jerseyClient.target(serviceUrl)
... | @Test
public void testHeartbeatReplicationWithResponseBody() throws Exception {
InstanceInfo remoteInfo = new InstanceInfo(this.instanceInfo);
remoteInfo.setStatus(InstanceStatus.DOWN);
byte[] responseBody = toGzippedJson(remoteInfo);
serverMockClient.when(
request()... |
@Override
public RouteContext route(final ShardingRule shardingRule) {
RouteContext result = new RouteContext();
String dataSourceName = getDataSourceName(shardingRule.getDataSourceNames());
RouteMapper dataSourceMapper = new RouteMapper(dataSourceName, dataSourceName);
if (logicTabl... | @Test
void assertRoutingForShardingTable() {
RouteContext actual = new ShardingUnicastRoutingEngine(mock(SQLStatementContext.class), Collections.singleton("t_order"), new ConnectionContext(Collections::emptySet)).route(shardingRule);
assertThat(actual.getRouteUnits().size(), is(1));
assertFa... |
@Override
public String getName() {
return _name;
} | @Test
public void testStringPadTransformFunction() {
int padLength = 50;
String padString = "#";
ExpressionContext expression = RequestContextUtils.getExpression(
String.format("lpad(%s, %d, '%s')", STRING_ALPHANUM_SV_COLUMN, padLength, padString));
TransformFunction transformFunction = Transf... |
public void addEdge(V from, V to) {
addVertex(from);
addVertex(to);
neighbors.get(from).add(to);
} | @Test
void addEdge() {
graph.addEdge('B', 'G');
List<Character> result = graph.getNeighbors('B');
List<Character> expected = Arrays.asList('C', 'F', 'G');
assertEquals(expected, result);
} |
@Override
public void loadData(Priority priority, DataCallback<? super T> callback) {
this.callback = callback;
serializer.startRequest(priority, url, this);
} | @Test
public void testRequestComplete_withNon200StatusCode_callsCallbackWithException()
throws Exception {
UrlResponseInfo info = getInfo(0, HttpURLConnection.HTTP_INTERNAL_ERROR);
fetcher.loadData(Priority.LOW, callback);
UrlRequest.Callback urlCallback = urlRequestListenerCaptor.getValue();
su... |
@ConstantFunction(name = "subtract", argTypes = {INT, INT}, returnType = INT, isMonotonic = true)
public static ConstantOperator subtractInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt(Math.subtractExact(first.getInt(), second.getInt()));
} | @Test
public void subtractInt() {
assertEquals(0,
ScalarOperatorFunctions.subtractInt(O_INT_10, O_INT_10).getInt());
} |
@Override
public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return leftJoin(otherStream, toValueJoinerWi... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullOtherStreamOnLeftJoin() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.leftJoin(null, MockValueJoiner.TOSTRING_JOINER, JoinWindows.of(ofMillis(10))));
... |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (bizConfig.isAdminServiceAccessControlEnabled()) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res... | @Test
public void testWithConfigChanged() throws Exception {
String someToken = "someToken";
String anotherToken = "anotherToken";
String yetAnotherToken = "yetAnotherToken";
// case 1: init state
when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true);
when(bizConfig.getAdminSe... |
public static <T> int lastIndexOfSub(T[] array, T[] subArray) {
if (isEmpty(array) || isEmpty(subArray)) {
return INDEX_NOT_FOUND;
}
return lastIndexOfSub(array, array.length - 1, subArray);
} | @Test
public void lastIndexOfSubTest() {
Integer[] a = {0x12, 0x34, 0x56, 0x78, 0x9A};
Integer[] b = {0x56, 0x78};
Integer[] c = {0x12, 0x56};
Integer[] d = {0x78, 0x9A};
Integer[] e = {0x78, 0x9A, 0x10};
int i = ArrayUtil.lastIndexOfSub(a, b);
assertEquals(2, i);
i = ArrayUtil.lastIndexOfSub(a, c);
... |
@Override
protected CouchbaseEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
CouchbaseEndpoint endpoint = new CouchbaseEndpoint(uri, remaining, this);
setProperties(endpoint, parameters);
return endpoint;
} | @Test
public void testCouchbaseDuplicateAdditionalHosts() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("additionalHosts", "127.0.0.1,localhost, localhost");
params.put("bucket", "bucket");
String uri = "couchbase:http://localhost";
String remain... |
public final void isNotNaN() {
if (actual == null) {
failWithActual(simpleFact("expected a float other than NaN"));
} else {
isNotEqualTo(NaN);
}
} | @Test
public void isNotNaNIsNull() {
expectFailureWhenTestingThat(null).isNotNaN();
assertFailureKeys("expected a float other than NaN", "but was");
} |
public boolean overlaps(final BoundingBox pBoundingBox, double pZoom) {
//FIXME this is a total hack but it works around a number of issues related to vertical map
//replication and horiztonal replication that can cause polygons to completely disappear when
//panning
if (pZoom < 3)
... | @Test
public void testSouthernBoundsSimple() {
//item's southern bounds is just out of view
BoundingBox view = new BoundingBox(2, 2, -2, -2);
BoundingBox item = new BoundingBox(1, 1, 2.1, -1);
Assert.assertTrue(view.overlaps(item, 4));
} |
@Override
public String getAELSafeURIString() {
return resolvedFileObject.getPublicURIString().replaceFirst( "s3://", "s3a://" );
} | @Test
public void testGetAELSafeURIString() {
when( resolvedFileObject.getPublicURIString() ).thenReturn( "s3://bucket" );
assertEquals( "s3a://bucket", fileObject.getAELSafeURIString() );
} |
public CqExtUnit get(final long address) {
CqExtUnit cqExtUnit = new CqExtUnit();
if (get(address, cqExtUnit)) {
return cqExtUnit;
}
return null;
} | @Test
public void testGet() {
ConsumeQueueExt consumeQueueExt = genExt();
putSth(consumeQueueExt, false, false, UNIT_COUNT);
try {
// from start.
long addr = consumeQueueExt.decorate(0);
ConsumeQueueExt.CqExtUnit unit = new ConsumeQueueExt.CqExtUnit();
... |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldBuildSchemaWithImplicitKeyFieldForStream() {
// Given:
final CreateStream statement = new CreateStream(SOME_NAME, STREAM_ELEMENTS, false, true,
withProperties, false);
// When:
final CreateStreamCommand result = createSourceFactory.createStreamCommand(
statemen... |
public static long getTimeInHour(long ms) {
return ms - ms % HOUR_IN_MILL;
} | @Test
public void testGetTimeInHour() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2019-04-18 15:32:33");
long timeInHour = TimeUtils.getTimeInHour(date.getTime());
Assert.assertEquals("2019-04-18 15:00:00", sdf.fo... |
public KsqlEntityList execute(
final KsqlSecurityContext securityContext,
final List<ParsedStatement> statements,
final SessionProperties sessionProperties
) {
final KsqlEntityList entities = new KsqlEntityList();
for (final ParsedStatement parsed : statements) {
final PreparedStatemen... | @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT")
@Test
public void shouldCallPrepareStatementWithEmptySessionVariablesIfSubstitutionDisabled() {
// Given
final StatementExecutor<CreateStream> customExecutor =
givenReturningExecutor(CreateStream.class, mock(KsqlEntity.class));
givenR... |
@Override
public Type determine(final BackgroundException failure) {
if(log.isDebugEnabled()) {
log.debug(String.format("Determine cause for failure %s", failure));
}
for(Throwable cause : ExceptionUtils.getThrowableList(failure)) {
if(failure instanceof UnsupportedEx... | @Test
public void testDetermine() {
assertEquals(FailureDiagnostics.Type.application, new DefaultFailureDiagnostics().determine(null));
assertEquals(FailureDiagnostics.Type.network, new DefaultFailureDiagnostics().determine(new ResolveFailedException("d", null)));
assertEquals(FailureDiagnos... |
public static Map<String, Object> getTopologySummary(TopologyPageInfo topologyPageInfo,
String window, Map<String, Object> config, String remoteUser) {
Map<String, Object> result = new HashMap();
Map<String, Object> topologyConf = (Map<String, Obj... | @Test
void test_getTopologySpoutAggStatsMap_includesLastError() {
// Define inputs
final String expectedSpoutId = "MySpoutId";
final String expectedErrorMsg = "This is my test error message";
final int expectedErrorTime = Time.currentTimeSecs();
final int errorElapsedTimeSecs... |
public TargetAssignmentResult build() throws PartitionAssignorException {
Map<String, MemberSubscriptionAndAssignmentImpl> memberSpecs = new HashMap<>();
// Prepare the member spec for all members.
members.forEach((memberId, member) ->
memberSpecs.put(memberId, createMemberSubscript... | @Test
public void testReplaceStaticMember() {
TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
"my-group",
20
);
Uuid fooTopicId = context.addTopicMetadata("foo", 6, Collections.emptyMap());
Uuid barTopicId = context.addTop... |
public XADataSource swap(final DataSource dataSource) {
XADataSource result = createXADataSource();
setProperties(result, getDatabaseAccessConfiguration(dataSource));
return result;
} | @Test
void assertSwap() {
DataSourceSwapper swapper = new DataSourceSwapper(xaDataSourceDefinition);
assertResult(swapper.swap(new MockedDataSource()));
} |
public String getProperty(String name) {
return properties.getProperty(name);
} | @Test
public void getProperty() {
assertNull(new MapStoreConfig().getProperty("a"));
} |
public List<HistoryKey> getCurrentHistory() {
if (mLoadedKeys.size() == 0)
// For a unknown reason, we cannot have 0 history emoji...
mLoadedKeys.add(new HistoryKey(DEFAULT_EMOJI, DEFAULT_EMOJI));
return Collections.unmodifiableList(mLoadedKeys);
} | @Test
public void testLoadMoreThanLimit() {
StringBuilder exceedString = new StringBuilder();
for (int i = 0; i < QuickKeyHistoryRecords.MAX_LIST_SIZE * 2; i++) {
exceedString
.append(Integer.toString(2 * i))
.append(QuickKeyHistoryRecords.HISTORY_TOKEN_SEPARATOR)
.append(I... |
public TableMetaData revise(final TableMetaData originalMetaData) {
Optional<? extends TableNameReviser<T>> tableNameReviser = reviseEntry.getTableNameReviser();
String revisedTableName = tableNameReviser.map(optional -> optional.revise(originalMetaData.getName(), rule)).orElse(originalMetaData.getName(... | @SuppressWarnings("unchecked")
@Test
void assertGetOriginalTableName() {
Collection<ColumnMetaData> columns = new LinkedList<>();
columns.add(new ColumnMetaData("column1", 2, true, true, true, false, false, false));
Collection<IndexMetaData> indexes = new LinkedList<>();
indexes.... |
@Override
@Cacheable(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#id", unless = "#result == null")
public MailAccountDO getMailAccountFromCache(Long id) {
return getMailAccount(id);
} | @Test
public void testGetMailAccountFromCache() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailAccount.getId();
// 调用
MailAccountDO mailAccount =... |
@Override
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return join(otherStream, toValueJoinerWithKey(joiner), w... | @Test
public void shouldNotAllowNullValueJoinerWithKeyOnJoinWithGlobalTable() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(testGlobalTable, MockMapper.selectValueMapper(), (ValueJoinerWithKey<? super String, ? super String, ... |
@CanIgnoreReturnValue
public GsonBuilder setVersion(double version) {
if (Double.isNaN(version) || version < 0.0) {
throw new IllegalArgumentException("Invalid version: " + version);
}
excluder = excluder.withVersion(version);
return this;
} | @Test
public void testSetVersionInvalid() {
GsonBuilder builder = new GsonBuilder();
var e = assertThrows(IllegalArgumentException.class, () -> builder.setVersion(Double.NaN));
assertThat(e).hasMessageThat().isEqualTo("Invalid version: NaN");
e = assertThrows(IllegalArgumentException.class, () -> bui... |
public static String stripLeadingAndTrailingQuotes(String str) {
int length = str.length();
if (length > 1 && str.startsWith("\"") && str.endsWith("\"")) {
str = str.substring(1, length - 1);
}
return str;
} | @Test
public void stripLeadingAndTrailingQuotes() throws Exception {
assertEquals("", CommonUtils.stripLeadingAndTrailingQuotes(""));
assertEquals("\"", CommonUtils.stripLeadingAndTrailingQuotes("\""));
assertEquals("", CommonUtils.stripLeadingAndTrailingQuotes("\"\""));
assertEquals("\"", CommonUtils... |
@Override
public OAuth2CodeDO consumeAuthorizationCode(String code) {
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code);
if (codeDO == null) {
throw exception(OAUTH2_CODE_NOT_EXISTS);
}
if (DateUtils.isExpired(codeDO.getExpiresTime())) {
throw exceptio... | @Test
public void testConsumeAuthorizationCode_null() {
// 调用,并断言
assertServiceException(() -> oauth2CodeService.consumeAuthorizationCode(randomString()),
OAUTH2_CODE_NOT_EXISTS);
} |
public static String removeCharacter(String str, char charToRemove) {
if (str == null || str.indexOf(charToRemove) == -1) {
return str;
}
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != charToRemove) ... | @Test
void when_removingNotExistingCharactersFromString_then_sameInstanceIsReturned() {
assertSame("-------", StringUtil.removeCharacter("-------", '0'));
} |
@Override
public void registerRecoveryResource(final String dataSourceName, final XADataSource xaDataSource) {
if (null != xaRecoveryModule) {
xaRecoveryModule.addXAResourceRecoveryHelper(new DataSourceXAResourceRecoveryHelper(xaDataSource));
}
} | @Test
void assertRegisterRecoveryResource() {
transactionManagerProvider.registerRecoveryResource("ds1", xaDataSource);
verify(xaRecoveryModule).addXAResourceRecoveryHelper(any(DataSourceXAResourceRecoveryHelper.class));
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
ctx.logJsEvalRequest();
withCallback(scriptEngine.executeFilterAsync(msg),
filterResult -> {
ctx.logJsEvalResponse();
ctx.tellNext(msg, filterResult ? TbNodeConnectionType.TRUE : TbNodeCon... | @Test
public void metadataConditionCanBeTrue() throws TbNodeException {
initWithScript();
TbMsgMetaData metaData = new TbMsgMetaData();
TbMsg msg = TbMsg.newMsg(TbMsgType.POST_TELEMETRY_REQUEST, null, metaData, TbMsgDataType.JSON, TbMsg.EMPTY_JSON_OBJECT, ruleChainId, ruleNodeId);
wh... |
public static Catalog createCatalog(
String catalogName,
Map<String, String> options,
ReadableConfig configuration,
ClassLoader classLoader) {
// Use the legacy mechanism first for compatibility
try {
final CatalogFactory legacyFactory =
... | @Test
void testCreateCatalog() {
final Map<String, String> options = new HashMap<>();
options.put(CommonCatalogOptions.CATALOG_TYPE.key(), TestCatalogFactory.IDENTIFIER);
options.put(TestCatalogFactory.DEFAULT_DATABASE.key(), "my-database");
final Catalog catalog =
F... |
@Udf
public String chr(@UdfParameter(
description = "Decimal codepoint") final Integer decimalCode) {
if (decimalCode == null) {
return null;
}
if (!Character.isValidCodePoint(decimalCode)) {
return null;
}
final char[] resultChars = Character.toChars(decimalCode);
return Str... | @Test
public void shouldReturnNullForNegativeDecimalCode() {
final String result = udf.chr(-1);
assertThat(result, is(nullValue()));
} |
@VisibleForTesting
static void enforceStreamStateDirAvailability(final File streamsStateDir) {
if (!streamsStateDir.exists()) {
final boolean mkDirSuccess = streamsStateDir.mkdirs();
if (!mkDirSuccess) {
throw new KsqlServerException("Could not create the kafka streams state directory: "
... | @Test
public void shouldFailIfStreamsStateDirectoryIsNotWritable() {
// Given:
when(mockStreamsStateDir.canWrite()).thenReturn(false);
// When:
final Exception e = assertThrows(
KsqlServerException.class,
() -> KsqlServerMain.enforceStreamStateDirAvailability(mockStreamsStateDir)
... |
@Override
public synchronized void cleanupAll() {
LOG.info("Attempting to cleanup MongoDB manager.");
boolean producedError = false;
// First, delete the database if it was not given as a static argument
try {
if (!usingStaticDatabase) {
mongoClient.getDatabase(databaseName).drop();
... | @Test
public void testCleanupAllShouldThrowErrorWhenMongoClientFailsToClose() {
doThrow(RuntimeException.class).when(mongoClient).close();
assertThrows(MongoDBResourceManagerException.class, () -> testManager.cleanupAll());
} |
@SuppressWarnings("unchecked")
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, CircuitBreaker circuitBreaker,
String methodName) throws Throwable {
CircuitBreakerOperator circuitBreakerOperator = CircuitBreakerOperator.of(circuitBreaker);
Object returnValue = proc... | @Test
public void testReactorTypes() throws Throwable {
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava2CircuitBreakerAspectExt
.handle(proceedingJoinPoint, circuitBreaker, ... |
public static byte[] getSolicitNodeAddress(byte[] targetIp) {
checkArgument(targetIp.length == Ip6Address.BYTE_LENGTH);
return new byte[] {
(byte) 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, (byte) 0xff,
targetIp[targetIp.length... | @Test
public void testSolicitationNodeAddress() {
assertArrayEquals(SOLICITATION_NODE_ADDRESS, getSolicitNodeAddress(DESTINATION_ADDRESS));
} |
@Override
public UpdateSchema makeColumnOptional(String name) {
internalUpdateColumnRequirement(name, true);
return this;
} | @Test
public void testMakeColumnOptional() {
Schema schema = new Schema(required(1, "id", Types.IntegerType.get()));
Schema expected = new Schema(optional(1, "id", Types.IntegerType.get()));
Schema result = new SchemaUpdate(schema, 1).makeColumnOptional("id").apply();
assertThat(result.asStruct()).i... |
public ConfigCenterBuilder timeout(Long timeout) {
this.timeout = timeout;
return getThis();
} | @Test
void timeout() {
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.timeout(1000L);
Assertions.assertEquals(1000L, builder.build().getTimeout());
} |
public static DisruptContext timeout()
{
return new TimeoutDisruptContext();
} | @Test
public void testTimeout()
{
DisruptContexts.TimeoutDisruptContext context =
(DisruptContexts.TimeoutDisruptContext) DisruptContexts.timeout();
Assert.assertEquals(context.mode(), DisruptMode.TIMEOUT);
} |
@NonNull
@Override
public HealthResponse healthResponse(final Map<String, Collection<String>> queryParams) {
final String type = queryParams.getOrDefault(CHECK_TYPE_QUERY_PARAM, Collections.emptyList())
.stream()
.findFirst()
.orElse(null);
final Collection<H... | @Test
void shouldHandleSingleHealthStateViewCorrectly() throws IOException {
// given
final HealthStateView view = new HealthStateView("foo", true, HealthCheckType.READY, true);
final Map<String, Collection<String>> queryParams = Collections.singletonMap(
JsonHealthResponseProvid... |
@Override
public void execute(SensorContext context) {
for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) {
processFileError(file, context);
}
} | @Test
public void test() throws IOException {
Path baseDir = temp.newFolder().toPath().toAbsolutePath();
createErrorFile(baseDir);
int[] startOffsets = {10, 20, 30, 40};
int[] endOffsets = {19, 29, 39, 49};
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLang... |
@Override
public AppResponse process(Flow flow, CancelFlowRequest request) {
Map<String, Object> logOptions = new HashMap<>();
if (appAuthenticator != null && appAuthenticator.getAccountId() != null) logOptions.put(lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId());
if ("upgrade_... | @Test
public void processReturnOkResponseWithAppAutheticatorAndNoRdaSession() {
mockedAppSession.setRdaSessionId(null);
Map<String, Object> logOptions = new HashMap<>();
var logCode = Map.of(
"upgrade_rda_widchecker", "1311",
"upgrade_app", "879"
);
A... |
public static String getFlowName(String activationMethod) {
return switch (activationMethod) {
case ActivationMethod.ACCOUNT -> ActivateAppWithRequestWebsite.NAME;
case ActivationMethod.PASSWORD -> ActivateAppWithPasswordLetterFlow.NAME;
case ActivationMethod.SMS -> ActivateA... | @Test
void getFlowNameTest() {
String result = flowService.getFlowName(ActivationMethod.RDA);
assertEquals(ActivateAppWithPasswordRdaFlow.NAME, result);
} |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_map_of_string_to_string__throws_exception__more_then_one_value_per_key() {
DataTable table = parse("",
"| KMSY | 29.993333 | -90.258056 |",
"| KSFO | 37.618889 | -122.375 |",
"| KSEA | 47.448889 | -122.309444 |",
"| KJFK | 40.639722 |... |
public void assertNonNegative() {
if(value < 0)
throw new IllegalStateException("non negative value required");
} | @Test(expected=IllegalStateException.class)
public void negativeQuantity_throwsIllegalStateExceptionOnCheckForNonNegative() throws Exception {
Quantity<Metrics> negative = new Quantity<Metrics>(-1, Metrics.cm);
negative.assertNonNegative();
} |
@Override
public Catalog createCatalog(Context context) {
final FactoryUtil.CatalogFactoryHelper helper =
FactoryUtil.createCatalogFactoryHelper(this, context);
helper.validate();
return new HiveCatalog(
context.getName(),
helper.getOptions().... | @Test
public void testCreateMultipleHiveCatalog() throws Exception {
final Map<String, String> props1 = new HashMap<>();
props1.put(CommonCatalogOptions.CATALOG_TYPE.key(), HiveCatalogFactoryOptions.IDENTIFIER);
props1.put(
HiveCatalogFactoryOptions.HIVE_CONF_DIR.key(),
... |
@Activate
public void activate() {
localNodeId = clusterService.getLocalNode().id();
leadershipService.addListener(leaderListener);
listenerRegistry = new ListenerRegistry<>();
eventDispatcher.addSink(WorkPartitionEvent.class, listenerRegistry);
for (int i = 0; i < NUM_PART... | @Test
public void testActivate() {
reset(leadershipService);
leadershipService.addListener(anyObject(LeadershipEventListener.class));
for (int i = 0; i < WorkPartitionManager.NUM_PARTITIONS; i++) {
expect(leadershipService.runForLeadership(ELECTION_PREFIX + i))
... |
void createOutputValueMapping() throws KettleException {
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields( getInputRowMeta(), getStepname(), null, null, this, repository, metaStore );
data.fieldIndex = getInputRowMeta().indexOfValue( meta.getFieldname() );
if ( data.fieldIndex < 0 ) {
... | @Test
public void testCreateOutputValueMapping() throws KettleException, URISyntaxException,
ParserConfigurationException, SAXException, IOException {
SwitchCaseCustom krasavez = new SwitchCaseCustom( mockHelper );
// load step info value-case mapping from xml.
List<DatabaseMeta> emptyList = new Arra... |
public EnumSet<E> get() {
return value;
} | @SuppressWarnings("unchecked")
@Test
public void testSerializeAndDeserializeEmpty() throws IOException {
boolean gotException = false;
try {
new EnumSetWritable<TestEnumSet>(emptyFlag);
} catch (RuntimeException e) {
gotException = true;
}
assertTrue(
"Instantiation of empt... |
@Override
public void close() {
this.internalClient.close();
ExecutorUtils.gracefulShutdown(5, TimeUnit.SECONDS, this.kubeClientExecutorService);
} | @Test
void testIOExecutorShouldBeShutDownWhenFlinkKubeClientClosed() {
final ScheduledExecutorService executorService =
Executors.newSingleThreadScheduledExecutor();
final FlinkKubeClient flinkKubeClient =
new Fabric8FlinkKubeClient(flinkConfig, kubeClient, executorSe... |
public void restore(final List<Pair<byte[], byte[]>> backupCommands) {
// Delete the command topic
deleteCommandTopicIfExists();
// Create the command topic
KsqlInternalTopicUtils.ensureTopic(commandTopicName, serverConfig, topicClient);
// Restore the commands
restoreCommandTopic(backupComman... | @Test
public void shouldCreateAndRestoreCommandTopic() throws ExecutionException, InterruptedException {
// Given:
when(topicClient.isTopicExists(COMMAND_TOPIC_NAME)).thenReturn(false);
// When:
restoreCommandTopic.restore(BACKUP_COMMANDS);
// Then:
verifyCreateCommandTopic();
final InO... |
public EventDefinitionDto createWithoutSchedule(EventDefinitionDto unsavedEventDefinition, Optional<User> user) {
return createEventDefinition(unsavedEventDefinition, user);
} | @Test
public void createWithoutSchedule() {
final EventDefinitionDto newDto = EventDefinitionDto.builder()
.title("Test")
.description("A test event definition")
.config(TestEventProcessorConfig.builder()
.message("This is a test event ... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testLowercaseOutputLabelNames() throws Exception {
new JmxCollector(
"\n---\nlowercaseOutputLabelNames: true\nrules:\n- pattern: `^hadoop<service=DataNode, name=DataNodeActivity-ams-hdd001-50010><>replaceBlockOpMinTime:`\n name: Foo\n labels:\n ABC: DEF"
... |
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (listClass != null || inner != null) {
log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner);
throw new ConfigException("List dese... | @Test
public void testListValueDeserializerNoArgConstructorsShouldThrowConfigExceptionDueMissingTypeClassProp() {
props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_INNER_CLASS, Serdes.StringSerde.class);
final ConfigException exception = assertThrows(
ConfigException.class,
... |
@Override
public void putJobGraph(JobGraph jobGraph) throws Exception {
checkNotNull(jobGraph, "Job graph");
final JobID jobID = jobGraph.getJobID();
final String name = jobGraphStoreUtil.jobIDToName(jobID);
LOG.debug("Adding job graph {} to {}.", jobID, jobGraphStateHandleStore);
... | @Test
public void testOnAddedJobGraphShouldNotProcessKnownJobGraphs() throws Exception {
final TestingStateHandleStore<JobGraph> stateHandleStore =
builder.setAddFunction((ignore, state) -> jobGraphStorageHelper.store(state))
.build();
final JobGraphStore jobG... |
public String translate(String text, String targetLanguage) throws TikaException, IOException {
String sourceLanguage = detectLanguage(text).getLanguage();
return translate(text, sourceLanguage, targetLanguage);
} | @Test
public void testNoConfig() throws Exception {
String source = "Apache Tika is a wonderful tool";
String expected =
"Apache Tika is a wonderful tool"; // Pattern from other Translators is to return source
String translated = translator.translate(source, "en", "zz");
... |
@Override
public StringBuffer format(Object obj, StringBuffer result, FieldPosition pos) {
return format.format(toArgs((Attributes) obj), result, pos);
} | @Test
public void testFormatMD5() {
Attributes attrs = new Attributes();
attrs.setString(Tag.StudyDate, VR.DA, "20111012");
attrs.setString(Tag.StudyTime, VR.TM, "0930");
attrs.setString(Tag.StudyInstanceUID, VR.UI, "1.2.3");
attrs.setString(Tag.SeriesInstanceUID, VR.UI, "1.2... |
public int tryClaim(final int msgTypeId, final int length)
{
checkTypeId(msgTypeId);
checkMsgLength(length);
final AtomicBuffer buffer = this.buffer;
final int recordLength = length + HEADER_LENGTH;
final int recordIndex = claimCapacity(buffer, recordLength);
if (IN... | @Test
void tryClaimReturnsIndexAtWhichEncodedMessageStarts()
{
final int length = 10;
final int recordLength = length + HEADER_LENGTH;
final int alignedRecordLength = align(recordLength, ALIGNMENT);
final long headPosition = 248L;
final long tailPosition = 320L;
f... |
static void validateDependencies(Set<Artifact> dependencies, Set<String> allowedRules, boolean failOnUnmatched)
throws EnforcerRuleException {
SortedSet<Artifact> unmatchedArtifacts = new TreeSet<>();
Set<String> matchedRules = new HashSet<>();
for (Artifact dependency : dependencies... | @Test
void matches_on_version_in_allowed_range() {
var dependencies = Set.of(
artifact("com.yahoo.testing", "test", "1.2.3", "compile"));
var rules = Set.of("com.yahoo.testing:test:jar:[1.0,2):compile");
assertDoesNotThrow(() -> EnforceDependencies.validateDependencies(depend... |
static SortKey[] rangeBounds(
int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) {
// sort the keys first
Arrays.sort(samples, comparator);
int numCandidates = numPartitions - 1;
SortKey[] candidates = new SortKey[numCandidates];
int step = (int) Math.ceil((double) sample... | @Test
public void testRangeBoundsOneChannel() {
assertThat(
SketchUtil.rangeBounds(
1,
SORT_ORDER_COMPARTOR,
new SortKey[] {
CHAR_KEYS.get("a"),
CHAR_KEYS.get("b"),
CHAR_KEYS.get("c"),
... |
static String guessIcon(String iconGuess, String rootURL) {
String iconSource;
//noinspection HttpUrlsUsage
if (iconGuess.startsWith("http://") || iconGuess.startsWith("https://")) {
iconSource = iconGuess;
} else {
if (!iconGuess.startsWith("/")) {
... | @Test
public void guessIcon() throws Exception {
Jenkins.RESOURCE_PATH = "/static/12345678";
assertEquals("/jenkins/static/12345678/images/48x48/green.gif", Functions.guessIcon("jenkins/images/48x48/green.gif", "/jenkins"));
assertEquals("/jenkins/static/12345678/images/48x48/green.gif", Fun... |
public Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
Marshaller marshaller = getContext(clazz).createMarshaller();
setMarshallerProperties(marshaller);
if (marshallerEventHandler != null) {
marshaller.setEventHandler(marshallerEventHandler);
}
marshaller.setSchema(marshall... | @Test
void buildsMarshallerWithNoNamespaceSchemaLocationProperty() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder()
.withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd").build();
Marshaller marshaller = factory.createMarshaller(Object.class)... |
List<Integer> allocatePorts(NetworkPortRequestor service, int wantedPort) {
PortAllocBridge allocator = new PortAllocBridge(this, service);
service.allocatePorts(wantedPort, allocator);
return allocator.result();
} | @Test
void allocating_same_port_throws_exception() {
assertThrows(RuntimeException.class, () -> {
HostPorts host = new HostPorts("myhostname");
MockRoot root = new MockRoot();
TestService service1 = new TestService(root, 1);
TestService service2 = new TestServ... |
protected void gatherBestRouteCoverages() {
// get a de-duplicated list of the routes
testResults.forEach(testResult -> {
List<Route> routeList = testResult.getCamelContextRouteCoverage().getRoutes().getRouteList();
routeList.forEach(route -> {
String routeId =... | @Test
public void testGatherBestRouteCoverages() throws IllegalAccessException, IOException {
@SuppressWarnings("unchecked")
List<TestResult> testResults = (List<TestResult>) FieldUtils.readDeclaredField(processor, "testResults", true);
@SuppressWarnings("unchecked")
Map<String, Rou... |
@Override
public void runExclusively(Runnable runnable) {
lock.lock();
try {
runnable.run();
} finally {
lock.unlock();
}
} | @Test
void testRunExclusively() throws InterruptedException {
CountDownLatch exclusiveCodeStarted = new CountDownLatch(1);
final int numMails = 10;
// send 10 mails in an atomic operation
new Thread(
() ->
taskMailbox.runExclu... |
protected abstract Source.Reader<T> createReader(@Nonnull FlinkSourceSplit<T> sourceSplit)
throws IOException; | @Test
public void testNumBytesInMetrics() throws Exception {
final int numSplits = 2;
final int numRecordsPerSplit = 10;
List<FlinkSourceSplit<KV<Integer, Integer>>> splits =
createSplits(numSplits, numRecordsPerSplit, 0);
SourceTestMetrics.TestMetricGroup testMetricGroup = new SourceTestMetri... |
@Override
public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return leftJoin(otherStream, toValueJoinerWi... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullStreamJoinedOnLeftJoin() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.leftJoin(
testStream,
MockValueJoiner.TOSTRING_JOINER,... |
public void parse(DataByteArrayInputStream input, int readSize) throws Exception {
if (currentParser == null) {
currentParser = initializeHeaderParser();
}
// Parser stack will run until current incoming data has all been consumed.
currentParser.parse(input, readSize);
} | @Test
public void testMessageDecoding() throws Exception {
byte[] CONTENTS = new byte[MESSAGE_SIZE];
for (int i = 0; i < MESSAGE_SIZE; i++) {
CONTENTS[i] = 'a';
}
PUBLISH publish = new PUBLISH();
publish.dup(false);
publish.messageId((short) 127);
... |
public BigDecimal calculateTDEE(ActiveLevel activeLevel) {
if(activeLevel == null) return BigDecimal.valueOf(0);
BigDecimal multiplayer = BigDecimal.valueOf(activeLevel.getMultiplayer());
return multiplayer.multiply(BMR).setScale(2, RoundingMode.HALF_DOWN);
} | @Test
void calculateTDEE_SUPER_ACTIVE() {
BigDecimal TDEE = bmrCalculator.calculate(attributes).calculateTDEE(ActiveLevel.SUPER);
assertEquals(new BigDecimal("3880.75"), TDEE);
} |
public void processOnce() throws IOException {
// set status of query to OK.
ctx.getState().reset();
executor = null;
// reset sequence id of MySQL protocol
final MysqlChannel channel = ctx.getMysqlChannel();
channel.setSequenceId(0);
// read packet from channel
... | @Test
public void testInitWarehouse() throws IOException {
ConnectContext ctx = initMockContext(mockChannel(initWarehousePacket), GlobalStateMgr.getCurrentState());
ctx.setCurrentUserIdentity(UserIdentity.ROOT);
ctx.setQualifiedUser(AuthenticationMgr.ROOT_USER);
ConnectProcessor proc... |
@Override
public void onRenamed(Item item, String oldName, String newName) {
// bug 5077308 - Display name field should be cleared when you rename a job.
if (item instanceof AbstractItem) {
AbstractItem abstractItem = (AbstractItem) item;
if (oldName.equals(abstractItem.getDi... | @Test
public void testOnRenamedOldNameNotEqualDisplayName() throws Exception {
DisplayNameListener listener = new DisplayNameListener();
final String oldName = "old job name";
final String newName = "new job name";
final String displayName = "the display name";
StubJob src = ... |
String formatStepText(
String keyword, String stepText, Format textFormat, Format argFormat, List<Argument> arguments
) {
int beginIndex = 0;
StringBuilder result = new StringBuilder(textFormat.text(keyword));
for (Argument argument : arguments) {
// can be null if th... | @Test
void should_mark_nested_arguments_as_part_of_enclosing_argument() {
Formats formats = ansi();
PrettyFormatter prettyFormatter = new PrettyFormatter(new ByteArrayOutputStream());
StepTypeRegistry registry = new StepTypeRegistry(Locale.ENGLISH);
StepExpressionFactory stepExpressi... |
@Override
public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context,
Map<String, Long> recentlyUnloadedBundles,
Map<String, Long> recentlyUnloadedBrokers) {
final var conf = context.broker... | @Test
public void testTargetStdAfterTransfer() {
UnloadCounter counter = new UnloadCounter();
TransferShedder transferShedder = new TransferShedder(counter);
var ctx = setupContext();
var brokerLoadDataStore = ctx.brokerLoadDataStore();
brokerLoadDataStore.pushAsync("broker4:... |
@Override
public Charset detect(InputStream input, Metadata metadata) throws IOException {
input.mark(MAX_BYTES);
byte[] bytes = new byte[MAX_BYTES];
try {
int numRead = IOUtils.read(input, bytes);
if (numRead < MIN_BYTES) {
return null;
} ... | @Test
public void testShort() throws Exception {
EncodingDetector detector = new BOMDetector();
for (ByteOrderMark bom : new ByteOrderMark[] {
ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
ByteOrderMark.UTF_32LE
}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.