focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public boolean isReasonablyCertain() {
return distance < CERTAINTY_LIMIT;
} | @Test
public void testMixedLanguages() throws IOException {
for (String language : languages) {
for (String other : languages) {
if (!language.equals(other)) {
if (language.equals("lt") || other.equals("lt")) {
continue;
... |
public static <T> T[] getBeans(Class<T> interfaceClass) {
Object object = serviceMap.get(interfaceClass.getName());
if(object == null) return null;
if(object instanceof Object[]) {
return (T[])object;
} else {
Object array = Array.newInstance(interfaceClass, 1);
... | @Test
public void testMultipleToMultiple() {
E[] e = SingletonServiceFactory.getBeans(E.class);
Arrays.stream(e).forEach(o -> logger.debug(o.e()));
F[] f = SingletonServiceFactory.getBeans(F.class);
Arrays.stream(f).forEach(o -> logger.debug(o.f()));
} |
public TbMsgMetaData copy() {
return new TbMsgMetaData(this.data);
} | @Test
public void testScript_whenMetadataWithPropertiesValueNull_returnMetadataWithoutPropertiesValueEqualsNull() {
metadataExpected.put("deviceName", null);
TbMsgMetaData tbMsgMetaData = new TbMsgMetaData(metadataExpected);
Map<String, String> dataActual = tbMsgMetaData.copy().getData();
... |
private SelectorData buildDefaultSelectorData(final SelectorData selectorData) {
if (StringUtils.isEmpty(selectorData.getId())) {
selectorData.setId(UUIDUtils.getInstance().generateShortUuid());
}
if (StringUtils.isEmpty(selectorData.getName())) {
selectorData.setName(sel... | @Test
public void testBuildDefaultSelectorData() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method buildDefaultSelectorData = LocalPluginController.class.getDeclaredMethod("buildDefaultSelectorData", SelectorData.class);
buildDefaultSelectorData.setAccessible(t... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest httpRequest) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
chain.doFilter(new Servle... | @Test
public void throwable_in_doFilter_is_caught_and_500_error_returned_if_response_is_not_committed() throws Exception {
doThrow(new RuntimeException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
HttpServletResponse response = mockHttpResponse(false);
underTest.doFilter... |
public void removeJobMetricsGroup(JobID jobId) {
if (jobId != null) {
TaskManagerJobMetricGroup groupToClose;
synchronized (this) { // synchronization isn't strictly necessary as of FLINK-24864
groupToClose = jobs.remove(jobId);
}
if (groupToClose ... | @Test
void testRemoveNullJobID() {
metricGroup.removeJobMetricsGroup(null);
} |
public static boolean isContentType(String contentType, Message message) {
if (contentType == null) {
return message.getContentType() == null;
} else {
return contentType.equals(message.getContentType());
}
} | @Test
public void testIsContentTypeWithNonNullStringValueAndNonNullMessageContentTypeNotEqual() {
Message message = Proton.message();
message.setContentType("fails");
assertFalse(AmqpMessageSupport.isContentType("test", message));
} |
List<MethodSpec> buildEventFunctions(
AbiDefinition functionDefinition, TypeSpec.Builder classBuilder)
throws ClassNotFoundException {
String functionName = functionDefinition.getName();
List<AbiDefinition.NamedType> inputs = functionDefinition.getInputs();
String respons... | @Test
public void testBuildEventConstantMultipleValueReturn() throws Exception {
NamedType id = new NamedType("id", "string", true);
NamedType fromAddress = new NamedType("from", "address");
NamedType toAddress = new NamedType("to", "address");
NamedType value = new NamedType("value... |
synchronized Optional<ExecutableWork> completeWorkAndGetNextWorkForKey(
ShardedKey shardedKey, WorkId workId) {
@Nullable Queue<ExecutableWork> workQueue = activeWork.get(shardedKey);
if (workQueue == null) {
// Work may have been completed due to clearing of stuck commits.
LOG.warn("Unable to... | @Test
public void testCompleteWorkAndGetNextWorkForKey_noWorkQueueForKey() {
assertEquals(
Optional.empty(),
activeWorkState.completeWorkAndGetNextWorkForKey(
shardedKey("someKey", 1L), workId(1L, 1L)));
} |
public static Thread daemonThread(Runnable r, Class<?> context, String description) {
return daemonThread(r, "hollow", context, description);
} | @Test
public void nullRunnable() {
try {
daemonThread(null, getClass(), "boom");
fail("expected an exception");
} catch (NullPointerException e) {
assertEquals("runnable required", e.getMessage());
}
} |
public synchronized <K, V> KStream<K, V> stream(final String topic) {
return stream(Collections.singleton(topic));
} | @Test
public void shouldThrowWhenSubscribedToATopicWithUnsetAndSetResetPolicies() {
builder.stream("another-topic");
builder.stream("another-topic", Consumed.with(AutoOffsetReset.LATEST));
assertThrows(TopologyException.class, builder::build);
} |
@Override
public long getSetOperationCount() {
throw new UnsupportedOperationException("Set operation on replicated maps is not supported.");
} | @Test(expected = UnsupportedOperationException.class)
public void testSetOperationCount() {
localReplicatedMapStats.getSetOperationCount();
} |
@Override
public void checkBeforeUpdate(final AlterReadwriteSplittingRuleStatement sqlStatement) {
ReadwriteSplittingRuleStatementChecker.checkAlteration(database, sqlStatement.getRules(), rule.getConfiguration());
} | @Test
void assertCheckSQLStatementWithoutToBeAlteredRules() {
ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class);
when(rule.getConfiguration()).thenReturn(new ReadwriteSplittingRuleConfiguration(Collections.emptyList(), Collections.emptyMap()));
executor.setRule(rule);
... |
public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException {
long result = 0;
if (cronEntry == null || cronEntry.length() == 0) {
return result;
}
// Handle the once per minute case "* * * * *"
// starting the ne... | @Test
public void testgetNextTimeHoursZeroMin() throws MessageFormatException {
String test = "0 1 * * *";
Calendar calender = Calendar.getInstance();
calender.set(1972, 2, 2, 17, 10, 0);
long current = calender.getTimeInMillis();
long next = CronParser.getNextScheduledTime(... |
@Override
public Integer call() throws Exception {
return this.call(
Flow.class,
yamlFlowParser,
modelValidator,
(Object object) -> {
Flow flow = (Flow) object;
return flow.getNamespace() + " / " + flow.getId();
},
... | @Test
void warning() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) {
String[] args = {
"--local",
"src/t... |
public MailConfiguration getConfiguration() {
if (configuration == null) {
configuration = new MailConfiguration(getCamelContext());
}
return configuration;
} | @Test
public void testConnectionTimeout() {
MailEndpoint endpoint = checkEndpoint("smtp://james@myhost?password=secret&connectionTimeout=2500");
MailConfiguration config = endpoint.getConfiguration();
assertEquals(2500, config.getConnectionTimeout());
} |
@Override
public void increment(@Nonnull UUID txnId, boolean backup) {
if (txnId.equals(NULL_UUID)) {
return;
}
reservedCapacityCountByTxId.compute(txnId, (ignored, currentCapacityCount) -> {
if (backup) {
nodeWideUsedCapacityCounter.add(1L);
... | @Test
public void increment() {
UUID txnId = UuidUtil.newSecureUUID();
for (int i = 0; i < 11; i++) {
counter.increment(txnId, false);
}
Map<UUID, Long> countPerTxnId = counter.getReservedCapacityCountPerTxnId();
long count = countPerTxnId.get(txnId);
as... |
public String getTopicName() {
return topicName == null ? INVALID_TOPIC_NAME : topicName;
} | @Test
public void shouldUseNameFromWithClause() {
// When:
final TopicProperties properties = new TopicProperties.Builder()
.withWithClause(
Optional.of("name"),
Optional.of(1),
Optional.empty(),
Optional.of((long) 100)
)
.build();
/... |
@Override
public <T> Optional<List<T>> getListProperty(String key, Class<T> itemType) {
var targetKey = targetPropertyName(key);
var listResult = binder.bind(targetKey, Bindable.listOf(itemType));
return listResult.isBound() ? Optional.of(listResult.get()) : Optional.empty();
} | @Test
void resolvesListProperties() {
env.setProperty("prop.0.strLst", "v1,v2,v3");
env.setProperty("prop.0.intLst", "1,2,3");
var resolver = new PropertyResolverImpl(env);
assertThat(resolver.getListProperty("prop.0.strLst", String.class))
.hasValue(List.of("v1", "v2", "v3"));
assertThat... |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \... | @Test
void testInvokeMethodWithMapParameter() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willR... |
public static void rename(
List<ResourceId> srcResourceIds, List<ResourceId> destResourceIds, MoveOptions... moveOptions)
throws IOException {
validateSrcDestLists(srcResourceIds, destResourceIds);
if (srcResourceIds.isEmpty()) {
return;
}
renameInternal(
getFileSystemInternal(... | @Test
public void testRenameIgnoreMissingFiles() throws Exception {
Path srcPath1 = temporaryFolder.newFile().toPath();
Path nonExistentPath = srcPath1.resolveSibling("non-existent");
Path srcPath3 = temporaryFolder.newFile().toPath();
Path destPath1 = srcPath1.resolveSibling("dest1");
Path destP... |
public String abbreviate(String fqClassName) {
if (fqClassName == null) {
throw new IllegalArgumentException("Class name may not be null");
}
int inLen = fqClassName.length();
if (inLen < targetLength) {
return fqClassName;
}
StringBuilder buf = ... | @Test
public void testTwoDot() {
{
TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1);
String name = "com.logback.Foobar";
assertEquals("c.l.Foobar", abbreviator.abbreviate(name));
}
{
TargetLength... |
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry>... | @Test
public void testFilterAclEntriesByAclSpecAutomaticDefaultGroup()
throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, READ))
.add(aclEntry(DEFAULT... |
long useService(int value) {
var result = serviceAmbassador.doRemoteFunction(value);
LOGGER.info("Service result: {}", result);
return result;
} | @Test
void test() {
Client client = new Client();
var result = client.useService(10);
assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue());
} |
public Node parse() throws ScanException {
return E();
} | @Test
public void testNested() throws Exception {
{
Parser<Object> p = new Parser("%top %(%child%(%h))");
Node t = p.parse();
Node witness = new SimpleKeywordNode("top");
Node w = witness.next = new Node(Node.LITERAL, " ");
CompositeNode composite = new CompositeNode(BARE);
w =... |
@VisibleForTesting
public Set<NodeAttribute> parseAttributes(String config)
throws IOException {
if (Strings.isNullOrEmpty(config)) {
return ImmutableSet.of();
}
Set<NodeAttribute> attributeSet = new HashSet<>();
// Configuration value should be in one line, format:
// "ATTRIBUTE_NAME,... | @Test
public void testDisableFetchNodeAttributes() throws IOException,
InterruptedException {
Set<NodeAttribute> expectedAttributes1 = new HashSet<>();
expectedAttributes1.add(NodeAttribute
.newInstance("test.io", "host",
NodeAttributeType.STRING, "host1"));
Configuration conf =... |
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (StringUtils.isNotBlank(protocol)) {
b.append(protocol);
b.append("://");
}
if (StringUtils.isNotBlank(host)) {
b.append(host);
}
if (!isPortDefault() &&... | @Test
public void testHttpProtocolNoPort() {
s = "http://www.example.com/blah";
t = "http://www.example.com/blah";
assertEquals(t, new HttpURL(s).toString());
} |
public static LogExceptionBehaviourInterface getExceptionStrategy( LogTableCoreInterface table ) {
return getExceptionStrategy( table, null );
} | @Test public void testExceptionStrategyWithMysqlDataTruncationException() {
DatabaseMeta databaseMeta = mock( DatabaseMeta.class );
DatabaseInterface databaseInterface = new MySQLDatabaseMeta();
MysqlDataTruncation e = new MysqlDataTruncation();
when( logTable.getDatabaseMeta() ).thenReturn( databaseMe... |
@Override
public CompletableFuture<Void> deleteKvConfig(String address, DeleteKVConfigRequestHeader requestHeader,
long timeoutMillis) {
CompletableFuture<Void> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_KV_CONFIG, re... | @Test
public void assertDeleteKvConfigWithError() {
setResponseError();
DeleteKVConfigRequestHeader requestHeader = mock(DeleteKVConfigRequestHeader.class);
CompletableFuture<Void> actual = mqClientAdminImpl.deleteKvConfig(defaultBrokerAddr, requestHeader, defaultTimeout);
Throwable ... |
public void parseFile(final InputStream inStream) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, IoUtils.UTF8_CHARSET));
try {
startSheet();
processRows(reader);
finishSheet();
} catch (final IOException e) {
thr... | @Test
public void testCsv() {
final MockSheetListener listener = new MockSheetListener();
final CsvLineParser lineParser = new CsvLineParser();
final CsvParser parser = new CsvParser(listener, lineParser);
parser.parseFile(getClass().getResourceAsStream("/data/TestCsv.drl.csv"));
... |
public static int chineseToNumber(String chinese) {
final int length = chinese.length();
int result = 0;
// 节总和
int section = 0;
int number = 0;
ChineseUnit unit = null;
char c;
for (int i = 0; i < length; i++) {
c = chinese.charAt(i);
final int num = chineseToNumber(c);
if (num >= 0) {
if... | @Test
public void chineseToNumberTest3() {
// issue#1726,对于单位开头的数组,默认赋予1
// 十二 -> 一十二
// 百二 -> 一百二
assertEquals(12, NumberChineseFormatter.chineseToNumber("十二"));
assertEquals(120, NumberChineseFormatter.chineseToNumber("百二"));
assertEquals(1300, NumberChineseFormatter.chineseToNumber("千三"));
} |
public static List<TypedExpression> coerceCorrectConstructorArguments(
final Class<?> type,
List<TypedExpression> arguments,
List<Integer> emptyCollectionArgumentsIndexes) {
Objects.requireNonNull(type, "Type parameter cannot be null as the method searches constructors from t... | @Test
public void coerceCorrectConstructorArgumentsArgumentsAreNull() {
Assertions.assertThatThrownBy(
() -> MethodResolutionUtils.coerceCorrectConstructorArguments(
Person.class,
null,
nu... |
@Override public boolean isOutput() {
return false;
} | @Test
public void testIsOutput() throws Exception {
assertFalse( analyzer.isOutput() );
} |
static String getMessageForInvalidTag(String paramName) {
return String.format(
"@%1$s is not a valid tag, but is a parameter name. "
+ "Use {@code %1$s} to refer to parameter names inline.",
paramName);
} | @Test
public void invalidTagMessage() {
assertEquals(
"@type is not a valid tag, but is a parameter name. Use {@code type} to refer to parameter"
+ " names inline.",
InvalidInlineTag.getMessageForInvalidTag("type"));
} |
PartitionsOnReplicaIterator iterator(int brokerId, boolean leadersOnly) {
Map<Uuid, int[]> topicMap = isrMembers.get(brokerId);
if (topicMap == null) {
topicMap = Collections.emptyMap();
}
return new PartitionsOnReplicaIterator(topicMap, leadersOnly);
} | @Test
public void testIterator() {
SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
BrokersToIsrs brokersToIsrs = new BrokersToIsrs(snapshotRegistry);
assertEquals(toSet(), toSet(brokersToIsrs.iterator(1, false)));
brokersToIsrs.update(UUIDS[0], 0, null, ne... |
boolean shouldReplicateTopic(String topic) {
return (topicFilter.shouldReplicateTopic(topic) || replicationPolicy.isHeartbeatsTopic(topic))
&& !replicationPolicy.isInternalTopic(topic) && !isCycle(topic);
} | @Test
public void testReplicatesHeartbeatsDespiteFilter() {
DefaultReplicationPolicy defaultReplicationPolicy = new DefaultReplicationPolicy();
MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"),
defaultReplicationPolicy, x -> false, new D... |
@Override
public void setOnKeyboardActionListener(OnKeyboardActionListener keyboardActionListener) {
FrameKeyboardViewClickListener frameKeyboardViewClickListener =
new FrameKeyboardViewClickListener(keyboardActionListener);
frameKeyboardViewClickListener.registerOnViews(this);
final Context cont... | @Test
public void testPassesOnlyEnabledAddOns() throws Exception {
final QuickTextKeyFactory quickTextKeyFactory =
AnyApplication.getQuickTextKeyFactory(getApplicationContext());
Assert.assertEquals(17, quickTextKeyFactory.getAllAddOns().size());
Assert.assertEquals(17, quickTextKeyFactory.getEna... |
@Override
public int size() {
return count(members, selector);
} | @Test
public void testSizeWhenDataMembersSelected() {
Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, DATA_MEMBER_SELECTOR);
assertEquals(1, collection.size());
} |
public static Page createFileStatisticsPage(long fileSize, long rowCount)
{
// FileStatistics page layout:
//
// fileSize rowCount
// X X
PageBuilder statsPageBuilder = new PageBuilder(ImmutableList.of(BIGINT, BIGINT));
statsPageBuilder.declarePosition(... | @Test
public void testCreateFileStatisticsPage()
{
Page statisticsPage = createFileStatisticsPage(FILE_SIZE, ROW_COUNT);
assertEquals(statisticsPage.getPositionCount(), 1);
assertEquals(statisticsPage.getChannelCount(), 2);
} |
@Override
public boolean start() throws IOException {
LOG.info("Starting reader using {}", initialCheckpointGenerator);
try {
shardReadersPool = createShardReadersPool();
shardReadersPool.start();
} catch (TransientKinesisException e) {
throw new IOException(e);
}
return advanc... | @Test
public void startReturnsTrueIfSomeDataAvailable() throws IOException {
when(shardReadersPool.nextRecord())
.thenReturn(CustomOptional.of(a))
.thenReturn(CustomOptional.absent());
assertThat(reader.start()).isTrue();
} |
@Override
public void afterComponent(Component component) {
componentsWithUnprocessedIssues.remove(component.getUuid());
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component);
if (originalFile.isPresent()) {
componentsWithUnprocessedIssues.remove(... | @Test
public void also_remove_moved_files() {
String uuid2 = "uuid2";
OriginalFile movedFile = new OriginalFile(uuid2, "key");
when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.of(movedFile));
underTest.afterComponent(component);
verify(movedFilesRepository).ge... |
@Override
public CoordinatorRecord deserialize(
ByteBuffer keyBuffer,
ByteBuffer valueBuffer
) throws RuntimeException {
final short recordType = readVersion(keyBuffer, "key");
final ApiMessage keyMessage = apiMessageKeyFor(recordType);
readMessage(keyMessage, keyBuffer, ... | @Test
public void testDeserialize() {
GroupCoordinatorRecordSerde serde = new GroupCoordinatorRecordSerde();
ApiMessageAndVersion key = new ApiMessageAndVersion(
new ConsumerGroupMetadataKey().setGroupId("foo"),
(short) 3
);
ByteBuffer keyBuffer = MessageUtil... |
@Override
public void validatePostList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得岗位信息
List<PostDO> posts = postMapper.selectBatchIds(ids);
Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId);
// 校验
ids.forEach(id ... | @Test
public void testValidatePostList_notEnable() {
// mock 数据
PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.DISABLE.getStatus());
postMapper.insert(postDO);
// 准备参数
List<Long> ids = singletonList(postDO.getId());
// 调用, 并断言异常
assertServiceExcept... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testPartitionedDays() throws Exception {
createPartitionedTable(spark, tableName, "days(ts)");
SparkScanBuilder builder = scanBuilder();
DaysFunction.TimestampToDaysFunction function = new DaysFunction.TimestampToDaysFunction();
UserDefinedScalarFunc udf = toUDF(function, e... |
public boolean rollbackOn(Throwable ex) {
RollbackRule winner = null;
int deepest = Integer.MAX_VALUE;
if (CollectionUtils.isNotEmpty(rollbackRules)) {
winner = NoRollbackRule.DEFAULT_NO_ROLLBACK_RULE;
for (RollbackRule rule : this.rollbackRules) {
int d... | @Test
public void testRollBackOn() {
TransactionInfo txInfo = new TransactionInfo();
//default true
assertThat(txInfo.rollbackOn(new IllegalArgumentException())).isTrue();
assertThat(txInfo.rollbackOn(new Exception())).isTrue();
assertThat(txInfo.rollbackOn(new IOException()... |
@Override
public void restore(final Path file, final LoginCallback prompt) throws BackgroundException {
final String nodeId = fileid.getFileId(file);
try {
new CoreRestControllerApi(session.getClient()).revertNode(nodeId);
this.fileid.cache(file, null);
}
catc... | @Test
public void restoreDirectory() throws Exception {
final DeepboxIdProvider fileid = new DeepboxIdProvider(session);
final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path trash = new Path("/ORG ... |
public static DataMap convertToDataMap(Map<String, Object> queryParams)
{
return convertToDataMap(queryParams, Collections.<String, Class<?>>emptyMap(),
AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(),
RestLiProjectionDataMapSerializer.DEFAULT_SERIALIZER);
} | @Test
public void testCustomProjectionDataMapSerializer()
{
Map<String, Object> queryParams = new HashMap<>();
Set<PathSpec> specSet = new HashSet<>();
specSet.add(new PathSpec("random"));
queryParams.put(RestConstants.FIELDS_PARAM, specSet);
queryParams.put(RestConstants.PAGING_FIELDS_PARAM, sp... |
private void migrateV1toV2() throws BlockStoreException, IOException {
long currentLength = randomAccessFile.length();
long currentBlocksLength = currentLength - FILE_PROLOGUE_BYTES;
if (currentBlocksLength % RECORD_SIZE_V1 != 0)
throw new BlockStoreException(
"Fi... | @Test
public void migrateV1toV2() throws Exception {
// create V1 format
RandomAccessFile raf = new RandomAccessFile(blockStoreFile, "rw");
FileChannel channel = raf.getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0,
SPVBlockStore.FILE_PR... |
@Override
public Map<String, String> run(final Session<?> session) throws BackgroundException {
final Metadata feature = session.getFeature(Metadata.class);
if(log.isDebugEnabled()) {
log.debug(String.format("Run with feature %s", feature));
}
// Map for metadata entry ke... | @Test
public void testRun() throws Exception {
final List<Path> files = new ArrayList<>();
files.add(new Path("a", EnumSet.of(Path.Type.file)));
files.add(new Path("b", EnumSet.of(Path.Type.file)));
files.add(new Path("c", EnumSet.of(Path.Type.file)));
ReadMetadataWorker work... |
public static FusedPipeline fuse(Pipeline p) {
return new GreedyPipelineFuser(p).fusedPipeline;
} | @Test
public void sideInputRootsNewStage() {
Components components =
Components.newBuilder()
.putCoders("coder", Coder.newBuilder().build())
.putCoders("windowCoder", Coder.newBuilder().build())
.putWindowingStrategies(
"ws", WindowingStrategy.newBuilder... |
public boolean check() {
// the dependency com.sonarsource:sonarsource-branding is shaded to webapp
// during official build (see sonar-web pom)
File brandingFile = new File(serverFileSystem.getHomeDir(), BRANDING_FILE_PATH);
// no need to check that the file exists. java.io.File#length() returns zero i... | @Test
public void official_distribution() throws Exception {
File rootDir = temp.newFolder();
FileUtils.write(new File(rootDir, OfficialDistribution.BRANDING_FILE_PATH), "1.2");
when(serverFileSystem.getHomeDir()).thenReturn(rootDir);
assertThat(underTest.check()).isTrue();
} |
public Pair<Long, Jwts> refresh(String refreshToken) {
JwtClaims claims = refreshTokenProvider.getJwtClaimsFromToken(refreshToken);
Long userId = JwtClaimsParserUtil.getClaimsValue(claims, RefreshTokenClaimKeys.USER_ID.getValue(), Long::parseLong);
String role = JwtClaimsParserUtil.getClaimsVal... | @Test
@DisplayName("사용자 아이디에 해당하는 다른 리프레시 토큰이 저장되어 있을 시, 탈취되었다고 판단하고 토큰을 제거한 후 JwtErrorException을 발생시킨다.")
public void RefreshTokenRefreshFail() {
// given
RefreshToken refreshToken = RefreshToken.builder()
.userId(1L)
.token("refreshToken")
.ttl(1... |
@Override
public void properties(SAPropertiesFetcher fetcher) {
if (mCustomProperties != null) {
JSONUtils.mergeJSONObject(mCustomProperties, fetcher.getProperties());
mCustomProperties = null;
}
} | @Test
public void properties() {
InternalCustomPropertyPlugin customPropertyPlugin = new InternalCustomPropertyPlugin();
JSONObject libProperty = new JSONObject();
try {
libProperty.put("custom", "customAndroid");
} catch (JSONException e) {
e.printStackTrace(... |
@Override
public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception {
this.config = config;
this.sourceContext = sourceContext;
this.intermediateTopicName = SourceConfigUtils.computeBatchSourceIntermediateTopicName(sourceContext.getTenant(),
sourceContext.getNamespac... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp =
"Batch Configs cannot be found")
public void testPushWithoutRightConfig() throws Exception {
pushConfig.clear();
batchSourceExecutor.open(pushConfig, context);
} |
@Override
public WebSocketExtensionData newRequestData() {
return new WebSocketExtensionData(
useWebkitExtensionName ? X_WEBKIT_DEFLATE_FRAME_EXTENSION : DEFLATE_FRAME_EXTENSION,
Collections.<String, String>emptyMap());
} | @Test
public void testWebkitDeflateFrameData() {
DeflateFrameClientExtensionHandshaker handshaker =
new DeflateFrameClientExtensionHandshaker(true);
WebSocketExtensionData data = handshaker.newRequestData();
assertEquals(X_WEBKIT_DEFLATE_FRAME_EXTENSION, data.name());
... |
public static void main(String[] args) {
var queue = new SimpleMessageQueue(10000);
final var producer = new Producer("PRODUCER_1", queue);
final var consumer = new Consumer("CONSUMER_1", queue);
new Thread(consumer::consume).start();
new Thread(() -> {
producer.send("hand shake");
pr... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
public int compareTo(EipAttribute o) {
if (o == null) {
return 1;
}
return index - o.index;
} | @Test
public void testCompareTo() {
EipAttribute attribute1 = getInstance();
EipAttribute attribute2 = getInstance();
int result = attribute1.compareTo(attribute2);
assertEquals(0, result);
result = attribute1.compareTo(null);
assertNotEquals(0, result);
... |
@Override
public double variance() {
return variance;
} | @Test
public void testVariance() {
System.out.println("variance");
LogNormalDistribution instance = new LogNormalDistribution(1.0, 1.0);
instance.rand();
assertEquals(34.51261, instance.variance(), 1E-5);
} |
public static Write write() {
return new AutoValue_RedisIO_Write.Builder()
.setConnectionConfiguration(RedisConnectionConfiguration.create())
.setMethod(Write.Method.APPEND)
.build();
} | @Test
public void testWriteUsingINCRBY() {
String key = "key_incr";
List<String> values = Arrays.asList("0", "1", "2", "-3", "2", "4", "0", "5");
List<KV<String, String>> data = buildConstantKeyList(key, values);
PCollection<KV<String, String>> write = p.apply(Create.of(data));
write.apply(RedisI... |
public Matrix tm(Matrix B) {
if (m != B.m) {
throw new IllegalArgumentException(String.format("Matrix multiplication A' * B: %d x %d vs %d x %d", m, n, B.m, B.n));
}
Matrix C = new Matrix(n, B.n);
C.mm(TRANSPOSE, this, NO_TRANSPOSE, B);
return C;
} | @Test
public void testTm() {
System.out.println("tm");
float[][] A = {
{4.0f, 1.2f, 0.8f},
{1.2f, 9.0f, 1.2f},
{0.8f, 1.2f, 16.0f}
};
float[] B = {-4.0f, 1.0f, -3.0f};
float[] C = {-1.0505f, 0.2719f, -0.1554f};
Matrix a... |
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY);
} | @Test
public void testForceSeverity() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
... |
public static <T> T getItemAtPositionOrNull(T[] array, int position) {
if (position >= 0 && array.length > position) {
return array[position];
}
return null;
} | @Test
public void getItemAtPositionOrNull_whenPositionExist_thenReturnTheItem() {
Object obj = new Object();
Object[] src = new Object[1];
src[0] = obj;
Object result = ArrayUtils.getItemAtPositionOrNull(src, 0);
assertSame(obj, result);
} |
public static void free(final DirectBuffer buffer)
{
if (null != buffer)
{
free(buffer.byteBuffer());
}
} | @Test
void freeShouldReleaseByteBufferResources()
{
final ByteBuffer buffer = ByteBuffer.allocateDirect(4);
buffer.put((byte)1);
buffer.put((byte)2);
buffer.put((byte)3);
buffer.position(0);
BufferUtil.free(buffer);
} |
public String printFlags() {
return flags().stream().sorted().map(Enum::toString).collect(Collectors.joining("|"));
} | @Test
void printFlags() {
ADUserAccountControl allFlagsAccountcontrol = ADUserAccountControl.create(
ADUserAccountControl.Flags.NORMAL_ACCOUNT.getFlagValue() |
ADUserAccountControl.Flags.ACCOUNTDISABLE.getFlagValue() |
ADUserAccountCont... |
@Override
public String getUriForDisplay() {
return String.format("%s / %s", pipelineName, stageName);
} | @Test
void shouldUseACombinationOfPipelineAndStageNameAsURI() {
Material material = new DependencyMaterial(new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar"));
assertThat(material.getUriForDisplay()).isEqualTo("pipeline-foo / stage-bar");
} |
public boolean submitProcessingErrors(Message message) {
return submitProcessingErrorsInternal(message, message.processingErrors());
} | @Test
public void submitProcessingErrors_allProcessingErrorsSubmittedToQueueAndMessageNotFilteredOut_ifSubmissionEnabledAndDuplicatesAreKept() throws Exception {
// given
final Message msg = Mockito.mock(Message.class);
when(msg.getMessageId()).thenReturn("msg-x");
when(msg.supportsF... |
public synchronized void flush() {
try {
StringBuffer buffer = this.buffer.getBuffer();
logFileOutputStream.write( buffer.toString().getBytes() );
logFileOutputStream.flush();
} catch ( Exception e ) {
exception = new KettleException( "There was an error logging to file '" + logFile + "... | @Test
public void test() throws Exception {
LogChannelFileWriter writer = new LogChannelFileWriter( id, fileObject, false );
LoggingRegistry.getInstance().getLogChannelFileWriterBuffer( id ).addEvent(
new KettleLoggingEvent( logMessage, System.currentTimeMillis(), LogLevel.BASIC ) );
writer... |
@Override
public boolean createTable(String tableName, JDBCSchema schema) {
// Check table ID
checkValidTableName(tableName);
// Check if table already exists
if (tableIds.containsKey(tableName)) {
throw new IllegalStateException(
"Table " + tableName + " already exists for database "... | @Test
public void testCreateTableShouldReturnTrueIfJDBCDoesNotThrowAnyError() throws SQLException {
when(container.getHost()).thenReturn(HOST);
when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT);
assertTrue(
testManager.createTable(
TABLE_NAME,
new JDBCResour... |
private void fail(long frameLength) {
if (frameLength > 0) {
throw new TooLongFrameException(
"Adjusted frame length exceeds " + maxFrameLength +
": " + frameLength + " - discarded");
} else {
throw new TooLongFrameException... | @Test
public void testDiscardTooLongFrame1() {
ByteBuf buf = Unpooled.buffer();
buf.writeInt(32);
for (int i = 0; i < 32; i++) {
buf.writeByte(i);
}
buf.writeInt(1);
buf.writeByte('a');
EmbeddedChannel channel = new EmbeddedChannel(new LengthFieldB... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var originator = msg.getOriginator();
var msgDataAsObjectNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null;
if (!EntityType.DEVICE.equals(origin... | @Test
void givenUnsupportedOriginatorType_whenOnMsg_thenShouldTellFailure() throws Exception {
// GIVEN
var randomCustomerId = new CustomerId(UUID.randomUUID());
// WHEN
node.onMsg(ctxMock, getTbMsg(randomCustomerId));
// THEN
var newMsgCaptor = ArgumentCaptor.forCl... |
@Override
protected Result check() throws Exception {
long expiration = clock.getTime() - result.getTime() - healthyTtl;
if (expiration > 0) {
return Result.builder()
.unhealthy()
.usingClock(clock)
.withMessage("Result was %s b... | @Test
public void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() throws Exception {
HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck();
AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService);
... |
public static String idCardNum(String idCardNum, int front, int end) {
//身份证不能为空
if (StrUtil.isBlank(idCardNum)) {
return StrUtil.EMPTY;
}
//需要截取的长度不能大于身份证号长度
if ((front + end) > idCardNum.length()) {
return StrUtil.EMPTY;
}
//需要截取的不能小于0
if (front < 0 || end < 0) {
return StrUtil.EMPTY;
}
r... | @Test
public void idCardNumTest() {
assertEquals("5***************1X", DesensitizedUtil.idCardNum("51343620000320711X", 1, 2));
} |
protected static List<LastOpenedDTO> filterForExistingIdAndCapAtMaximum(final LastOpenedForUserDTO loi, final GRN grn, final long max) {
return loi.items().stream().filter(i -> !i.grn().equals(grn)).limit(max - 1).toList();
} | @Test
public void testRemoveItemFromTheMiddle() {
var list = List.of(
new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "1"), DateTime.now(DateTimeZone.UTC)),
new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "2"), DateTime.now(DateTimeZone.UTC)),
... |
@Transactional
public void create(String uuid, long attendeeId, ScheduleCreateRequest request) {
Meeting meeting = meetingRepository.findByUuid(uuid)
.orElseThrow(() -> new MomoException(MeetingErrorCode.INVALID_UUID));
validateMeetingUnLocked(meeting);
Attendee attendee = a... | @DisplayName("스케줄 생성 시 사용자의 기존 스케줄들을 모두 삭제하고 새로운 스케줄을 저장한다.")
@Test
void createSchedulesReplacesOldSchedules() {
ScheduleCreateRequest request = new ScheduleCreateRequest(dateTimes);
scheduleRepository.saveAll(List.of(
new Schedule(attendee, today, Timeslot.TIME_0130),
... |
static long sizeForField(@Nonnull String key, @Nonnull Object value) {
return key.length() + sizeForValue(value);
} | @Test
public void fieldTest() {
assertThat(Message.sizeForField("", true)).isEqualTo(4);
assertThat(Message.sizeForField("", (byte) 1)).isEqualTo(1);
assertThat(Message.sizeForField("", (char) 1)).isEqualTo(2);
assertThat(Message.sizeForField("", (short) 1)).isEqualTo(2);
ass... |
public long readIntLenenc() {
int firstByte = readInt1();
if (firstByte < 0xfb) {
return firstByte;
}
if (0xfb == firstByte) {
return 0L;
}
if (0xfc == firstByte) {
return readInt2();
}
if (0xfd == firstByte) {
... | @Test
void assertReadIntLenencWithTwoBytes() {
when(byteBuf.readUnsignedByte()).thenReturn((short) 0xfc);
when(byteBuf.readUnsignedShortLE()).thenReturn(100);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readIntLenenc(), is(100L));
} |
@SuppressWarnings({"checkstyle:CyclomaticComplexity", "checkstyle:MethodLength"})
public static Expression convert(Predicate predicate) {
Operation op = FILTERS.get(predicate.name());
if (op != null) {
switch (op) {
case TRUE:
return Expressions.alwaysTrue();
case FALSE:
... | @Test
public void testDateFilterConversion() {
LocalDate localDate = LocalDate.parse("2018-10-18");
long epochDay = localDate.toEpochDay();
NamedReference namedReference = FieldReference.apply("x");
LiteralValue ts = new LiteralValue(epochDay, DataTypes.DateType);
org.apache.spark.sql.connector.e... |
@Override
public Set<Tuple> zRangeWithScores(byte[] key, long start, long end) {
if (executorService.getServiceManager().isResp3()) {
return read(key, ByteArrayCodec.INSTANCE, ZRANGE_ENTRY_V2, key, start, end, "WITHSCORES");
}
return read(key, ByteArrayCodec.INSTANCE, ZRANGE_ENTR... | @Test
public void testZRangeWithScores() {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson));
redisTemplate.afterPropertiesSet();
redisTemplate.boundZSetOps("test").add("1", 10);
redisTe... |
@Override
public ValidationError validate(Exchange exchange, ValidationContext validationContent) {
OpenAPI openAPI = exchange.getProperty(Exchange.REST_OPENAPI, OpenAPI.class);
if (openAPI == null) {
return null;
}
String method = exchange.getMessage().getHeader(Exchang... | @Test
public void testValidator() throws Exception {
String data = IOHelper.loadText(OpenApiRestClientRequestValidatorTest.class.getResourceAsStream("/petstore-v3.json"));
OpenAPIV3Parser parser = new OpenAPIV3Parser();
SwaggerParseResult out = parser.readContents(data);
OpenAPI open... |
@Override
public void process(Exchange exchange) throws Exception {
String operation = getOperation(exchange);
switch (operation) {
case GlanceConstants.RESERVE:
doReserve(exchange);
break;
case OpenstackConstants.CREATE:
doCre... | @Test
public void reserveWithHeadersTest() throws Exception {
when(endpoint.getOperation()).thenReturn(GlanceConstants.RESERVE);
msg.setHeader(OpenstackConstants.NAME, dummyImage.getName());
msg.setHeader(GlanceConstants.CONTAINER_FORMAT, dummyImage.getContainerFormat());
msg.setHead... |
@NonNull
public String processShownotes() {
String shownotes = rawShownotes;
if (TextUtils.isEmpty(shownotes)) {
Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message");
shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno... | @Test
public void testProcessShownotesAddTimecodeParentheses() {
final String timeStr = "10:11";
final long time = 3600 * 1000 * 10 + 60 * 1000 * 11;
String shownotes = "<p> Some test text with a timecode (" + timeStr + ") here.</p>";
ShownotesCleaner t = new ShownotesCleaner(contex... |
void sendNextRpc() {
this.lock.lock();
try {
this.timer = null;
final long offset = this.requestBuilder.getOffset() + this.requestBuilder.getCount();
final long maxCount = this.destBuf == null ? this.raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE;
... | @Test
public void testSendNextRpc() {
final int maxCount = this.raftOpts.getMaxByteCountPerRpc();
sendNextRpc(maxCount);
} |
public static byte[] generateContractAddress(byte[] address, BigInteger nonce) {
List<RlpType> values = new ArrayList<>();
values.add(RlpString.create(address));
values.add(RlpString.create(nonce));
RlpList rlpList = new RlpList(values);
byte[] encoded = RlpEncoder.encode(rlpLi... | @Test
public void testCreateContractAddress() {
String address = "0x19e03255f667bdfd50a32722df860b1eeaf4d635";
assertEquals(
generateContractAddress(address, BigInteger.valueOf(209)),
("0xe41e694d8fa4337b7bffc7483d3609ae1ea068d5"));
assertEquals(
... |
public static ExpansionServer create(ExpansionService service, String host, int port)
throws IOException {
return new ExpansionServer(service, host, port);
} | @Test
public void testEmptyFilesToStageIsOK() {
String[] args = {"--filesToStage="};
ExpansionService service = new ExpansionService(args);
assertThat(
service
.createPipeline(PipelineOptionsFactory.create())
.getOptions()
.as(PortablePipelineOptions.class)
... |
public InputFormat<RowData, ?> getInputFormat() {
return getInputFormat(false);
} | @Test
void testGetInputFormat() throws Exception {
beforeEach();
// write some data to let the TableSchemaResolver get the right instant
TestData.writeData(TestData.DATA_SET_INSERT, conf);
HoodieTableSource tableSource = new HoodieTableSource(
SerializableSchema.create(TestConfigurations.TABL... |
static String getErrorKey(Sample sample) {
if (sample.getSuccess()) {
return "";
}
String responseCode = sample.getResponseCode();
String responseMessage = sample.getResponseMessage();
String key = responseCode + (!StringUtils.isEmpty(responseMessage) ?
... | @Test
public void testGetErrorKey() {
SampleMetadata metadata = new SampleMetadata(',', new String[] { CSVSaveService.SUCCESSFUL,
CSVSaveService.RESPONSE_CODE, CSVSaveService.RESPONSE_MESSAGE, CSVSaveService.FAILURE_MESSAGE });
Sample sample = new Sample(0, metadata, new String[] { "... |
@Override
public <KR> KGroupedStream<KR, V> groupBy(final KeyValueMapper<? super K, ? super V, KR> keySelector) {
return groupBy(keySelector, Grouped.with(null, valueSerde));
} | @Test
public void shouldNotAllowNullGroupedOnGroupBy() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.groupBy((k, v) -> k, (Grouped<String, String>) null));
assertThat(exception.getMessage(), equalTo("grouped can't be null"... |
public String get(String key, String defaultValue) {
String v = get(key);
if (v == null) v = defaultValue;
return v;
} | @Test
public void caseInsensitive() {
EnvVars ev = new EnvVars(Map.of("Path", "A:B:C"));
assertTrue(ev.containsKey("PATH"));
assertEquals("A:B:C", ev.get("PATH"));
} |
public double p50() {
return getLinearInterpolation(0.50);
} | @Test
public void testP50() {
HistogramData histogramData1 = HistogramData.linear(0, 0.2, 50);
histogramData1.record(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
assertThat(String.format("%.3f", histogramData1.p50()), equalTo("4.200"));
HistogramData histogramData2 = HistogramData.linear(0, 0.02, 50);
histogra... |
public static boolean isMatchGlobPattern(String pattern, String value, URL param) {
if (param != null && pattern.startsWith("$")) {
pattern = param.getRawParameter(pattern.substring(1));
}
return isMatchGlobPattern(pattern, value);
} | @Test
void testIsMatchGlobPattern() throws Exception {
assertTrue(UrlUtils.isMatchGlobPattern("*", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("", null));
assertFalse(UrlUtils.isMatchGlobPattern("", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("value", "value"));
a... |
public boolean setTriggerError(JobTriggerDto trigger) {
requireNonNull(trigger, "trigger cannot be null");
final var filter = and(
// Make sure that the owner still owns the trigger
eq(FIELD_LOCK_OWNER, nodeId),
idEq(getId(trigger))
);
fin... | @Test
public void setTriggerError() {
final JobTriggerDto trigger1 = dbJobTriggerService.create(JobTriggerDto.Builder.create(clock)
.jobDefinitionId("abc-123")
.jobDefinitionType("event-processor-execution-v1")
.schedule(IntervalJobSchedule.builder()
... |
void setReplicas(PartitionReplica[] newReplicas) {
PartitionReplica[] oldReplicas = replicas;
replicas = newReplicas;
onReplicasChange(newReplicas, oldReplicas);
} | @Test
public void testSetReplicaAddresses_multipleTimes() {
replicaOwners[0] = localReplica;
partition.setReplicas(replicaOwners);
partition.setReplicas(replicaOwners);
} |
@Override
public void store(Measure newMeasure) {
saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure);
} | @Test
public void should_merge_coverage() {
DefaultInputFile file = new TestInputFileBuilder("foo", "src/Foo.php").setLines(5).build();
DefaultCoverage coverage = new DefaultCoverage(underTest);
coverage.onFile(file).lineHits(3, 1);
DefaultCoverage coverage2 = new DefaultCoverage(underTest);
cov... |
public static FlinkJobServerDriver fromConfig(FlinkServerConfiguration configuration) {
return create(
configuration,
createJobServerFactory(configuration),
createArtifactServerFactory(configuration),
() -> FlinkJobInvoker.create(configuration));
} | @Test
public void testConfigurationDefaults() {
FlinkJobServerDriver.FlinkServerConfiguration config =
new FlinkJobServerDriver.FlinkServerConfiguration();
assertThat(config.getHost(), is("localhost"));
assertThat(config.getPort(), is(8099));
assertThat(config.getArtifactPort(), is(8098));
... |
@Override
public double p(double x) {
int start = Arrays.binarySearch(this.x, x-5*h);
if (start < 0) {
start = -start - 1;
}
int end = Arrays.binarySearch(this.x, x+5*h);
if (end < 0) {
end = -end - 1;
}
double p = 0.0;
for (i... | @Test
public void testP() {
System.out.println("p");
KernelDensity instance = new KernelDensity(x);
double expResult = 0.10122;
double result = instance.p(3.5);
assertEquals(expResult, result, 1E-5);
} |
public static DescribeAclsRequest parse(ByteBuffer buffer, short version) {
return new DescribeAclsRequest(new DescribeAclsRequestData(new ByteBufferAccessor(buffer), version), version);
} | @Test
public void shouldRoundTripLiteralV0() {
final DescribeAclsRequest original = new DescribeAclsRequest.Builder(LITERAL_FILTER).build(V0);
final DescribeAclsRequest result = DescribeAclsRequest.parse(original.serialize(), V0);
assertRequestEquals(original, result);
} |
public ClusterSerdes init(Environment env,
ClustersProperties clustersProperties,
int clusterIndex) {
ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex);
log.debug("Configuring serdes for cluster {}", clusterP... | @Test
void serdeWithBuiltInNameAndSetPropertiesAreExplicitlyConfigured() {
ClustersProperties.SerdeConfig serdeConfig = new ClustersProperties.SerdeConfig();
serdeConfig.setName("BuiltIn1");
serdeConfig.setProperties(Map.of("any", "property"));
serdeConfig.setTopicKeysPattern("keys");
serdeConfig.... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
ClassLoader stagedClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader effectiveClassLoader;
if (invocation.getServiceModel() != null) {
effectiveClassLoader = inv... | @Test
void testInvoke() throws Exception {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1");
String path = DemoService.class.getResource("/").getPath();
final URLClassLoader cl = new URLClassLoader(new java.net.URL[] {new java.net.URL("file:" + path)}) {
... |
public Certificate add(X509Certificate cert) {
final Certificate db;
try {
db = Certificate.from(cert);
} catch (CertificateEncodingException e) {
logger.error("Encoding error in certificate", e);
throw new ClientException("Encoding error in certificate", e);
... | @Test
public void shouldDisallowToAddCertificateIfTrustedByExistingIfExpiredAndNotAllowed() throws CertificateException, IOException {
certificateRepo.saveAndFlush(loadCertificate("test/root.crt", true));
certificateRepo.saveAndFlush(loadCertificate("test/intermediate.crt", false));
final X5... |
public static URI getServerAddress(final KsqlRestConfig restConfig) {
final List<String> listeners = restConfig.getList(KsqlRestConfig.LISTENERS_CONFIG);
final String address = listeners.stream()
.map(String::trim)
.findFirst()
.orElseThrow(() ->
new ConfigException(KsqlRestC... | @Test
public void shouldReturnServerAddress() {
// Given:
final KsqlRestConfig restConfig =
new KsqlRestConfig(
Collections.singletonMap(KsqlRestConfig.LISTENERS_CONFIG,
"http://localhost:8088, http://localhost:9099"));
// Then:
ServerUtil.getServerAddress(restConf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.