focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public SSLContext createContext(ContextAware context) throws NoSuchProviderException,
NoSuchAlgorithmException, KeyManagementException,
UnrecoverableKeyException, KeyStoreException, CertificateException {
SSLContext sslContext = getProvider() != null ?
SSLContext.getInstance(getProtocol(), getP... | @Test
public void testCreateDefaultContext() throws Exception {
// should be able to create a context with no configuration at all
assertNotNull(factoryBean.createContext(context));
assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN));
} |
@Override
public Iterable<Product> findAllProducts(String filter) {
if (filter != null && !filter.isBlank()) {
return this.productRepository.findAllByTitleLikeIgnoreCase("%" + filter + "%");
} else {
return this.productRepository.findAll();
}
} | @Test
void findAllProducts_FilterIsSet_ReturnsFilteredProductsList() {
// given
var products = IntStream.range(1, 4)
.mapToObj(i -> new Product(i, "Товар №%d".formatted(i), "Описание товара №%d".formatted(i)))
.toList();
doReturn(products).when(this.productRe... |
public static String subPath(String rootDir, File file) {
try {
return subPath(rootDir, file.getCanonicalPath());
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | @Test
public void subPathTest() {
final Path path = Paths.get("/aaa/bbb/ccc/ddd/eee/fff");
Path subPath = FileUtil.subPath(path, 5, 4);
assertEquals("eee", subPath.toString());
subPath = FileUtil.subPath(path, 0, 1);
assertEquals("aaa", subPath.toString());
subPath = FileUtil.subPath(path, 1, 0);
assert... |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull7() {
// Arrange
final int type = 10;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Exec_load", actual);
} |
@Override
protected Release findLatestActiveRelease(String appId, String clusterName, String namespaceName,
ApolloNotificationMessages clientMessages) {
String messageKey = ReleaseMessageKeyGenerator.generate(appId, clusterName, namespaceName);
String cacheKey = mes... | @Test
public void testFindLatestActiveReleaseWithIrrelevantMessages() throws Exception {
long someNewNotificationId = someNotificationId + 1;
String someIrrelevantKey = "someIrrelevantKey";
when(releaseMessageService.findLatestReleaseMessageForMessages(Lists.newArrayList(someKey))).thenReturn
(so... |
public static Method getApplyMethod(ScalarFn scalarFn) {
Class<? extends ScalarFn> clazz = scalarFn.getClass();
Collection<Method> matches =
ReflectHelpers.declaredMethodsWithAnnotation(
ScalarFn.ApplyMethod.class, clazz, ScalarFn.class);
if (matches.isEmpty()) {
throw new Illegal... | @Test
public void testDifferentMethodSignatureThrowsIllegalArgumentException() {
thrown.expect(instanceOf(IllegalArgumentException.class));
thrown.expectMessage("Found multiple methods annotated with @ApplyMethod.");
ScalarFnReflector.getApplyMethod(new IncrementFnDifferentSignature());
} |
public static PersistenceSchema from(
final List<? extends SimpleColumn> columns,
final SerdeFeatures features
) {
return new PersistenceSchema(columns, features);
} | @Test(expected = IllegalArgumentException.class)
public void shouldThrowOnUnwrapIfMultipleFields() {
PersistenceSchema
.from(MULTI_COLUMN, SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES));
} |
public String getRestfulArtifactUrl(JobIdentifier jobIdentifier, String filePath) {
return format("/files/%s", jobIdentifier.artifactLocator(filePath));
} | @Test
public void shouldReturnProperDownloadUrl() {
String downloadUrl1 = urlService.getRestfulArtifactUrl(jobIdentifier, "file");
String downloadUrl2 = urlService.getRestfulArtifactUrl(jobIdentifier, "/file");
assertThat(downloadUrl1, is("/files/pipelineName/LATEST/stageName/LATEST/buildNam... |
@Override
public int compareTo(SemanticVersion o) {
int cmp;
cmp = compareIntegers(major, o.major);
if (cmp != 0) {
return cmp;
}
cmp = compareIntegers(minor, o.minor);
if (cmp != 0) {
return cmp;
}
cmp = compareIntegers(patch, o.patch);
if (cmp != 0) {
return ... | @Test
public void testCompare() {
assertTrue(new SemanticVersion(1, 8, 1).compareTo(new SemanticVersion(1, 8, 1)) == 0);
assertTrue(new SemanticVersion(1, 8, 0).compareTo(new SemanticVersion(1, 8, 1)) < 0);
assertTrue(new SemanticVersion(1, 8, 2).compareTo(new SemanticVersion(1, 8, 1)) > 0);
assertTr... |
@Override
public KStream<K, V> repartition() {
return doRepartition(Repartitioned.as(null));
} | @Test
public void shouldNotAllowNullRepartitionedOnRepartition() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.repartition(null));
assertThat(exception.getMessage(), equalTo("repartitioned can't be null"));
} |
public String getParameter(String key) {
return urlParam.getParameter(key);
} | @Test
void testGetParameter() {
URL url = URL.valueOf("http://127.0.0.1:8080/path?i=1&b=false");
assertEquals(Integer.valueOf(1), url.getParameter("i", Integer.class));
assertEquals(Boolean.FALSE, url.getParameter("b", Boolean.class));
} |
@Override
public String getAuthenticationMethodName() {
return PostgreSQLAuthenticationMethod.MD5.getMethodName();
} | @Test
void assertAuthenticationMethodName() {
assertThat(new PostgreSQLMD5PasswordAuthenticator().getAuthenticationMethodName(), is("md5"));
} |
public ProtocolBuilder payload(Integer payload) {
this.payload = payload;
return getThis();
} | @Test
void payload() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.payload(40);
Assertions.assertEquals(40, builder.build().getPayload());
} |
@Override
public SqlRequest refactor(QueryParamEntity entity, Object... args) {
if (injector == null) {
initInjector();
}
return injector.refactor(entity, args);
} | @Test
void testTableFunctionJoin() {
QueryAnalyzerImpl analyzer = new QueryAnalyzerImpl(
database,
"select t1.*,t2.key from s_test t1 left join json_each_text('{\"name\":\"test\"}') t2 on t2.key='test' and t2.value='test1'");
SqlRequest request = analyzer
.refact... |
public void notifyKvStateRegistered(
JobVertexID jobVertexId,
KeyGroupRange keyGroupRange,
String registrationName,
KvStateID kvStateId,
InetSocketAddress kvStateServerAddress) {
KvStateLocation location = lookupTable.get(registrationName);
i... | @Test
void testRegisterDuplicateName() throws Exception {
ExecutionJobVertex[] vertices =
new ExecutionJobVertex[] {createJobVertex(32), createJobVertex(13)};
Map<JobVertexID, ExecutionJobVertex> vertexMap = createVertexMap(vertices);
String registrationName = "duplicated-n... |
@Operation(summary = "verifyTenantCode", description = "VERIFY_TENANT_CODE_NOTES")
@Parameters({
@Parameter(name = "tenantCode", description = "TENANT_CODE", required = true, schema = @Schema(implementation = String.class))
})
@GetMapping(value = "/verify-code")
@ResponseStatus(HttpStatus.OK... | @Test
public void testVerifyTenantCode() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("tenantCode", "cxc_test");
MvcResult mvcResult = mockMvc.perform(get("/tenants/verify-code")
.header(SESSION_ID, sessionId)
... |
private Mono<ServerResponse> fetchThemeConfig(ServerRequest request) {
return themeNameInPathVariableOrActivated(request)
.flatMap(themeName -> client.fetch(Theme.class, themeName))
.mapNotNull(theme -> theme.getSpec().getConfigMapName())
.flatMap(configMapName -> client.fetc... | @Test
void fetchThemeConfig() {
Theme theme = new Theme();
theme.setMetadata(new Metadata());
theme.getMetadata().setName("fake");
theme.setSpec(new Theme.ThemeSpec());
theme.getSpec().setConfigMapName("fake-config");
when(client.fetch(eq(ConfigMap.class), eq("fake-c... |
public void reset() {
cb.clear();
} | @Test
public void reset() {
cyclicBufferAppender.append("foobar");
assertEquals(1, cyclicBufferAppender.getLength());
cyclicBufferAppender.reset();
assertEquals(0, cyclicBufferAppender.getLength());
} |
@SuppressWarnings("dereference.of.nullable")
public static PTransform<PCollection<Failure>, PDone> getDlqTransform(String fullConfig) {
List<String> strings = Splitter.on(":").limit(2).splitToList(fullConfig);
checkArgument(
strings.size() == 2, "Invalid config, must start with `identifier:`. %s", ful... | @Test
@Category(NeedsRunner.class)
public void testDlq() {
StoringDlqProvider.reset();
Failure failure1 = Failure.newBuilder().setError("a").setPayload("b".getBytes(UTF_8)).build();
Failure failure2 = Failure.newBuilder().setError("c").setPayload("d".getBytes(UTF_8)).build();
p.apply(Create.of(failu... |
@Override
public String getProviderName() {
return findManagedInstanceService()
.map(ManagedInstanceService::getProviderName)
.orElseThrow(() -> NOT_MANAGED_INSTANCE_EXCEPTION);
} | @Test
public void getProviderName_whenManaged_shouldReturnName() {
DelegatingManagedServices managedInstanceService = new DelegatingManagedServices(Set.of(new AlwaysManagedInstanceService()));
assertThat(managedInstanceService.getProviderName()).isEqualTo("Always");
} |
void printJobQueueInfo(JobQueueInfo jobQueueInfo, Writer writer)
throws IOException {
printJobQueueInfo(jobQueueInfo, writer, "");
} | @Test
@SuppressWarnings("deprecation")
public void testPrintJobQueueInfo() throws IOException {
JobQueueClient queueClient = new JobQueueClient();
JobQueueInfo parent = new JobQueueInfo();
JobQueueInfo child = new JobQueueInfo();
JobQueueInfo grandChild = new JobQueueInfo();
child.addChild(grand... |
@Override
public void demote(NodeId instance, DeviceId deviceId) {
checkNotNull(instance, NODE_ID_NULL);
checkNotNull(deviceId, DEVICE_ID_NULL);
checkPermission(CLUSTER_WRITE);
store.demote(instance, deviceId);
} | @Test
public void demote() {
mgr.setRole(NID1, DID1, MASTER);
mgr.setRole(NID2, DID1, STANDBY);
mgr.setRole(NID3, DID1, STANDBY);
List<NodeId> stdbys = Lists.newArrayList(NID2, NID3);
MastershipInfo mastershipInfo = mgr.getMastershipFor(DID1);
assertTrue(mastershipInf... |
@Override
public void upgrade() {
if (hasBeenRunSuccessfully()) {
LOG.debug("Migration already completed.");
return;
}
final Map<String, String> savedSearchToViewsMap = new HashMap<>();
final Map<View, Search> newViews = this.savedSearchService.streamAll()
... | @Test
@MongoDBFixtures("sample_saved_search_absolute_with_interval_field.json")
public void migrateSavedSearchAbsoluteWithIntervalField() throws Exception {
this.migration.upgrade();
final MigrationCompleted migrationCompleted = captureMigrationCompleted();
assertThat(migrationCompleted... |
public boolean isDefault() {
return (state & MASK_DEFAULT) != 0;
} | @Test
public void isDefault() {
LacpState state = new LacpState((byte) 0x40);
assertTrue(state.isDefault());
} |
@Override
public Set<ReservationAllocation> getReservationsAtTime(long tick) {
return getReservations(null, new ReservationInterval(tick, tick), "");
} | @Test
public void testGetReservationsAtTime() {
Plan plan = new InMemoryPlan(queueMetrics, policy, agent, totalCapacity, 1L,
resCalc, minAlloc, maxAlloc, planName, replanner, true, context);
ReservationId reservationID =
ReservationSystemTestUtil.getNewReservationId();
int[] alloc = { 10, ... |
@Override
public Type classify(final Throwable e) {
Type type = Type.UNKNOWN;
if (e instanceof KsqlSerializationException
|| (e instanceof StreamsException
&& (ExceptionUtils.indexOfThrowable(e, KsqlSerializationException.class) != -1))) {
if (!hasInternalTopicPrefix(e)) {
t... | @Test
public void shouldClassifyWrappedKsqlSerializationExceptionWithUserTopicAsUserError() {
// Given:
final String topic = "foo.bar";
final Exception e = new StreamsException(
new KsqlSerializationException(
topic,
"Error serializing message to topic: " + topic,
... |
@Override
public void preflight(Path file) throws BackgroundException {
assumeRole(file, WRITEPERMISSION);
} | @Test
public void testPreflightFileAccessGrantedCustomProps() throws Exception {
final Path file = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
file.setAttributes(file.attributes().withAcl(new Acl(new Acl.Canonica... |
public static RemotingServer bind(String url, ChannelHandler... handler) throws RemotingException {
return bind(URL.valueOf(url), handler);
} | @Test
void testBind() throws RemotingException {
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind((String) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind((URL) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.b... |
public void putKVConfigValue(final String namespace, final String key, final String value, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
PutKVConfigRequestHeader requestHeader = new PutKVConfigRequestHeader();
requestHeader.setNamespace(namespace);... | @Test
public void testPutKVConfigValue() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
mqClientAPI.putKVConfigValue("", "", "", defaultTimeout);
} |
public static void tryCloseConnections(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
closeSockets(factory);
} | @Test
public void testTryCloseConnections_shouldDoNothingWhenThrowableIsThrown() {
tryCloseConnections(hazelcastInstanceThrowsException);
} |
public static Collection<SubquerySegment> getSubquerySegments(final SelectStatement selectStatement) {
List<SubquerySegment> result = new LinkedList<>();
extractSubquerySegments(result, selectStatement);
return result;
} | @Test
void assertGetSubquerySegmentsInWhere() {
SelectStatement subquerySelectStatement = mock(SelectStatement.class);
when(subquerySelectStatement.getFrom()).thenReturn(Optional.of(new SimpleTableSegment(new TableNameSegment(73, 99, new IdentifierValue("t_order")))));
ProjectionsSegment sub... |
@Override
public T add(K name, V value) {
validateName(nameValidator, true, name);
validateValue(valueValidator, name, value);
checkNotNull(value, "value");
int h = hashingStrategy.hashCode(name);
int i = index(h);
add0(h, i, name, value);
return thisT();
... | @Test
public void testAddSelf() {
final TestDefaultHeaders headers = newInstance();
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
headers.add(headers);
}
});
} |
public void validate(ProjectReactor reactor) {
List<String> validationMessages = new ArrayList<>();
for (ProjectDefinition moduleDef : reactor.getProjects()) {
validateModule(moduleDef, validationMessages);
}
if (isBranchFeatureAvailable()) {
branchParamsValidator.validate(validationMessag... | @Test
void fail_when_pull_request_branch_is_specified_but_branch_plugin_not_present() {
ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo");
ProjectReactor reactor = new ProjectReactor(def);
when(settings.get(ScannerProperties.PULL_REQUEST_BRANCH)).t... |
@Override
public V fetch(final K key, final long time) {
Objects.requireNonNull(key, "key can't be null");
final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType);
for (final ReadOnlyWindowStore<K, V> windowStore : stores) {
try {
... | @Test
public void shouldThrowNPEIfKeyIsNull() {
assertThrows(NullPointerException.class, () -> windowStore.fetch(null, ofEpochMilli(0), ofEpochMilli(0)));
} |
@Override
public SpringCache getCache(final String name) {
return springCaches.computeIfAbsent(name, n -> {
final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n);
return new SpringCache(nativeCache, reactive);
});
} | @Test
public final void getCacheShouldReturnDifferentInstancesForDifferentNames() {
withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) {
@Override
public void call() {
// Given
cm.defineConfiguration("thisCache", new ConfigurationBu... |
public boolean isRegisterEnabled() {
return registerEnabled;
} | @Test
public void testIsRegisterEnabled() {
assertThat(polarisRegistration1.isRegisterEnabled()).isTrue();
} |
@UdafFactory(description = "Compute average of column with type Integer.",
aggregateSchema = "STRUCT<SUM integer, COUNT bigint>")
public static TableUdaf<Integer, Struct, Double> averageInt() {
return getAverageImplementation(
0,
STRUCT_INT,
(sum, newValue) -> sum.getInt32(SUM) + ne... | @Test
public void shouldIgnoreNull() {
final TableUdaf<Integer, Struct, Double> udaf = AverageUdaf.averageInt();
Struct agg = udaf.initialize();
final Integer[] values = new Integer[] {1, 1, 1};
for (final int thisValue : values) {
agg = udaf.aggregate(thisValue, agg);
}
agg = udaf.aggre... |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testValidator452() {
UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html"));
} |
@Override
public Serde<GenericKey> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> schemaRegistryClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
f... | @Test
public void shouldNotWrapInTrackingSerdeIfNoCallbackProvided() {
// When:
factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
verify(innerFactory, never()).wrapInTrackingSerde(any(), any());
} |
private byte[] readToken(HttpURLConnection conn)
throws IOException, AuthenticationException {
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_UNAUTHORIZED) {
String authHeader = conn.getHeaderField(WWW_AUTHENTICATE);
if (authHea... | @Test(timeout = 60000)
public void testReadToken() throws NoSuchMethodException, IOException, IllegalAccessException,
InvocationTargetException {
KerberosAuthenticator kerberosAuthenticator = new KerberosAuthenticator();
FieldUtils.writeField(kerberosAuthenticator, "base64", new Base64(), true);
... |
@Override
protected void init(@Nonnull Context context) {
topics = new ArrayList<>(topicsConfig.getTopicNames());
for (String topic : topics) {
offsets.put(topic, new long[0]);
}
processorIndex = context.globalProcessorIndex();
totalParallelism = context.totalPara... | @Test
public void when_customProjection_then_used() throws Exception {
// When
var processor = createProcessor(properties(), 2, r -> r.key() + "=" + r.value(), 10_000);
TestOutbox outbox = new TestOutbox(new int[]{10}, 10);
processor.init(outbox, new TestProcessorContext());
... |
@Override
public String getActionDescription() {
return "retrieve authentication method for " + registryEndpointRequestProperties.getServerUrl();
} | @Test
public void testGetActionDescription() {
Assert.assertEquals(
"retrieve authentication method for someServerUrl",
testAuthenticationMethodRetriever.getActionDescription());
} |
public static Snowflake getSnowflake(long workerId, long datacenterId) {
return Singleton.get(Snowflake.class, workerId, datacenterId);
} | @Test
public void getSnowflakeTest() {
Snowflake snowflake = IdUtil.getSnowflake(1, 1);
long id = snowflake.nextId();
assertTrue(id > 0);
} |
@Override
public CompletableFuture<TopicStatsTable> getTopicStatsInfo(String address,
GetTopicStatsInfoRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<TopicStatsTable> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(Requ... | @Test
public void assertGetTopicStatsInfoWithSuccess() throws Exception {
TopicStatsTable responseBody = new TopicStatsTable();
setResponseSuccess(RemotingSerializable.encode(responseBody));
GetTopicStatsInfoRequestHeader requestHeader = mock(GetTopicStatsInfoRequestHeader.class);
Co... |
@Override
public RuleNodePath getRuleNodePath() {
return INSTANCE;
} | @Test
void assertNew() {
RuleNodePathProvider ruleNodePathProvider = new ReadwriteSplittingRuleNodePathProvider();
RuleNodePath actualRuleNodePath = ruleNodePathProvider.getRuleNodePath();
assertThat(actualRuleNodePath.getNamedItems().size(), is(2));
assertTrue(actualRuleNodePath.get... |
public Set<MessageOutput> getOutputsForMessage(final Message msg) {
final Set<MessageOutput> result = getStreamOutputsForMessage(msg);
result.add(defaultMessageOutput);
return result;
} | @Test
public void testAlwaysIncludeDefaultOutput() throws Exception {
final Message message = mock(Message.class);
final OutputRouter outputRouter = new OutputRouter(defaultMessageOutput, outputRegistry);
final Collection<MessageOutput> messageOutputs = outputRouter.getOutputsForMessage(mes... |
public void start(long period, TimeUnit unit) {
start(period, period, unit);
} | @Test(expected = IllegalArgumentException.class)
public void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception {
reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS);
reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS);
} |
public Expression rewrite(final Expression expression) {
return new ExpressionTreeRewriter<>(new OperatorPlugin()::process)
.rewrite(expression, null);
} | @Test
public void shouldNotReplaceBetweenExpressionOnNonString() {
// Given:
final Expression predicate = getPredicate(
"SELECT * FROM orders where ROWTIME BETWEEN 123456 AND 147258;");
// When:
final Expression rewritten = rewriter.rewrite(predicate);
// Then:
assertThat(rewritten, ... |
@SuppressWarnings("unchecked")
public <IN, OUT> AvroDatumConverter<IN, OUT> create(Class<IN> inputClass) {
boolean isMapOnly = ((JobConf) getConf()).getNumReduceTasks() == 0;
if (AvroKey.class.isAssignableFrom(inputClass)) {
Schema schema;
if (isMapOnly) {
schema = AvroJob.getMapOutputKeyS... | @Test
void convertFloatWritable() {
AvroDatumConverter<FloatWritable, Float> converter = mFactory.create(FloatWritable.class);
assertEquals(2.2f, converter.convert(new FloatWritable(2.2f)), 0.00001);
} |
public static boolean notMarkedWithNoAutoStart(Object o) {
if (o == null) {
return false;
}
Class<?> clazz = o.getClass();
NoAutoStart a = findAnnotation(clazz, NoAutoStart.class);
return a == null;
} | @Test
public void noAutoStartOnInterface() {
ComponentWithNoAutoStartOnInterface o = new ComponentWithNoAutoStartOnInterface();
assertFalse(NoAutoStartUtil.notMarkedWithNoAutoStart(o));
} |
public static Schema assignIncreasingFreshIds(Schema schema) {
AtomicInteger lastColumnId = new AtomicInteger(0);
return TypeUtil.assignFreshIds(schema, lastColumnId::incrementAndGet);
} | @Test
public void testAssignIncreasingFreshIdWithIdentifier() {
Schema schema =
new Schema(
Lists.newArrayList(
required(10, "a", Types.IntegerType.get()),
required(11, "A", Types.IntegerType.get())),
Sets.newHashSet(10));
Schema expectedSchema =... |
@Override
protected void analyzeDependency(final Dependency dependency, final Engine engine) throws AnalysisException {
// batch request component-reports for all dependencies
synchronized (FETCH_MUTIX) {
if (reports == null) {
try {
requestDelay();
... | @Test
public void should_analyzeDependency_only_warn_when_socket_error_from_sonatype() throws Exception {
// Given
OssIndexAnalyzer analyzer = new OssIndexAnalyzerThrowingSocketTimeout();
getSettings().setBoolean(Settings.KEYS.ANALYZER_OSSINDEX_WARN_ONLY_ON_REMOTE_ERRORS, true);
ana... |
public void addAll(PartitionIdSet other) {
bitSet.or(other.bitSet);
resetSize();
} | @Test
public void test_addAll() {
partitionIdSet.addAll(listOf(0, 1, 2, 3, 4));
assertContents(partitionIdSet);
} |
@SuppressWarnings("unchecked")
public static <W extends BoundedWindow> StateContext<W> nullContext() {
return (StateContext<W>) NULL_CONTEXT;
} | @Test
public void nullContextThrowsOnSideInput() {
StateContext<BoundedWindow> context = StateContexts.nullContext();
thrown.expect(IllegalArgumentException.class);
context.sideInput(view);
} |
public void perform(String url, FetchHandler handler) throws InterruptedException {
int retryCount = 0;
while (true) {
retryCount++;
String message = "";
try {
int rc = download(httpService, url, handler);
if (handler.handleResult(rc, g... | @Test
public void shouldRetryWhenCreatingFolderZipCache() throws Exception {
when(fetchHandler.handleResult(200, publisher)).thenReturn(true);
MockCachingFetchZipHttpService httpService = new MockCachingFetchZipHttpService(3);
DownloadAction downloadAction = new DownloadAction(httpService, p... |
@VisibleForTesting
void sinkTo(
DataStream<Event> input,
Sink<Event> sink,
String sinkName,
OperatorID schemaOperatorID) {
DataStream<Event> stream = input;
// Pre-write topology
if (sink instanceof WithPreWriteTopology) {
stream = ... | @Test
void testPreWriteWithoutCommitSink() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
ArrayList<Event> mockEvents = Lists.newArrayList(new EmptyEvent(), new EmptyEvent());
DataStreamSource<Event> inputStream = env.fromCollection(mockEvents);
... |
@Override
public void doSendMail(MailSendMessage message) {
// 1. 创建发送账号
MailAccountDO account = validateMailAccount(message.getAccountId());
MailAccount mailAccount = MailAccountConvert.INSTANCE.convert(account, message.getNickname());
// 2. 发送邮件
try {
String me... | @Test
public void testDoSendMail_exception() {
try (MockedStatic<MailUtil> mailUtilMock = mockStatic(MailUtil.class)) {
// 准备参数
MailSendMessage message = randomPojo(MailSendMessage.class, o -> o.setNickname("芋艿"));
// mock 方法(获得邮箱账号)
MailAccountDO account = ra... |
public PackageRepository find(final String repoId) {
return stream().filter(repository -> repository.getId().equals(repoId)).findFirst().orElse(null);
} | @Test
void shouldReturnNullIfNoMatchingRepoFound() throws Exception {
PackageRepositories packageRepositories = new PackageRepositories();
assertThat(packageRepositories.find("not-found")).isNull();
} |
public static void validate(WindowConfig windowConfig) {
if (windowConfig.getWindowLengthDurationMs() == null && windowConfig.getWindowLengthCount() == null) {
throw new IllegalArgumentException("Window length is not specified");
}
if (windowConfig.getWindowLengthDurationMs() != nul... | @Test
public void testSettingSlidingTimeWindow() throws Exception {
final Object[][] args = new Object[][]{
{-1L, 10L},
{10L, -1L},
{0L, 10L},
{10L, 0L},
{0L, 0L},
{-1L, -1L},
{5L, 10L},
... |
@Override
public <KR, VR> KStream<KR, VR> map(final KeyValueMapper<? super K, ? super V, ? extends KeyValue<? extends KR, ? extends VR>> mapper) {
return map(mapper, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullNamedOnMap() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.map(KeyValue::pair, null));
assertThat(exception.getMessage(), equalTo("named can't be null"));
} |
public <V> boolean contains(IndexDefinition<T, V> indexDefinition, V value) {
FieldIndex<T, V> index = (FieldIndex<T, V>) mIndices.get(indexDefinition);
if (index == null) {
throw new IllegalStateException("the given index isn't defined for this IndexedSet");
}
return index.containsField(value);
... | @Test
public void NonUniqueContains() {
for (long l = 0; l < 9; l++) {
assertTrue(mSet.contains(mUniqueLongIndex, l));
}
assertFalse(mSet.contains(mUniqueLongIndex, 9L));
} |
Set<SourceName> analyzeExpression(
final Expression expression,
final String clauseType
) {
final Validator extractor = new Validator(clauseType);
extractor.process(expression, null);
return extractor.referencedSources;
} | @Test
public void shouldGetSourceForQualifiedColumnRef() {
// Given:
final QualifiedColumnReferenceExp expression = new QualifiedColumnReferenceExp(
SourceName.of("something"),
ColumnName.of("else")
);
when(sourceSchemas.sourcesWithField(any(), any()))
.thenReturn(ImmutableSet... |
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void givenRulesWhereAddedModifiedOrRemoved_whenEventStep_thenQPChangeEventIsAddedWithDetails() {
QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, BEFORE_DATE);
QualityProfile qp2 = qp(QP_NAME_1, LANGUAGE_KEY_1, AFTER_DATE);
// mock updated profile
qProfileStatusRepository.register(qp2.... |
public static TransactionManager get() {
if (SingletonHolder.INSTANCE == null) {
throw new ShouldNeverHappenException("TransactionManager is NOT ready!");
}
return SingletonHolder.INSTANCE;
} | @Test
void getTest() {
Assertions.assertThrows(ShouldNeverHappenException.class, () -> { TransactionManagerHolder.set(null);
TransactionManagerHolder.get();});
} |
public static void assertSoftly(Consumer<SoftAssertions> softly) {
SoftAssertionsProvider.assertSoftly(SoftAssertions.class, softly);
} | @Test
void should_assert_using_assertSoftly() {
assertThatThrownBy(() -> assertSoftly(assertions -> {
assertions.assertThat(true).isFalse();
assertions.assertThat(42).isEqualTo("meaning of life");
assertions.assertThat("red").isEqualTo("blue");
})).as("it should call assertAll() and fail wit... |
@Override
public void addKey(DeviceKey deviceKey) {
checkNotNull(deviceKey, "Device key cannot be null");
store.createOrUpdateDeviceKey(deviceKey);
} | @Test(expected = NullPointerException.class)
public void testAddNullKey() {
manager.addKey(null);
} |
public static Bech32Data decode(final String str) throws AddressFormatException {
boolean lower = false, upper = false;
if (str.length() < 8)
throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length());
if (str.length() > 90)
throw new AddressFo... | @Test(expected = AddressFormatException.InvalidPrefix.class)
public void decode_invalidHrp() {
Bech32.decode("1pzry9x0s0muk");
} |
public static MongoDatabase createDatabaseProxy(final MongoDatabase database) {
if (DISABLED) {
return database;
}
SERVICES_COUNTER.setDisplayed(!COUNTER_HIDDEN);
SERVICES_COUNTER.setUsed(true);
return JdbcWrapper.createProxy(database, new MongoDatabaseHandler(database));
} | @Test
public void testCreateDatabaseProxy() {
try {
Class.forName("com.mongodb.ReadPreference");
} catch (final ClassNotFoundException e) {
LogManager.getRootLogger().info(e.toString());
// si mongodb-driver-core n'est pas disponible dans le classpath (test depuis Ant),
// on ne peut pas exécuter ce te... |
@Override
public boolean next() throws SQLException {
if (skipAll) {
return false;
}
if (!paginationContext.getActualRowCount().isPresent()) {
return getMergedResult().next();
}
return rowNumber++ < paginationContext.getActualRowCount().get() && getMer... | @Test
void assertNextForRowCountBoundOpenedTrue() throws SQLException {
OracleSelectStatement selectStatement = new OracleSelectStatement();
selectStatement.setProjections(new ProjectionsSegment(0, 0));
WhereSegment whereSegment = mock(WhereSegment.class);
BinaryOperationExpression b... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetName() {
HintAnalyzer instance = new HintAnalyzer();
String expResult = "Hint Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
} |
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
} | @Test
public void testRx() {
RedissonRxClient r1 = createInstance().rxJava();
r1.getRemoteService().register(RemoteInterface.class, new RemoteImpl());
RedissonRxClient r2 = createInstance().rxJava();
RemoteInterfaceRx ri = r2.getRemoteService().get(RemoteInterfaceRx.class);
... |
@Override
public String toString() {
if (null != table && null != column) {
return String.format("database.table.column: '%s'.'%s'.'%s'", database, table, column);
}
if (null != table) {
return String.format("database.table: '%s'.'%s'", database, table);
}
... | @Test
void assertToStringForColumnIdentifier() {
assertThat(new SQLExceptionIdentifier("foo_db", "foo_tbl", "foo_col").toString(), is("database.table.column: 'foo_db'.'foo_tbl'.'foo_col'"));
} |
String getWarFilePath() {
TaskProvider<Task> bootWarTask = TaskCommon.getBootWarTaskProvider(project);
if (bootWarTask != null && bootWarTask.get().getEnabled()) {
return bootWarTask.get().getOutputs().getFiles().getAsPath();
}
TaskProvider<Task> warTask = TaskCommon.getWarTaskProvider(project);
... | @Test
public void testGetWarFilePath_bootWarDisabled() throws IOException {
Path outputDir = temporaryFolder.newFolder("output").toPath();
project.getPlugins().apply("war");
War war = project.getTasks().withType(War.class).getByName("war");
war.getDestinationDirectory().set(outputDir.toFile());
... |
public static BtcFormat getSymbolInstance() { return getSymbolInstance(defaultLocale()); } | @Ignore("non-determinism between OpenJDK versions")
@Test
public void suffixTest() {
BtcFormat deFormat = BtcFormat.getSymbolInstance(Locale.GERMANY);
// int
assertEquals("1,00 ฿", deFormat.format(100000000));
assertEquals("1,01 ฿", deFormat.format(101000000));
assertEqua... |
@NonNull
@Override
public EncodeStrategy getEncodeStrategy(@NonNull Options options) {
Boolean encodeTransformation = options.get(ENCODE_TRANSFORMATION);
return encodeTransformation != null && encodeTransformation
? EncodeStrategy.TRANSFORMED
: EncodeStrategy.SOURCE;
} | @Test
public void testEncodeStrategy_withEncodeTransformationUnSet_returnsSource() {
options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, null);
assertThat(encoder.getEncodeStrategy(options)).isEqualTo(EncodeStrategy.SOURCE);
} |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, Bulkhead bulkhead,
String methodName) throws Throwable {
BulkheadOperator<?> bulkheadOperator = BulkheadOperator.of(bulkhead);
Object returnValue = proceedingJoinPoint.proceed();
return executeRxJava3Aspect(bulkh... | @Test
public void testRxTypes() throws Throwable {
Bulkhead bulkhead = Bulkhead.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava3BulkheadAspectExt.handle(proceedingJoinPoint, bulkhead, "testMethod"))
.isNotNull();
... |
@Override
public void refreshTable(String srDbName, Table table, List<String> partitionNames, boolean onlyCachedPartitions) {
if (isResourceMappingCatalog(catalogName)) {
refreshTableWithResource(table);
} else {
IcebergTable icebergTable = (IcebergTable) table;
S... | @Test
public void testRefreshTableException(@Mocked CachingIcebergCatalog icebergCatalog) {
new Expectations() {
{
icebergCatalog.refreshTable(anyString, anyString, null);
result = new StarRocksConnectorException("refresh failed");
}
};
... |
@Override
public boolean isSplittable() {
return false;
} | @Test
void testSplittable() {
assertThat(AvroParquetReaders.forGenericRecord(schema).isSplittable()).isFalse();
} |
public int length() {
split();
return splitted.size() - 1;
} | @Test
public void testLengthCPs() {
final UnicodeHelper lh = new UnicodeHelper("a", Method.CODEPOINTS);
assertEquals(1, lh.length());
final UnicodeHelper lh2 = new UnicodeHelper(new String(Character.toChars(0x1f600)), Method.CODEPOINTS);
assertEquals(1, lh2.length());
final... |
public static boolean contains(File file, String pattern) throws IOException {
try (Scanner fileScanner = new Scanner(file, UTF_8.name())) {
final Pattern regex = Pattern.compile(pattern);
if (fileScanner.findWithinHorizon(regex, 0) != null) {
return true;
}
... | @Test
public void testContains_File_String() throws Exception {
File file = BaseTest.getResourceAsFile(this, "SearchTest.txt");
String pattern = "blue";
boolean expResult = false;
boolean result = FileContentSearch.contains(file, pattern);
assertEquals(expResult, result);
... |
public static BsonTimestamp decodeTimestamp(BsonDocument resumeToken) {
BsonValue bsonValue =
Objects.requireNonNull(resumeToken, "Missing ResumeToken.").get(DATA_FIELD);
final byte[] keyStringBytes;
// Resume Tokens format: https://www.mongodb.com/docs/manual/changeStreams/#resu... | @Test
public void testDecodeBinDataFormat() {
BsonDocument resumeToken =
BsonDocument.parse(
"{\"_data\": {\"$binary\": {\"base64\": \"gmNXqzwAAAABRmRfaWQAZGNXqj41xq4H4ebHNwBaEATmzwG2DzpOl4tpOyYEG9zABA==\", \"subType\": \"00\"}}}");
BsonTimestamp expected = ne... |
public void updateAll() throws InterruptedException {
LOGGER.debug("DAILY UPDATE ALL");
var extensions = repositories.findAllPublicIds();
var extensionPublicIdsMap = extensions.stream()
.filter(e -> StringUtils.isNotEmpty(e.getPublicId()))
.collect(Collectors.toMa... | @Test
public void testUpdateAllNoChanges() throws InterruptedException {
var namespaceName1 = "foo";
var namespacePublicId1 = UUID.randomUUID().toString();
var extensionName1 = "bar";
var extensionPublicId1 = UUID.randomUUID().toString();
var namespace1 = new Namespace();
... |
public URL getInterNodeListener(
final Function<URL, Integer> portResolver
) {
return getInterNodeListener(portResolver, LOGGER);
} | @Test
public void shouldResolveInterNodeListenerToFirstListenerSetToIpv4Loopback() {
// Given:
final URL expected = url("https://127.0.0.2:12345");
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"... |
public Map<String, String> getPdiParameters() {
return pdiParameters;
} | @Test
public void getPdiParameters() {
JobScheduleRequest jobScheduleRequest = mock( JobScheduleRequest.class );
when( jobScheduleRequest.getPdiParameters() ).thenCallRealMethod();
Map<String, String> pdiParameters = new HashMap<>();
pdiParameters.put( "hitachi", "vantara" );
ReflectionTestUtils.s... |
@SuppressWarnings("deprecation")
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> left,
final KStreamHolder<K> right,
final StreamStreamJoin<K> join,
final RuntimeBuildContext buildContext,
final StreamJoinedFactory streamJoinedFactory) {
final QueryContext queryConte... | @Test
public void shouldBuildRightSerdeCorrectly() {
// Given:
givenInnerJoin(L_KEY);
// When:
join.build(planBuilder, planInfo);
// Then:
final QueryContext leftCtx = QueryContext.Stacker.of(CTX).push("Right").getQueryContext();
verify(buildContext).buildValueSerde(FormatInfo.of(FormatF... |
public static <K, V> Read<K, V> read() {
return new AutoValue_KafkaIO_Read.Builder<K, V>()
.setTopics(new ArrayList<>())
.setTopicPartitions(new ArrayList<>())
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES)
... | @Test
public void testUnboundedSourceWithExceptionInKafkaFetch() {
// Similar testUnboundedSource, but with an injected exception inside Kafk Consumer poll.
// The reader should throw an IOException:
thrown.expectCause(isA(IOException.class));
thrown.expectCause(hasMessage(containsString("Exception w... |
@Override
public long size() {
return colIndex[n];
} | @Test
public void testSize() {
System.out.println("size");
assertEquals(7, sparse.size());
} |
public ValueMetaInterface getValueMetaFor( int resultType, String name ) throws KettlePluginException {
// don't need any synchronization as data instance belongs only to one step instance
ValueMetaInterface meta = resultMetaMapping.get( resultType );
if ( meta == null ) {
meta = ValueMetaFactory.crea... | @Test
public void dataReturnsCachedValues() throws Exception {
KettleEnvironment.init( false );
CalculatorData data = new CalculatorData();
ValueMetaInterface valueMeta = data.getValueMetaFor( ValueMetaInterface.TYPE_INTEGER, null );
ValueMetaInterface shouldBeTheSame = data.getValueMetaFor( ValueMet... |
static int evaluateLevenshteinDistanceBestHits(LevenshteinDistance levenshteinDistance, List<String> terms,
List<String> texts) {
logger.debug("evaluateLevenshteinDistanceBestHits {} {}", terms, texts);
int batchSize = terms.size();
int limit = ... | @Test
void evaluateLevenshteinDistanceBestHits() {
String wordSeparatorCharacterRE = "\\s+"; // brown-foxy does not match
Pattern pattern = Pattern.compile(wordSeparatorCharacterRE);
List<String> terms = KiePMMLTextIndex.splitText("The", pattern);
List<String> texts = KiePMMLTextInde... |
@Override
public Collection<RedisServer> masters() {
List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS);
return toRedisServersList(masters);
} | @Test
public void testMasters() {
Collection<RedisServer> masters = connection.masters();
assertThat(masters).hasSize(1);
} |
public void encryptColumns(
String inputFile, String outputFile, List<String> paths, FileEncryptionProperties fileEncryptionProperties)
throws IOException {
Path inPath = new Path(inputFile);
Path outPath = new Path(outputFile);
RewriteOptions options = new RewriteOptions.Builder(conf, inPath, o... | @Test
public void testColumnIndex() throws IOException {
String[] encryptColumns = {"Name"};
testSetup("GZIP");
columnEncryptor.encryptColumns(
inputFile.getFileName(),
outputFile,
Arrays.asList(encryptColumns),
EncDecProperties.getFileEncryptionProperties(encryptColumns, P... |
@SuppressWarnings("unchecked")
@Override
public synchronized ProxyInfo<T> getProxy() {
if (currentUsedHandler != null) {
return currentUsedHandler;
}
Map<String, ProxyInfo<T>> targetProxyInfos = new HashMap<>();
StringBuilder combinedInfo = new StringBuilder("[");
for (int i = 0; i < proxi... | @Test
public void testExceptionInfo() throws Exception {
final ClientProtocol goodMock = mock(ClientProtocol.class);
when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
private boolean first = true;
@Override
public long[] answer(InvocationOnMock invocation)
throws Throwabl... |
public void increaseUsage(long value) {
if (value == 0) {
return;
}
usageLock.writeLock().lock();
try {
usage += value;
setPercentUsage(caclPercentUsage());
} finally {
usageLock.writeLock().unlock();
}
if (parent ... | @Test
public final void testPercentUsageNeedsNoThread() {
int activeThreadCount = Thread.activeCount();
underTest.setLimit(10);
underTest.start();
underTest.increaseUsage(1);
assertEquals("usage is correct", 10, underTest.getPercentUsage());
assertEquals("no new t... |
protected static boolean isValidQueueName(String queueName) {
if (queueName != null) {
if (queueName.equals(FairSchedulerUtilities.trimQueueName(queueName)) &&
!queueName.startsWith(DOT) &&
!queueName.endsWith(DOT)) {
return true;
}
}
return false;
} | @Test
public void testIsValidQueueName() {
// permutations of valid/invalid names
final String valid = "valid";
final String validRooted = "root.valid";
final String rootOnly = "root";
final String startDot = ".invalid";
final String endDot = "invalid.";
final String startSpace = " invalid... |
public static String diffProvenance(ModelProvenance originalProvenance, ModelProvenance newProvenance) throws JsonProcessingException {
Iterator<Pair<String, Provenance>> originalIter = originalProvenance.iterator();
Iterator<Pair<String, Provenance>> newIter = newProvenance.iterator();
String... | @Test
public void testProvDiffWithTransformTrainer() throws IOException, URISyntaxException {
//TODO: Expand this to actually assert something
CSVDataSource<Label> csvSource = getCSVDataSource();
MutableDataset<Label> datasetFromCSV = new MutableDataset<>(csvSource);
LogisticRegress... |
static void setTableInputInformation(
TableInput.Builder tableInputBuilder, TableMetadata metadata) {
setTableInputInformation(tableInputBuilder, metadata, null);
} | @Test
public void testSetTableInputInformationWithRemovedColumns() {
// Actual TableInput
TableInput.Builder actualTableInputBuilder = TableInput.builder();
Schema schema =
new Schema(
Types.NestedField.required(1, "x", Types.StringType.get(), "comment1"),
Types.NestedField... |
public Printed<K, V> withKeyValueMapper(final KeyValueMapper<? super K, ? super V, String> mapper) {
Objects.requireNonNull(mapper, "mapper can't be null");
this.mapper = mapper;
return this;
} | @Test
public void shouldPrintWithKeyValueMapper() throws UnsupportedEncodingException {
final Processor<String, Integer, Void, Void> processor = new PrintedInternal<>(
sysOutPrinter.withKeyValueMapper((key, value) -> String.format("%s -> %d", key, value))
).build("processor").get();
... |
@Override
public void finishSink(String dbName, String tableName, List<TSinkCommitInfo> commitInfos, String branch) {
boolean isOverwrite = false;
if (!commitInfos.isEmpty()) {
TSinkCommitInfo sinkCommitInfo = commitInfos.get(0);
if (sinkCommitInfo.isSetIs_overwrite()) {
... | @Test
public void testFinishSink() {
IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG);
IcebergMetadata metadata = new IcebergMetadata(CATALOG_NAME, HDFS_ENVIRONMENT, icebergHiveCatalog,
Executors.newSingleThreadExecuto... |
public static ByteBuf copyInt(int value) {
ByteBuf buf = buffer(4);
buf.writeInt(value);
return buf;
} | @Test
public void testWrapInt() {
ByteBuf buffer = copyInt(1, 4);
assertEquals(8, buffer.capacity());
assertEquals(1, buffer.readInt());
assertEquals(4, buffer.readInt());
assertFalse(buffer.isReadable());
buffer.release();
buffer = copyInt(null);
ass... |
@Override
public void copyTo(byte[] dest, int destPos) {
if (totalSize() > 0) {
System.arraycopy(payload, 0, dest, destPos, payload.length);
}
} | @Test
public void copyTo() {
byte[] inputBytes = "12345678890".getBytes();
HeapData heap = new HeapData(inputBytes);
byte[] bytes = new byte[inputBytes.length];
heap.copyTo(bytes, 0);
assertEquals(new String(inputBytes), new String(bytes));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.