focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
boolean isPostComment(Comment comment) {
return Ref.groupKindEquals(comment.getSpec().getSubjectRef(), POST_GVK);
} | @Test
void isPostCommentTest() {
var comment = createComment();
comment.getSpec()
.setSubjectRef(Ref.of("fake-post", GroupVersionKind.fromExtension(Post.class)));
assertThat(reasonPublisher.isPostComment(comment)).isTrue();
comment.getSpec()
.setSubjectRef(R... |
@Override
/**
* Parses the given text to transform it to the desired target type.
* @param text The LLM output in string format.
* @return The parsed output in the desired target type.
*/
public T convert(@NonNull String text) {
try {
// Remove leading and trailing whitespace
text = text.trim();
/... | @Test
public void convertTypeReference() {
var converter = new BeanOutputConverter<>(new ParameterizedTypeReference<TestClass>() {
});
var testClass = converter.convert("{ \"someString\": \"some value\" }");
assertThat(testClass.getSomeString()).isEqualTo("some value");
} |
public Value parse(String json) {
return this.delegate.parse(json);
} | @Test
public void testExponentialInteger1() throws Exception {
final JsonParser parser = new JsonParser();
final Value msgpackValue = parser.parse("12345e3");
assertTrue(msgpackValue.getValueType().isNumberType());
// TODO: Consider this needs to be an integer?
// See: https:... |
@Override
public Set<ConstraintCheckResult> checkConstraints(Collection<Constraint> requestedConstraints) {
final ImmutableSet.Builder<ConstraintCheckResult> fulfilledConstraints = ImmutableSet.builder();
for (Constraint constraint : requestedConstraints) {
if (constraint instanceof Gray... | @Test
public void checkConstraintsFails() {
final GraylogVersionConstraintChecker constraintChecker = new GraylogVersionConstraintChecker("1.0.0");
final GraylogVersionConstraint graylogVersionConstraint = GraylogVersionConstraint.builder()
.version("^2.0.0")
.build(... |
public static ClassLoader getClassLoader(Class<?> clazz) {
ClassLoader cl = null;
if (!clazz.getName().startsWith("org.apache.dubbo")) {
cl = clazz.getClassLoader();
}
if (cl == null) {
try {
cl = Thread.currentThread().getContextClassLoader();
... | @Test
void testGetClassLoader2() {
assertThat(ClassUtils.getClassLoader(), sameInstance(ClassUtils.class.getClassLoader()));
} |
@VisibleForTesting
public void validateDictTypeExists(String type) {
DictTypeDO dictType = dictTypeService.getDictType(type);
if (dictType == null) {
throw exception(DICT_TYPE_NOT_EXISTS);
}
if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) {
... | @Test
public void testValidateDictTypeExists_notEnable() {
// mock 方法,数据类型被禁用
String dictType = randomString();
when(dictTypeService.getDictType(eq(dictType))).thenReturn(
randomPojo(DictTypeDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 调用, 并... |
public String getMeta(String key)
{
return metadata.get(key);
} | @Test
public void testGetMeta()
{
ZCert cert = new ZCert();
cert.setMeta("version", "1");
ZMetadata meta = cert.getMetadata();
String version = meta.get("version");
assertThat(version, is("1"));
meta.set("version", "2");
version = cert.getMeta("version")... |
@VisibleForTesting
void validateNameUnique(List<MemberLevelDO> list, Long id, String name) {
for (MemberLevelDO levelDO : list) {
if (ObjUtil.notEqual(levelDO.getName(), name)) {
continue;
}
if (id == null || !id.equals(levelDO.getId())) {
... | @Test
public void testCreateLevel_nameUnique() {
// 准备参数
String name = randomString();
// mock 数据
memberlevelMapper.insert(randomLevelDO(o -> o.setName(name)));
// 调用,校验异常
List<MemberLevelDO> list = memberlevelMapper.selectList();
assertServiceException(() -... |
public String compile(final String xls,
final String template,
int startRow,
int startCol) {
return compile( xls,
template,
InputType.XLS,
startRow,
... | @Test
public void testIntegration() throws Exception {
final String drl = converter.compile("/data/IntegrationExampleTestForTemplates.drl.xls", "/templates/test_integration.drl", 18, 3);
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.... |
@PublicAPI(usage = ACCESS)
public Optional<String> getFileName() {
return fileName;
} | @Test
public void source_file_name() {
Source source = new Source(uriOf(Object.class), Optional.of("SomeClass.java"), false);
assertThat(source.getFileName()).as("source file name").contains("SomeClass.java");
source = new Source(uriOf(Object.class), Optional.empty(), false);
assert... |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final EnumSet<OpenMode> flags;
if(status.isAppend()) {
if(status.isExists()) {
// No... | @Test
public void testWrite() throws Exception {
final Path folder = new SFTPDirectoryFeature(session).mkdir(new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus());
final long folderModification =... |
public static Permission getPermission(String name, String serviceName, String... actions) {
PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName);
if (permissionFactory == null) {
throw new IllegalArgumentException("No permissions found for service: " + serviceName);... | @Test
public void getPermission_Queue() {
Permission permission = ActionConstants.getPermission("foo", QueueService.SERVICE_NAME);
assertNotNull(permission);
assertTrue(permission instanceof QueuePermission);
} |
@VisibleForTesting
static void validateFips(final KsqlConfig config, final KsqlRestConfig restConfig) {
if (config.getBoolean(ConfluentConfigs.ENABLE_FIPS_CONFIG)) {
final FipsValidator fipsValidator = ConfluentConfigs.buildFipsValidator();
// validate cipher suites and TLS version
validateCiph... | @Test
public void shouldFailOnInvalidBrokerSecurityProtocol() {
// Given:
final KsqlConfig config = configWith(ImmutableMap.of(
ConfluentConfigs.ENABLE_FIPS_CONFIG, true,
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_PLAINTEXT.name
));
final KsqlRestConfig restCon... |
public static double tileYToLatitude(long tileY, byte zoomLevel) {
return pixelYToLatitude(tileY * DUMMY_TILE_SIZE, getMapSize(zoomLevel, DUMMY_TILE_SIZE));
} | @Test
public void tileYToLatitudeTest() {
for (int tileSize : TILE_SIZES) {
for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) {
double latitude = MercatorProjection.tileYToLatitude(0, zoomLevel);
Assert.assertEquals(MercatorProjection... |
@Override
public void emit(OutboundPacket packet) {
store.emit(networkId(), packet);
} | @Test
public void emitTest() {
OutboundPacket packet =
new DefaultOutboundPacket(VDID1, DefaultTrafficTreatment.emptyTreatment(), ByteBuffer.allocate(5));
packetManager1.emit(packet);
assertEquals("Packet not emitted correctly", packet, emittedPacket);
} |
public static synchronized int getAvailablePort() {
int randomPort = getRandomPort();
return getAvailablePort(randomPort);
} | @Test
void testGetAvailablePort() {
assertThat(NetUtils.getAvailablePort(), greaterThan(0));
assertThat(NetUtils.getAvailablePort(12345), greaterThanOrEqualTo(12345));
assertThat(NetUtils.getAvailablePort(-1), greaterThanOrEqualTo(0));
} |
@Override
public boolean tryClaim(Long i) {
checkArgument(
lastAttemptedOffset == null || i > lastAttemptedOffset,
"Trying to claim offset %s while last attempted was %s",
i,
lastAttemptedOffset);
checkArgument(
i >= range.getFrom(), "Trying to claim offset %s before st... | @Test
public void testClaimBeforeStartOfRange() throws Exception {
expected.expectMessage("Trying to claim offset 90 before start of the range [100, 200)");
OffsetRangeTracker tracker = new OffsetRangeTracker(new OffsetRange(100, 200));
tracker.tryClaim(90L);
} |
public CompletableFuture<SendPushNotificationResult> sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeT... | @Test
void sendRegistrationChallengeNotification() {
final String deviceToken = "token";
final String challengeToken = "challenge";
when(apnSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())... |
@Override
public String getString() {
return this.string;
} | @Test
public void testGetString() {
ValueString vs = new ValueString( "Boden" );
assertEquals( "Boden", vs.getString() );
assertEquals( 0.0, vs.getNumber(), 0.0D );
assertNull( vs.getDate() ); // will fail parsing
assertEquals( false, vs.getBoolean() );
assertEquals( 0, vs.getInteger() );
... |
@Override
protected void recover() throws Exception {
// register
Set<URL> recoverRegistered = new HashSet<>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}... | @Test
void testRecover() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(6);
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
MockRegistry mockRegistry = new MockRegistr... |
@InvokeOnHeader(CONTROL_ACTION_SUBSCRIBE)
public void performSubscribe(final Message message, AsyncCallback callback) {
String filterId;
if (message.getBody() instanceof DynamicRouterControlMessage) {
filterId = subscribeFromMessage(dynamicRouterControlService, message, false);
}... | @Test
void performSubscribeActionWithEmptyExpressionLanguage() {
String subscribeChannel = "testChannel";
Map<String, Object> headers = Map.of(
CONTROL_ACTION_HEADER, CONTROL_ACTION_SUBSCRIBE,
CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel,
CONTROL_SUBSCR... |
@Override
public void commence(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse,
final AuthenticationException authenticationException) throws IOException {
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpS... | @Test
public void testCommence() throws IOException {
// Mock objects
HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputSt... |
@Nullable
@Override
public Message decode(@Nonnull final RawMessage rawMessage) {
final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
final String json = gelfMessage.getJSON(decompressSizeLimit, charset);
final JsonNode node;
... | @Test
public void decodeFailsWithWrongTypeForHost() throws Exception {
final String json = "{"
+ "\"version\": \"1.1\","
+ "\"host\": 42,"
+ "\"short_message\": \"A short message that helps you identify what is going on\""
+ "}";
final... |
public void add(CSQueue queue) {
String fullName = queue.getQueuePath();
String shortName = queue.getQueueShortName();
try {
modificationLock.writeLock().lock();
fullNameQueues.put(fullName, queue);
getMap.put(fullName, queue);
//we only update short queue name ambiguity for non r... | @Test
public void testSimpleMapping() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.main
CSQueue main = createParentQueue("main", root);
//root.main.A
CSQueue mainA = createLeafQueue("A", main);
//root.main.B
CSQueue mainB = createParentQueue("B", main);
//root.... |
public int printTopology() throws IOException {
DistributedFileSystem dfs = getDFS();
final DatanodeInfo[] report = dfs.getDataNodeStats();
// Build a map of rack -> nodes from the datanode report
Map<String, HashMap<String, String>> map = new HashMap<>();
for(DatanodeInfo dni : report) {
Str... | @Test(timeout = 30000)
public void testPrintTopology() throws Exception {
redirectStream();
/* init conf */
final Configuration dfsConf = new HdfsConfiguration();
final File baseDir = new File(
PathUtils.getTestDir(getClass()),
GenericTestUtils.getMethodName());
dfsConf.set(MiniDF... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
this.trash(files, callback, false);
} | @Test
public void testDeleteRevertDeletePurgeFile() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final Path parentFolder = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/Auditing", EnumSet.of(Path.Type.directory));
final Path trash = new Pat... |
public boolean streq(String str)
{
return streq(data, str);
} | @Test
public void testStreq()
{
ZData data = new ZData("test".getBytes(ZMQ.CHARSET));
assertThat(data.streq("test"), is(true));
} |
@Override
public URI resolveHostUri() {
InetSocketAddress host = resolveHost();
String hostUrl = serviceUri.getServiceScheme() + "://" + host.getHostString() + ":" + host.getPort();
return URI.create(hostUrl);
} | @Test(expectedExceptions = IllegalStateException.class)
public void testResolveUrlBeforeUpdateServiceUrl() {
resolver.resolveHostUri();
} |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_cancelJob_byJobId() {
// Given
Job job = newJob();
// When
run("cancel", job.getIdString());
// Then
assertThat(job).eventuallyHasStatus(JobStatus.FAILED);
} |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) {
list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file));
}
... | @Test
public void testToSignedUrlAnonymous() throws Exception {
final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
new Credentials("anonymous", null))) {
@Override
public RequestEntityRestStorageService getClient(... |
@Override
public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() {
Iterable<RedisClusterNode> res = clusterGetNodes();
Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>();
for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.... | @Test
public void testClusterGetMasterSlaveMap() {
Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap();
assertThat(map).hasSize(3);
for (Collection<RedisClusterNode> slaves : map.values()) {
assertThat(slaves).hasSize(1);
}
... |
@Override
public Collection<String> getJdbcUrlPrefixes() {
return Collections.singleton(String.format("jdbc:%s:", getType().toLowerCase()));
} | @Test
void assertGetJdbcUrlPrefixes() {
assertThat(TypedSPILoader.getService(DatabaseType.class, "H2").getJdbcUrlPrefixes(), is(Collections.singleton("jdbc:h2:")));
} |
@Override
public void createFunction(SqlInvokedFunction function, boolean replace)
{
checkCatalog(function);
checkFunctionLanguageSupported(function);
checkArgument(!function.hasVersion(), "function '%s' is already versioned", function);
QualifiedObjectName functionName = functi... | @Test
public void testCreateFunction()
{
assertListFunctions();
createFunction(FUNCTION_POWER_TOWER_DOUBLE, false);
assertListFunctions(FUNCTION_POWER_TOWER_DOUBLE.withVersion("1"));
createFunction(FUNCTION_POWER_TOWER_DOUBLE_UPDATED, true);
assertListFunctions(FUNCTION... |
@Override
public void clear() {
partitionMaps.clear();
} | @Test
public void testClear() {
PartitionMap<String> map = PartitionMap.create(SPECS);
map.put(UNPARTITIONED_SPEC.specId(), null, "v1");
map.put(BY_DATA_SPEC.specId(), Row.of("aaa"), "v2");
assertThat(map).hasSize(2);
map.clear();
assertThat(map).isEmpty();
} |
Location append(String relativeURI) {
relativeURI = encodeIllegalCharacters(relativeURI);
if (uri.toString().endsWith("/") && relativeURI.startsWith("/")) {
relativeURI = relativeURI.substring(1);
}
if (!uri.toString().endsWith("/") && !relativeURI.startsWith("/")) {
... | @Test
@UseDataProvider("base_locations")
public void append(Location location) {
Location appendAbsolute = location.append("/bar/baz");
Location appendRelative = location.append("bar/baz");
Location expected = Location.of(Paths.get("/some/path/bar/baz"));
assertThat(appendAbsolu... |
public Optional<Column> findColumn(final ColumnName columnName) {
return findColumnMatching(withName(columnName));
} | @Test
public void shouldGetValueColumns() {
assertThat(SOME_SCHEMA.findColumn(F0), is(Optional.of(
Column.of(F0, STRING, Namespace.VALUE, 0)
)));
} |
public static String getDesc(Class<?> c) {
StringBuilder ret = new StringBuilder();
while (c.isArray()) {
ret.append('[');
c = c.getComponentType();
}
if (c.isPrimitive()) {
String t = c.getName();
if ("void".equals(t)) {
... | @Test
void testGetDescConstructor() {
assertThat(ReflectUtils.getDesc(Foo2.class.getConstructors()[0]), equalTo("(Ljava/util/List;[I)V"));
} |
@Override
public void read(ChannelHandlerContext ctx) throws Exception {
if (dequeue(ctx, 1) == 0) {
// It seems no messages were consumed. We need to read() some
// messages from upstream and once one arrives it need to be
// relayed to downstream to keep the flow going.... | @Test
public void testAutoReadingOff() throws Exception {
final Exchanger<Channel> peerRef = new Exchanger<Channel>();
final CountDownLatch latch = new CountDownLatch(3);
ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
@Override
public voi... |
public static String resolvePassword( VariableSpace variables, String password ) {
String resolvedPassword = variables.environmentSubstitute( password );
if ( resolvedPassword != null ) {
// returns resolved decrypted password
return Encr.decryptPasswordOptionallyEncrypted( resolvedPassword );
}... | @Test
public void testResolvePasswordNull() {
String password = null;
// null is valid input parameter
assertSame( password, Utils.resolvePassword(
Variables.getADefaultVariableSpace(), password ) );
} |
public synchronized void synchronizePartitionSchemas( PartitionSchema partitionSchema ) {
synchronizePartitionSchemas( partitionSchema, partitionSchema.getName() );
} | @Test
public void synchronizePartitionSchemas_should_not_sync_unshared() throws Exception {
final String partitionSchemaName = "PartitionSchema";
TransMeta transformarion1 = createTransMeta();
PartitionSchema partitionSchema1 = createPartitionSchema( partitionSchemaName, true );
transformarion1.setPar... |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed!");
return;
}
final List<SearchPivotLimitMigration> pivotLimitMigrations = StreamSupport.stream(this.searches.find().spliterator... | @Test
@MongoDBFixtures("V20230113095301_MigrateGlobalPivotLimitsToGroupingsInSearchesTest_null_limits.json")
void migratingPivotsWithNullLimits() {
this.migration.upgrade();
assertThat(migrationCompleted().migratedSearchTypes()).isEqualTo(2);
final Document document = this.collection.f... |
public int getCodeLength()
{
return codeLength;
} | @Test
void testCodeLength()
{
byte[] startBytes1 = { 0x00 };
byte[] endBytes1 = { 0x20 };
CodespaceRange range1 = new CodespaceRange(startBytes1, endBytes1);
assertEquals(1, range1.getCodeLength());
byte[] startBytes2 = { 0x00, 0x00 };
byte[] endBytes2 = { 0x01, ... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseNonVarargWithNullValues() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING),
function(OTHER, 0, STRING_VARARGS)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(Collections.singletonList(null));
// Then:
assertThat(fun... |
public RingbufferConfig setCapacity(int capacity) {
this.capacity = checkPositive("capacity", capacity);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setCapacity_whenTooSmall() {
RingbufferConfig config = new RingbufferConfig(NAME);
config.setCapacity(0);
} |
public static Path compose(final Path root, final String path) {
if(StringUtils.startsWith(path, String.valueOf(Path.DELIMITER))) {
// Mount absolute path
final String normalized = normalize(StringUtils.replace(path, "\\", String.valueOf(Path.DELIMITER)), true);
if(StringUtil... | @Test
public void testRelativeParent() {
final Path home = PathNormalizer.compose(new Path("/", EnumSet.of(Path.Type.directory)), "sandbox/sub");
assertEquals(new Path("/sandbox/sub", EnumSet.of(Path.Type.directory)), home);
assertEquals(new Path("/sandbox", EnumSet.of(Path.Type.directory)),... |
@Override
public String encrypt(final Object plainValue, final AlgorithmSQLContext algorithmSQLContext) {
Object result = cryptographicAlgorithm.encrypt(plainValue);
return null == result ? null : String.valueOf(result);
} | @Test
void assertEncrypt() {
Object actual = encryptAlgorithm.encrypt("test", mock(AlgorithmSQLContext.class));
assertThat(actual, is("dSpPiyENQGDUXMKFMJPGWA=="));
} |
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
AsyncByteArrayFeeder streamFeeder = streamReader.getInputFeeder();
logger.info("Decoding XMPP data.. ");
byte[] buffer = new byte[in.readableBytes()];
in.readBytes(buffer);
... | @Test
public void testDecodeStreamOpen() throws Exception {
XmlStreamDecoder decoder = new XmlStreamDecoder();
ByteBuf buffer = Unpooled.buffer();
buffer.writeBytes(streamOpenMsg.getBytes(Charsets.UTF_8));
List<Object> list = Lists.newArrayList();
decoder.decode(new ChannelHa... |
public static Map<String, String> decodeFormData(String formString) {
return FORM_SPLITTER.split(formString).entrySet().stream()
.collect(
ImmutableMap.toImmutableMap(
e -> RESTUtil.decodeString(e.getKey()), e -> RESTUtil.decodeString(e.getValue())));
} | @Test
@SuppressWarnings("checkstyle:AvoidEscapedUnicodeCharacters")
public void testOAuth2FormDataDecoding() {
String utf8 = "\u0020\u0025\u0026\u002B\u00A3\u20AC";
String asString = "+%25%26%2B%C2%A3%E2%82%AC";
Map<String, String> expected = ImmutableMap.of("client_id", "12345", "client_secret", utf8);... |
public synchronized List<Page> getPages(
Long tableId,
int partNumber,
int totalParts,
List<Integer> columnIndexes,
long expectedRows)
{
if (!contains(tableId)) {
throw new PrestoException(MISSING_DATA, "Failed to find table on a worker... | @Test(expectedExceptions = PrestoException.class)
public void testTryToReadFromEmptyTable()
{
createTable(0L, 0L);
assertEquals(pagesStore.getPages(0L, 0, 1, ImmutableList.of(0), 0), ImmutableList.of());
pagesStore.getPages(0L, 0, 1, ImmutableList.of(0), 42);
} |
public static URI createURIWithQuery(URI uri, String query) throws URISyntaxException {
String schemeSpecificPart = uri.getRawSchemeSpecificPart();
// strip existing query if any
int questionMark = schemeSpecificPart.lastIndexOf("?");
// make sure question mark is not within parentheses
... | @Test
public void testCompositeCreateURIWithQuery() throws Exception {
String queryString = "query=value";
URI originalURI = new URI("outerscheme:(innerscheme:innerssp)");
URI querylessURI = originalURI;
assertEquals(querylessURI, URISupport.createURIWithQuery(originalURI, null));
... |
static void convertInputData(final List<KiePMMLMiningField> notTargetMiningFields,
final PMMLRequestData requestData) {
logger.debug("convertInputData {} {}", notTargetMiningFields, requestData);
Collection<ParameterInfo> requestParams = requestData.getRequestParams();
... | @Test
void convertInputDataNotConvertibles() {
assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> {
List<KiePMMLMiningField> miningFields = IntStream.range(0, 3).mapToObj(i -> {
DATA_TYPE dataType = DATA_TYPE.values()[i];
new MiningField("FIELD-" +... |
private void updateInputPartitions(final Map<TaskId, CompletableFuture<StateUpdater.RemovedTaskResult>> futures,
final Map<TaskId, Set<TopicPartition>> newInputPartitions,
final Map<TaskId, RuntimeException> failedTasks) {
getNonFaile... | @Test
public void shouldNotUpdateExistingStandbyTaskIfStandbyIsReassignedWithSameInputPartitionWithoutStateUpdater() {
final StandbyTask standbyTask = standbyTask(taskId03, taskId03ChangelogPartitions)
.inState(State.RUNNING)
.withInputPartitions(taskId03Partitions).build();
... |
public IntervalSet negate() {
if (!isValid()) {
return IntervalSet.ALWAYS;
}
if (mStartMs == MIN_MS) {
if (mEndMs == MAX_MS) {
// this is ALWAYS, so the negation is never
return IntervalSet.NEVER;
}
return new IntervalSet(after(mEndMs));
}
// start is after mi... | @Test
public void negateAlways() {
List<Interval> neg = Interval.ALWAYS.negate().getIntervals();
Assert.assertTrue(neg.size() == 1);
Interval in = neg.get(0);
Assert.assertEquals(Interval.NEVER, in);
} |
@Override
public byte[] serialize(final String topic, final T data) {
try {
return delegate.serialize(topic, data);
} catch (final RuntimeException e) {
processingLogger.error(new SerializationError<>(e, Optional.of(data), topic, isKey));
throw e;
}
} | @Test
public void shouldSerializeWithDelegate() {
// Given:
when(delegate.serialize(any(), any())).thenReturn(SOME_BYTES);
// When:
serializer.serialize("some topic", SOME_ROW);
// Then:
verify(delegate).serialize("some topic", SOME_ROW);
} |
public boolean doChannelCloseEvent(final String remoteAddr, final Channel channel) {
boolean removed = false;
Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
while (it.hasNext()) {
Entry<String, ConsumerGroupInfo> next = it.next();
... | @Test
public void doChannelCloseEventTest() {
consumerManager.doChannelCloseEvent("127.0.0.1", channel);
assert consumerManager.getConsumerTable().size() == 0;
} |
public MaterializedConfiguration getConfiguration() {
MaterializedConfiguration conf = new SimpleMaterializedConfiguration();
FlumeConfiguration fconfig = getFlumeConfiguration();
AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName());
if (agentConf != null) {
... | @Test
public void testChannelThrowsExceptionDuringConfiguration() throws Exception {
String agentName = "agent1";
String sourceType = "seq";
String channelType = UnconfigurableChannel.class.getName();
String sinkType = "null";
Map<String, String> properties = getProperties(ag... |
static BayeuxClient createClient(final SalesforceComponent component, final SalesforceSession session)
throws SalesforceException {
// use default Jetty client from SalesforceComponent, it's shared by all consumers
final SalesforceHttpClient httpClient = component.getConfig().getHttpClient()... | @Test
public void defaultLongPollingTimeoutShouldBeGreaterThanSalesforceTimeout() throws SalesforceException {
var endpointConfig = new SalesforceEndpointConfig();
endpointConfig.setHttpClient(mock(SalesforceHttpClient.class));
var session = mock(SalesforceSession.class);
var compone... |
public Cookie decode(String header) {
final int headerLen = checkNotNull(header, "header").length();
if (headerLen == 0) {
return null;
}
CookieBuilder cookieBuilder = null;
loop: for (int i = 0;;) {
// Skip spaces and separators.
for (;;) ... | @Test
public void testDecodingSingleCookieV1ExtraParamsIgnored() {
String cookieString = "myCookie=myValue;max-age=50;path=/apathsomewhere;"
+ "domain=.adomainsomewhere;secure;comment=this is a comment;version=1;"
+ "commentURL=http://aurl.com;port='80,8080';discard;";
... |
static Schema getSchema(Class<? extends Message> clazz) {
return getSchema(ProtobufUtil.getDescriptorForClass(clazz));
} | @Test
public void testNonContiguousOneOfSchema() {
assertEquals(
TestProtoSchemas.NONCONTIGUOUS_ONEOF_SCHEMA,
ProtoSchemaTranslator.getSchema(Proto3SchemaMessages.NonContiguousOneOf.class));
} |
public static String lastElement(List<String> strings) {
checkArgument(!strings.isEmpty(), "empty list");
return strings.get(strings.size() - 1);
} | @Test
public void testLastElementEmpty() throws Throwable {
intercept(IllegalArgumentException.class,
() -> lastElement(new ArrayList<>(0)));
} |
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" )... | @Test
public void testGetLegacyColumnNameFieldNumber() throws Exception {
assertEquals( "NUMBER", new MariaDBDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), getResultSetMetaData(), 1 ) );
} |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
final Optional<ValueRange> valueRange = getValueRangeBody(message);
String range = message.getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A:A").toString();
String majorDimension = message
... | @Test
public void testTransformToValueRangeColumnDimension() throws Exception {
Exchange inbound = new DefaultExchange(camelContext);
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A1:A2");
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX... |
public static QueryOptimizer newOptimizer(HazelcastProperties properties) {
HazelcastProperty property = ClusterProperty.QUERY_OPTIMIZER_TYPE;
String string = properties.getString(property);
Type type;
try {
type = Type.valueOf(string);
} catch (IllegalArgumentExcepti... | @Test
public void newOptimizer_whenPropertyContainsRule_thenCreateRulesBasedOptimizer() {
HazelcastProperties hazelcastProperties = createMockHazelcastProperties(QUERY_OPTIMIZER_TYPE, "RULES");
QueryOptimizer queryOptimizer = QueryOptimizerFactory.newOptimizer(hazelcastProperties);
assertTh... |
private static <T> Set<T> subtract(Set<T> set1, Set<T> set2)
{
return set1.stream()
.filter(value -> !set2.contains(value))
.collect(toLinkedSet());
} | @Test
public void testSubtract()
{
assertEquals(EquatableValueSet.all(TestingIdType.ID).subtract(EquatableValueSet.all(TestingIdType.ID)), EquatableValueSet.none(TestingIdType.ID));
assertEquals(EquatableValueSet.all(TestingIdType.ID).subtract(EquatableValueSet.none(TestingIdType.ID)), Equatable... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseFalseAsBooleanIfSurroundedByWhitespace() {
SchemaAndValue schemaAndValue = Values.parseString(WHITESPACE + "false" + WHITESPACE);
assertEquals(Type.BOOLEAN, schemaAndValue.schema().type());
assertEquals(false, schemaAndValue.value());
} |
public long readWPLong() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0) {
throw new EOFException();
}
return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1);
... | @Test
public void testReadLong() throws Exception {
try (WPInputStream wpInputStream = emptyWPStream()) {
wpInputStream.readWPLong();
fail("should have thrown EOF");
} catch (EOFException e) {
//swallow
}
} |
public URL addParameters(Map<String, String> parameters) {
URLParam newParam = urlParam.addParameters(parameters);
return returnURL(newParam);
} | @Test
void testAddParameters() throws Exception {
URL url = URL.valueOf("dubbo://127.0.0.1:20880");
assertURLStrDecoder(url);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("version", null);
url.addParameters(parameters);
assertURLStrD... |
static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure {
if (!a.exists()) {
throw new IllegalArgumentException("File [" + a + "] does not exist.");
}
if (!b.exists()) {
throw new IllegalArgumentException("File [" + b + "] does not exist.");
... | @Disabled
@Test
public void manual_filesOnDifferentVolumesShouldBeDetectedAsSuch() throws RolloverFailure {
if (!EnvUtil.isJDK7OrHigher())
return;
// author's computer has two volumes
File c = new File("c:/tmp/");
File d = new File("d:/");
assertFalse(FileSto... |
@Override
public RelativeRange apply(final Period period) {
if (period != null) {
return RelativeRange.Builder.builder()
.from(period.withYears(0).withMonths(0).plusDays(period.getYears() * 365).plusDays(period.getMonths() * 30).toStandardSeconds().getSeconds())
... | @Test
void testYearsMonthsPeriodConversion() {
final RelativeRange result = converter.apply(Period.years(5).plusMonths(1));
verifyResult(result, (5 * 365 + 1 * 30) * 24 * 60 * 60);
} |
public static void main(String[] args) throws Exception {
Options cliOptions = CliFrontendOptions.initializeOptions();
CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(cliOptions, args);
// Help message
if (args.length == 0 || commandLine.ha... | @Test
void testMissingFlinkHome() {
assertThatThrownBy(() -> CliFrontend.main(new String[] {pipelineDef()}))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(
"Cannot find Flink home from either command line arguments \"--flink-home\" "
... |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldNotCleanUpInternalTopicsOnReplace() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create stream s1 with (value_format = 'avro') as select * from test1;",
ksqlConfig, Collections.emptyM... |
public static int registerSchema(
final SchemaRegistryClient srClient,
final ParsedSchema parsedSchema,
final String topic,
final String subject,
final boolean isKey
) throws KsqlSchemaAuthorizationException, KsqlException {
try {
if (parsedSchema instanceof ProtobufSchema) {
... | @Test
public void shouldRegisterAvroSchema() throws Exception {
// Given:
when(schemaRegistryClient.register(any(), any(AvroSchema.class))).thenReturn(1);
// When:
SchemaRegistryUtil.registerSchema(schemaRegistryClient, AVRO_SCHEMA, "topic", "subject", false);
// Then:
verify(schemaRegistryC... |
public List<KiePMMLSegment> getSegments() {
return segments;
} | @Test
void getSegments() {
assertThat(KIE_PMML_SEGMENTATION.getSegments()).isNull();
final List<KiePMMLSegment> segments = getKiePMMLSegments();
KIE_PMML_SEGMENTATION = BUILDER.withSegments(segments).build();
assertThat(KIE_PMML_SEGMENTATION.getSegments()).isEqualTo(segments);
} |
@Override
@CheckForNull
public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) {
String bundleKey = propertyToBundles.get(key);
String value = null;
if (bundleKey != null) {
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(bundle... | @Test
public void format_message_with_parameters() {
assertThat(underTest.message(Locale.ENGLISH, "x_results", null, "10")).isEqualTo("10 results");
} |
public static void tryShutdown(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
closeSockets(factory);
try {
factory.node.shutdown(true);
} ... | @Test
public void testTryShutdown() {
tryShutdown(hazelcastInstance);
} |
@Override public void finish() {
finish(0L);
} | @Test void finished_client_annotation() {
finish("cs", "cr", Kind.CLIENT);
} |
public static <T> boolean isPrimitiveType(@Nonnull final Class<T> source)
{
Objects.requireNonNull(source);
if(WRAPPER_TYPES.contains(source))
{
return true;
}
return source.isPrimitive();
} | @SuppressWarnings("DataFlowIssue")
@Test
void isPrimitiveType()
{
Assertions.assertTrue(DataTypeUtil.isPrimitiveType(Integer.class));
Assertions.assertTrue(DataTypeUtil.isPrimitiveType(Byte.class));
Assertions.assertTrue(DataTypeUtil.isPrimitiveType(Character.class));
Assertions.assertTrue(DataTypeUtil.isPri... |
@Override
public void pluginJarAdded(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails);
try {
LOGGER.info("Plugin load starting: {}", bundleOrPluginFileDetails.file())... | @Test
void shouldLoadAPluginWhenAListOfTargetOSesIsNotDeclaredByThePluginInItsXML() throws Exception {
File pluginJarFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
copyPluginToTheDirectory(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
GoPluginBundleDescriptor descriptor = new GoPluginBundleD... |
@Override
protected Mono<Boolean> doMatcher(final ServerWebExchange exchange, final WebFilterChain chain) {
String path = exchange.getRequest().getURI().getRawPath();
return Mono.just(paths.contains(path));
} | @Test
public void testDoNotMatcher() {
ServerWebExchange webExchange =
MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost:8080/"));
Mono<Boolean> filter = excludeFilter.doMatcher(webExchange, webFilterChain);
StepVerifier.create(f... |
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("{component}")
public Response setConfigs(@PathParam("component") String component,
@DefaultValue("false") @QueryParam("preset") boolean preset,
InputStream request) throws IOException {
C... | @Test
public void setConfigs() {
WebTarget wt = target();
try {
wt.path("configuration/foo").request().post(
Entity.json("{ \"k\" : \"v\" }"), String.class);
} catch (BadRequestException e) {
assertEquals("incorrect key", "foo", service.component);... |
@Override
public CeTaskResult getResult() {
checkState(this.result != null, "No CeTaskResult has been set in the holder");
return this.result;
} | @Test
public void getResult_throws_ISE_if_no_CeTaskResult_is_set() {
assertThatThrownBy(() -> underTest.getResult())
.isInstanceOf(IllegalStateException.class)
.hasMessage("No CeTaskResult has been set in the holder");
} |
static <ID, T> TaskExecutors<ID, T> singleItemExecutors(final String name,
int workerCount,
final TaskProcessor<T> processor,
final Acceptor... | @Test
public void testSingleItemProcessingWithTransientError() throws Exception {
taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor);
TaskHolder<Integer, ProcessingResult> taskHolder = transientErrorTaskHolder(1);
taskQueue.add(taskHolder);
//... |
@Override
public void updateCategory(ProductCategorySaveReqVO updateReqVO) {
// 校验分类是否存在
validateProductCategoryExists(updateReqVO.getId());
// 校验父分类存在
validateParentProductCategory(updateReqVO.getParentId());
// 更新
ProductCategoryDO updateObj = BeanUtils.toBean(upda... | @Test
public void testUpdateCategory_success() {
// mock 数据
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class);
productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据
// 准备参数
ProductCategorySaveReqVO reqVO = randomPojo(ProductCategorySaveReqVO.class, o ... |
public static List<String> splitMarkdownParagraphs(
List<String> lines, int maxTokensPerParagraph) {
return internalSplitTextParagraphs(
lines,
maxTokensPerParagraph,
(text) -> internalSplitLines(
text, maxTokensPerParagraph, false, s_markdownSplitOpti... | @Test
public void canSplitMarkdownParagraphsOnNewlines() {
List<String> input = Arrays.asList(
"This_is_a_test_of_the_emergency_broadcast_system\r\nThis_is_only_a_test",
"We_repeat_this_is_only_a_test\nA_unit_test",
"A_small_note\n"
+ "And_another\r\n"
... |
public boolean isBeforeOrAt(KinesisRecord other) {
if (shardIteratorType == AT_TIMESTAMP) {
return timestamp.compareTo(other.getApproximateArrivalTimestamp()) <= 0;
}
int result = extendedSequenceNumber().compareTo(other.getExtendedSequenceNumber());
if (result == 0) {
return shardIteratorTy... | @Test
public void testComparisonWithExtendedSequenceNumber() {
assertThat(
new ShardCheckpoint("", "", new StartingPoint(LATEST))
.isBeforeOrAt(recordWith(new ExtendedSequenceNumber("100", 0L))))
.isTrue();
assertThat(
new ShardCheckpoint("", "", new StartingPo... |
public MutableRecordBatch nextBatch() {
int remaining = buffer.remaining();
Integer batchSize = nextBatchSize();
if (batchSize == null || remaining < batchSize)
return null;
byte magic = buffer.get(buffer.position() + MAGIC_OFFSET);
ByteBuffer batchSlice = buffer.s... | @Test
public void iteratorRaisesOnTooSmallRecords() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, Compression.NONE, TimestampType.CREATE_TIME, 0L);
builder.append(15L, "a".getBytes(), "1".getBytes());
builder.append(20L,... |
@Override
public DatabaseMetaData getMetaData() {
return new CircuitBreakerDatabaseMetaData();
} | @Test
void assertGetMetaData() {
assertThat(connection.getMetaData(), instanceOf(CircuitBreakerDatabaseMetaData.class));
} |
@Override
public void loginSuccess(HttpRequest request, @Nullable String login, Source source) {
checkRequest(request);
requireNonNull(source, "source can't be null");
LOGGER.atDebug().setMessage("login success [method|{}][provider|{}|{}][IP|{}|{}][login|{}]")
.addArgument(source::getMethod)
.... | @Test
public void login_success_prevents_log_flooding_on_login_starting_from_128_chars() {
underTest.loginSuccess(mockRequest(), LOGIN_129_CHARS, Source.realm(Method.BASIC, "some provider name"));
verifyLog("login success [method|BASIC][provider|REALM|some provider name][IP||][login|0123456789012345678901234... |
public boolean isSupported(final SQLStatement sqlStatement) {
for (Class<? extends SQLStatement> each : supportedSQLStatements) {
if (each.isAssignableFrom(sqlStatement.getClass())) {
return true;
}
}
for (Class<? extends SQLStatement> each : unsupportedSQ... | @Test
void assertIsNotSupportedWithInUnsupportedList() {
assertFalse(new SQLSupportedJudgeEngine(Collections.emptyList(), Collections.singleton(SelectStatement.class)).isSupported(mock(SelectStatement.class)));
} |
@Scheduled(fixedDelay = 3000)
public void send() {
CarDto carDto = CarDto.builder()
.id(UUID.randomUUID())
.color("white")
.name("vw")
.build();
RegistrationDto registrationDto = template.convertSendAndReceiveAsType(
dir... | @Test
void sendMessageSynchronously() {
// given
// when
ThrowableAssert.ThrowingCallable send = () -> statefulBlockingClient.send();
// then
assertThatCode(send).doesNotThrowAnyException();
} |
@VisibleForTesting
static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) {
final List<MemoryPoolMXBean> memoryPoolMXBeans =
ManagementFactory.getMemoryPoolMXBeans().stream()
.filter(bean -> "Metaspace".equals(bean.getName()))
... | @Test
void testMetaspaceCompleteness() {
assertThat(hasMetaspaceMemoryPool())
.withFailMessage("Requires JVM with Metaspace memory pool")
.isTrue();
final InterceptingOperatorMetricGroup metaspaceMetrics =
new InterceptingOperatorMetricGroup() {
... |
@Override
public byte[] getBytes(final int columnIndex) throws SQLException {
return (byte[]) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, byte[].class), byte[].class);
} | @Test
void assertGetBytesWithColumnIndex() throws SQLException {
when(mergeResultSet.getValue(1, byte[].class)).thenReturn(new byte[]{(byte) 1});
assertThat(shardingSphereResultSet.getBytes(1), is(new byte[]{(byte) 1}));
} |
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
if (isClosed) {
throw new ClassNotFoun... | @Test
public void directlyCallingNativeMethodShouldBeNoOp() throws Exception {
Class<?> exampleClass = loadClass(AClassWithNativeMethod.class);
Object exampleInstance = exampleClass.getDeclaredConstructor().newInstance();
Method directMethod = findDirectMethod(exampleClass, "nativeMethod", String.class, i... |
@Udf
public <T extends Comparable<? super T>> T arrayMin(@UdfParameter(
description = "Array of values from which to find the minimum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldFindIntMin() {
final List<Integer> input = Arrays.asList(1, 3, -2);
assertThat(udf.arrayMin(input), is(-2));
} |
@Override
public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters,
final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) {
Collection<Stri... | @Test
void assertDecideWhenContainsCombine() {
SelectStatementContext select = createStatementContext();
when(select.isContainsCombine()).thenReturn(true);
Collection<DataNode> includedDataNodes = new HashSet<>();
ShardingRule shardingRule = createShardingRule();
assertTrue(n... |
@Override
public CompletableFuture<List<Long>> getSplitBoundary(BundleSplitOption bundleSplitOption) {
NamespaceService service = bundleSplitOption.getService();
NamespaceBundle bundle = bundleSplitOption.getBundle();
List<Long> positions = bundleSplitOption.getPositions();
if (posit... | @Test
public void testEmptyTopicWithForce() {
SpecifiedPositionsBundleSplitAlgorithm algorithm = new SpecifiedPositionsBundleSplitAlgorithm(true);
NamespaceService mockNamespaceService = mock(NamespaceService.class);
NamespaceBundle mockNamespaceBundle = mock(NamespaceBundle.class);
... |
@Override
public boolean reveal(final Local file, final boolean select) {
synchronized(NSWorkspace.class) {
// If a second path argument is specified, a new file viewer is opened. If you specify an
// empty string (@"") for this parameter, the file is selected in the main viewer.
... | @Test
public void testReveal() {
assertTrue(new WorkspaceRevealService().reveal(new Local(System.getProperty("java.io.tmpdir"))));
} |
public V computeIfAbsent(K key, Function<K, V> provider) {
requireNonNull(key);
requireNonNull(provider);
long h = hash(key);
return getSection(h).put(key, null, (int) h, true, provider);
} | @Test
public void testComputeIfAbsent() {
ConcurrentOpenHashMap<Integer, Integer> map = ConcurrentOpenHashMap.<Integer, Integer>newBuilder()
.expectedItems(16)
.concurrencyLevel(1)
.build();
AtomicInteger counter = new AtomicInteger();
Function... |
@VisibleForTesting
static Comparator<ActualProperties> streamingExecutionPreference(PreferredProperties preferred)
{
// Calculating the matches can be a bit expensive, so cache the results between comparisons
LoadingCache<List<LocalProperty<VariableReferenceExpression>>, List<Optional<LocalPrope... | @Test
public void testPickLayoutPartitionedOnMultiple()
{
Comparator<ActualProperties> preference = streamingExecutionPreference(
PreferredProperties.partitioned(ImmutableSet.of(variable("a"), variable("b"))));
List<ActualProperties> input = ImmutableList.<ActualProperties>build... |
@Override
public LogicalSchema getSchema() {
return schema;
} | @Test
public void shouldHaveFullyQualifiedWindowedSchema() {
// Given:
givenWindowedSource(true);
givenNodeWithMockSource();
// When:
final LogicalSchema schema = node.getSchema();
// Then:
assertThat(schema, is(REAL_SCHEMA.withPseudoAndKeyColsInValue(true)));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.