focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public <T extends Tuple> DataSource<T> tupleType(Class<T> targetType) {
Preconditions.checkNotNull(targetType, "The target type class must not be null.");
if (!Tuple.class.isAssignableFrom(targetType)) {
throw new IllegalArgumentException(
"The target type must be a subcl... | @Test
void testUnsupportedPartialitem() {
CsvReader reader = getCsvReader();
assertThatThrownBy(() -> reader.tupleType(PartialItem.class))
.withFailMessage("tupleType() accepted an underspecified generic class.")
.isInstanceOf(Exception.class);
} |
public RemotingParser isRemoting(Object bean, String beanName) {
for (RemotingParser remotingParser : allRemotingParsers) {
if (remotingParser.isRemoting(bean, beanName)) {
return remotingParser;
}
}
return null;
} | @Test
public void testIsRemoting() {
SimpleRemoteBean remoteBean = new SimpleRemoteBean();
RemotingParser parser = remotingParser.isRemoting(remoteBean, remoteBean.getClass().getName());
assertInstanceOf(SimpleRemotingParser.class, parser);
} |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void manyBytesReadByteBuffer() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE);
ByteBuffer buffer = ByteBuffer.allocate(CHUNK_SIZE);
try (FileInStream inStream = getStream(ufsPath)) {
assertEquals(CHUNK_SIZE, inStream.read(bu... |
@Override
public KStream<K, V> merge(final KStream<K, V> stream) {
return merge(stream, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullKStreamOnMerge() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.merge(null));
assertThat(exception.getMessage(), equalTo("stream can't be null"));
} |
public static InputStream getResourceAsStream(String resource) throws IOException {
ClassLoader loader = ResourceUtils.class.getClassLoader();
return getResourceAsStream(loader, resource);
} | @Test
void testGetResourceAsStreamForClasspathFromSystem() throws IOException {
try (InputStream inputStream = ResourceUtils.getResourceAsStream(null, "test-tls-cert.pem")) {
assertNotNull(inputStream);
}
} |
@Override
@SneakyThrows
public String createFile(String name, String path, byte[] content) {
// 计算默认的 path 名
String type = FileTypeUtils.getMineType(content, name);
if (StrUtil.isEmpty(path)) {
path = FileUtils.generatePath(content, name);
}
// 如果 name 为空,则使用 ... | @Test
public void testCreateFile_success() throws Exception {
// 准备参数
String path = randomString();
byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
// mock Master 文件客户端
FileClient client = mock(FileClient.class);
when(fileConfigService.getMasterFileClient... |
public boolean hasTimeLeft() {
return clock.instant().isBefore(endTime);
} | @Test
public void testHasTimeLeft() {
ManualClock clock = new ManualClock();
TimeoutBudget budget = new TimeoutBudget(clock, Duration.ofMillis(7));
assertThat(budget.hasTimeLeft(), is(true));
clock.advance(Duration.ofMillis(1));
assertThat(budget.hasTimeLeft(), is(true));
... |
Map<String, Object> sourceAdminConfig(String role) {
Map<String, Object> props = new HashMap<>();
props.putAll(originalsWithPrefix(SOURCE_CLUSTER_PREFIX));
props.keySet().retainAll(MirrorClientConfig.CLIENT_CONFIG_DEF.names());
props.putAll(originalsWithPrefix(ADMIN_CLIENT_PREFIX));
... | @Test
public void testSourceAdminConfig() {
Map<String, String> connectorProps = makeProps(
MirrorConnectorConfig.ADMIN_CLIENT_PREFIX +
"connections.max.idle.ms", "10000"
);
MirrorConnectorConfig config = new TestMirrorConnectorConfig(connectorProps);
... |
@SuppressWarnings("FutureReturnValueIgnored")
public void start() {
running.set(true);
configFetcher.start();
memoryMonitor.start();
streamingWorkerHarness.start();
sampler.start();
workerStatusReporter.start();
activeWorkRefresher.start();
} | @Test
public void testKeyTokenInvalidException() throws Exception {
if (streamingEngine) {
// TODO: This test needs to be adapted to work with streamingEngine=true.
return;
}
KvCoder<String, String> kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of());
List<ParallelInstruction... |
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) {
if (statsEnabled) {
stats.log(deviceStateServiceMsg);
}
stateService.onQueueMsg(deviceStateServiceMsg, callback);
} | @Test
public void givenProcessingFailure_whenForwardingInactivityMsgToStateService_thenOnFailureCallbackIsCalled() {
// GIVEN
var inactivityMsg = TransportProtos.DeviceInactivityProto.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantId... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNonEmpty_Collection_nullFirst_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", null, new InnerObject("inner", 0, 1, 2, 3));
Getter parentGetter = GetterFactory.new... |
@Override
public KeyValueStore<K, V> build() {
return new MeteredKeyValueStore<>(
maybeWrapCaching(maybeWrapLogging(storeSupplier.get())),
storeSupplier.metricsScope(),
time,
keySerde,
valueSerde);
} | @Test
public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() {
setUp();
final KeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
as... |
@Override
public List<QueuedCommand> getNewCommands(final Duration timeout) {
completeSatisfiedSequenceNumberFutures();
final List<QueuedCommand> commands = Lists.newArrayList();
final Iterable<ConsumerRecord<byte[], byte[]>> records = commandTopic.getNewCommands(timeout);
for (ConsumerRecord<byte[]... | @Test
public void shouldFilterNullCommands() {
// Given:
final ConsumerRecords<byte[], byte[]> records = buildRecords(
commandId, null,
commandId, command);
final Deserializer<Command> commandDeserializer = mock(Deserializer.class);
when(commandDeserializer.deserialize(any(), any())).t... |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewName(), "New name must not be null!");
byte[] ... | @Test
public void testRename_keyNotExist() {
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot));
if (sameSlot) {
// This is a quirk of the implementation - since same-slot renames use the non... |
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> childConstructor) {
return Stream.ofNullable(get(key))
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::str... | @Test
void shouldRetrieveEmptyStreamForNonExistingChildren() {
var children = document.children(KEY, DocumentImplementation::new);
assertNotNull(children);
assertEquals(0, children.count());
} |
public double[] colMeans() {
double[] x = new double[n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
x[j] += get(i, j);
}
x[j] /= m;
}
return x;
} | @Test
public void testColMeans() {
System.out.println("colMeans");
double[][] A = {
{ 0.7220180, 0.07121225, 0.6881997f},
{-0.2648886, -0.89044952, 0.3700456f},
{-0.6391588, 0.44947578, 0.6240573f}
};
double[] r = {-0.06067647, -0.123... |
@Override
public void readLine(String line) {
if (line.startsWith("%") || line.isEmpty()) {
return;
}
if(line.startsWith("descr:") && this.organization == null) {
this.organization = lineValue(line);
}
if(line.startsWith("country:") && this.countryCo... | @Test
public void testRunDirectMatch() throws Exception {
APNICResponseParser parser = new APNICResponseParser();
for (String line : MATCH.split("\n")) {
parser.readLine(line);
}
assertEquals("SG", parser.getCountryCode());
assertEquals("SIMPLE SOLUTION SYSTEMS P... |
private boolean detectCharset(byte[] buf) throws IOException {
ByteCharsetDetector detector = new ByteCharsetDetector(new CharsetValidation(), userEncoding);
ByteOrderMark bom = detector.detectBOM(buf);
if (bom != null) {
detectedCharset = Charset.forName(bom.getCharsetName());
stream.skip(bom.l... | @Test
public void always_try_utf8() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// this is a valid 2 byte UTF-8.
out.write(194);
out.write(128);
Path filePath = temp.newFile().toPath();
Files.write(filePath, out.toByteArray());
assertThat(detectCharset(fi... |
@SuppressWarnings("unchecked")
@Override
public <S extends StateStore> S getStateStore(final String name) {
final StateStore store = stateManager.getGlobalStore(name);
return (S) getReadWriteStore(store);
} | @Test
public void shouldNotAllowInitForTimestampedKeyValueStore() {
when(stateManager.getGlobalStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME)).thenReturn(mock(TimestampedKeyValueStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME);
try ... |
public static void copy(int[] src, long[] dest, int length) {
for (int i = 0; i < length; i++) {
dest[i] = src[i];
}
} | @Test
public void testCopyFromIntArray() {
ArrayCopyUtils.copy(INT_ARRAY, LONG_BUFFER, COPY_LENGTH);
ArrayCopyUtils.copy(INT_ARRAY, FLOAT_BUFFER, COPY_LENGTH);
ArrayCopyUtils.copy(INT_ARRAY, DOUBLE_BUFFER, COPY_LENGTH);
ArrayCopyUtils.copy(INT_ARRAY, STRING_BUFFER, COPY_LENGTH);
for (int i = 0; i ... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NodeInfo nodeInfo = (NodeInfo) o;
return name.equals(nodeInfo.name);
} | @Test
public void test_equals_and_hashCode() {
NodeInfo foo = new NodeInfo("foo");
NodeInfo bar = new NodeInfo("bar");
NodeInfo bar2 = new NodeInfo("bar");
assertThat(foo.equals(foo)).isTrue();
assertThat(foo.equals(bar)).isFalse();
assertThat(bar.equals(bar2)).isTrue();
assertThat(bar)
... |
public static PartitionKey createPartitionKey(List<String> values, List<Column> columns) throws AnalysisException {
return createPartitionKey(values, columns, Table.TableType.HIVE);
} | @Test
public void testCreateDeltaLakePartitionKey() throws AnalysisException {
PartitionKey partitionKey = createPartitionKey(
Lists.newArrayList("1", "a", "3.0", DeltaLakeTable.PARTITION_NULL_VALUE), partColumns,
Table.TableType.DELTALAKE);
Assert.assertEquals("(\"1\... |
@Timed
@Path("/{destination}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
@Operation(
summary = "Send a message",
description = """
Deliver a message to a single recipient. May be authenticated or unauthenticated; if unauthenticated... | @Test
void testSingleDeviceCurrent() throws Exception {
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.... |
public static void ensureAllReadsConsumed(Pipeline pipeline) {
final Set<PCollection<?>> unconsumed = new HashSet<>();
pipeline.traverseTopologically(
new PipelineVisitor.Defaults() {
@Override
public void visitPrimitiveTransform(Node node) {
unconsumed.removeAll(node.get... | @Test
public void matcherProducesUnconsumedValueBoundedRead() {
Bounded<Long> transform = Read.from(CountingSource.upTo(20L));
pipeline.apply(transform);
UnconsumedReads.ensureAllReadsConsumed(pipeline);
validateConsumed();
} |
@Override
public Thread newThread(Runnable target) {
return delegate.newThread(target);
} | @Test
void requireThatThreadFactoryCallsProvider() {
MetricConsumerProvider provider = Mockito.mock(MetricConsumerProvider.class);
ThreadFactory factory = new ContainerThreadFactory(provider);
factory.newThread(Mockito.mock(Runnable.class));
Mockito.verify(provider, Mockito.times(1))... |
public static DataSourceProvider tryGetDataSourceProviderOrNull(Configuration hdpConfig) {
final String configuredPoolingType = MetastoreConf.getVar(hdpConfig,
MetastoreConf.ConfVars.CONNECTION_POOLING_TYPE);
return Iterables.tryFind(FACTORIES, factory -> {
String poolingType = factory.getPoolingT... | @Test
public void testEvictIdleConnection() throws Exception {
String[] dataSourceType = {HikariCPDataSourceProvider.HIKARI, DbCPDataSourceProvider.DBCP};
try (DataSourceProvider.DataSourceNameConfigurator configurator =
new DataSourceProvider.DataSourceNameConfigurator(conf, "mutex")) {
fo... |
@Override
public String name() {
return type.getSimpleName();
} | @Test
void test() {
assertThat(target.name()).isEqualTo("MockTargetTest");
} |
public OkHttpClient build() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.proxy(proxy);
if (connectTimeoutMs >= 0) {
builder.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS);
}
if (readTimeoutMs >= 0) {
builder.readTimeout(readTimeoutMs, TimeUnit.MILLISECOND... | @Test
public void build_default_instance_of_OkHttpClient() {
OkHttpClient okHttpClient = underTest.build();
assertThat(okHttpClient.proxy()).isNull();
assertThat(okHttpClient.networkInterceptors()).hasSize(2);
assertThat(okHttpClient.sslSocketFactory()).isNotNull();
assertThat(okHttpClient.follow... |
@Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedi... | @Test(expected = IllegalArgumentException.class)
public void heartMode_implicit_redirectUris() {
Mockito.when(config.isHeartMode()).thenReturn(true);
ClientDetailsEntity client = new ClientDetailsEntity();
Set<String> grantTypes = new LinkedHashSet<>();
grantTypes.add("implicit");
client.setGrantTypes(grant... |
@Override
public HoodieTimeline getTimeline() {
return execute(preferredView::getTimeline, () -> getSecondaryView().getTimeline());
} | @Test
public void testGetTimeline() {
HoodieTimeline actual;
HoodieTimeline expected = new MockHoodieTimeline(Stream.empty(), Stream.empty());
when(primary.getTimeline()).thenReturn(expected);
actual = fsView.getTimeline();
assertEquals(expected, actual);
verify(secondaryViewSupplier, never()... |
@VisibleForTesting
void recover() {
try (DbSession dbSession = dbClient.openSession(false)) {
Profiler profiler = Profiler.create(LOGGER).start();
long beforeDate = system2.now() - minAgeInMs;
IndexingResult result = new IndexingResult();
Collection<EsQueueDto> items = dbClient.esQueueDao... | @Test
public void recover_multiple_times_the_same_document() {
EsQueueDto item1 = insertItem(FOO_TYPE, "f1");
EsQueueDto item2 = insertItem(FOO_TYPE, item1.getDocId());
EsQueueDto item3 = insertItem(FOO_TYPE, item1.getDocId());
advanceInTime();
SuccessfulFakeIndexer indexer = new SuccessfulFakeIn... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() != 5 && data.size() != 7) {
onInvalidDataReceived(device, data);
return;
}
final int timeOffset = data.getIntValue(Data.FORMAT_UINT16_LE, 0);
f... | @Test
public void onContinuousGlucoseMonitorStatusChanged_withCrc() {
final DataReceivedCallback callback = new CGMStatusDataCallback() {
@Override
public void onContinuousGlucoseMonitorStatusChanged(@NonNull final BluetoothDevice device, @NonNull final CGMStatus status,
final int timeOffset, f... |
@Override
public V get(K key) {
begin();
V value = transactionalMap.get(key);
commit();
return value;
} | @Test
public void testGet() {
map.put(42, "foobar");
String result = adapter.get(42);
assertEquals("foobar", result);
} |
public static ValueLabel formatPacketRate(long packets) {
return new ValueLabel(packets, PACKETS_UNIT).perSec();
} | @Test
public void formatPacketRateKilo() {
vl = TopoUtils.formatPacketRate(1024);
assertEquals(AM_WL, "1 Kpps", vl.toString());
} |
public StorageEntity queryResourcesFileInfo(String userName, String fullName) throws Exception {
return resourceService.queryFileStatus(userName, fullName);
} | @Test
public void testQueryResourcesFileInfo() throws Exception {
User user = getTestUser();
StorageEntity storageEntity = getTestResource();
Mockito.when(resourcesService.queryFileStatus(user.getUserName(), storageEntity.getFullName()))
.thenReturn(storageEntity);
S... |
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
checkInitialized();
for (Callback callback : callbacks) {
if (callback instanceof OAuthBearerTokenCallback) {
handleTokenCallback((OAuthBearerTokenCallback) callback);
... | @Test
public void testNotConfigured() {
OAuthBearerLoginCallbackHandler handler = new OAuthBearerLoginCallbackHandler();
assertThrowsWithMessage(IllegalStateException.class, () -> handler.handle(new Callback[] {}), "first call the configure or init method");
} |
public long getLastAccessTime() {
return lastAccessTime;
} | @Test
public void getLastAccessTime() {
long lastAccessTime = replicatedRecord.getLastAccessTime();
sleepAtLeastMillis(100);
replicatedRecord.setValue("newValue", 0);
assertTrue("replicatedRecord.getLastAccessTime() should return a greater access time",
replicatedRec... |
public static ConfigDefinitionKey createConfigDefinitionKeyFromDefFile(File file) throws IOException {
String[] fileName = file.getName().split("\\.");
assert (fileName.length >= 2);
String name = fileName[fileName.length - 2];
byte[] content = IOUtils.readFileBytes(file);
retur... | @Test
public void testCreateConfigDefinitionKeyFromDefFile() {
ConfigDefinitionKey def = null;
try {
def = ConfigUtils.createConfigDefinitionKeyFromDefFile(new File("src/test/resources/configs/def-files/app.def"));
} catch (IOException e) {
e.printStackTrace();
... |
@Override
public String getOperationName(Exchange exchange, Endpoint endpoint) {
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
String opName = queryParameters.get("operation");
if (opName != null) {
return opName;
}
return sup... | @Test
public void testGetOperationName() {
Endpoint endpoint = Mockito.mock(Endpoint.class);
Mockito.when(endpoint.getEndpointUri()).thenReturn(MONGODB_STATEMENT);
SpanDecorator decorator = new MongoDBSpanDecorator();
assertEquals("findOneByQuery", decorator.getOperationName(null,... |
public static String encodeSetCookie(HttpCookie cookie)
{
if (cookie == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(cookie.getName()).append("=").append(cookie.getValue());
if (cookie.getPath() != null)
{
sb.append(";Path=").append(cookie.getPath(... | @Test
public void testCookieAttributeEncoding()
{
String encodedCookie = CookieUtil.encodeSetCookie(cookieA);
Assert.assertTrue(encodedCookie.contains("Domain=.android.com"));
Assert.assertTrue(encodedCookie.contains("Path=/source/"));
Assert.assertTrue(encodedCookie.contains("Max-Age=125"));
A... |
public AlluxioURI joinUnsafe(String suffix) {
String path = getPath();
StringBuilder sb = new StringBuilder(path.length() + 1 + suffix.length());
return new AlluxioURI(this,
sb.append(path).append(AlluxioURI.SEPARATOR).append(suffix).toString(), false);
} | @Test
public void joinUnsafe() {
assertEquals(new AlluxioURI("/a"), new AlluxioURI("/").joinUnsafe("a"));
assertEquals(new AlluxioURI("/a/b"), new AlluxioURI("/a").joinUnsafe("b"));
assertEquals(new AlluxioURI("a/b"), new AlluxioURI("a").joinUnsafe("b"));
assertEquals(new AlluxioURI("a/b.txt"), new Al... |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void greaterThanOrEqual() {
assertUnifiesAndInlines(
"4 >= 17",
UBinary.create(Kind.GREATER_THAN_EQUAL, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
} | @SuppressWarnings("unchecked")
@Test
void testRuntimeException() {
ExceptionFilter exceptionFilter = new ExceptionFilter();
RpcInvocation invocation = new RpcInvocation(
"sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"});
... |
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
} | @Test
void testToObject13() {
assertThrows(Exception.class, () -> {
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass());
});
} |
@Override
public Num calculate(BarSeries series, Position position) {
if (position.isClosed()) {
Num profit = excludeCosts ? position.getGrossProfit() : position.getProfit();
return profit.isPositive() ? profit : series.zero();
}
return series.zero();
} | @Test
public void calculateProfitWithShortPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 95, 100, 70, 80, 85, 100);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(1, series),
Trade.sellAt(2, series), Trade.buyAt(5, series... |
@Override
public synchronized void markEvent() {
eventTimestamps.add(clock.absoluteTimeMillis());
eventCount++;
} | @Test
void testMarkEvent() {
final ThresholdMeter thresholdMeter = createLargeThresholdMeter();
thresholdMeter.markEvent();
clock.advanceTime(SLEEP, TimeUnit.MILLISECONDS);
assertThat(thresholdMeter.getCount()).isOne();
assertThat(thresholdMeter.getRate()).isCloseTo(toPerSec... |
static JarFileWithEntryClass findOnlyEntryClass(Iterable<File> jarFiles) throws IOException {
List<JarFileWithEntryClass> jarsWithEntryClasses = new ArrayList<>();
for (File jarFile : jarFiles) {
findEntryClass(jarFile)
.ifPresent(
entryClass -... | @Test
void testFindOnlyEntryClassEmptyArgument() {
assertThatThrownBy(() -> JarManifestParser.findOnlyEntryClass(Collections.emptyList()))
.isInstanceOf(NoSuchElementException.class);
} |
@Override
public boolean checkMasterWritable() {
testMasterWritableJT.setDataSource(jt.getDataSource());
// Prevent the login interface from being too long because the main library is not available
testMasterWritableJT.setQueryTimeout(1);
String sql = " SELECT @@read_only ";... | @Test
void testCheckMasterWritable() {
when(testMasterWritableJT.queryForObject(eq(" SELECT @@read_only "), eq(Integer.class))).thenReturn(0);
assertTrue(service.checkMasterWritable());
} |
@Override
public boolean isDisposed() {
return !running.get();
} | @Test
void testIssue416() {
TestResources resources = TestResources.get();
TestResources.set(ConnectionProvider.create("testIssue416"));
assertThat(resources.provider.isDisposed()).isTrue();
assertThat(resources.loops.isDisposed()).isFalse();
TestResources.set(LoopResources.create("test"));
assertThat(re... |
@Override
public boolean isAdded(Component component) {
checkComponent(component);
if (analysisMetadataHolder.isFirstAnalysis()) {
return true;
}
return addedComponents.contains(component);
} | @Test
public void isAdded_returns_false_for_unregistered_component_type_when_not_on_first_analysis() {
when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false);
Arrays.stream(Component.Type.values()).forEach(type -> {
Component component = newComponent(type);
assertThat(underTest.isAdded... |
@Override
public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final EueApiClient client = new EueApiClient(session);
if(status.isExists()) {
... | @Test(expected = NotfoundException.class)
public void testMoveNotFound() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path test = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
test.attributes().setFi... |
public void await() {
mSync.acquire(IGNORED_ARG);
} | @Test
public void await() throws Exception {
Assert.assertEquals(0, mLatch.getState());
mLatch.inc();
Assert.assertEquals(1, mLatch.getState());
mLatch.inc();
Assert.assertEquals(2, mLatch.getState());
BlockingThread await = new BlockingThread(mLatch::await);
await.start();
Assert.as... |
public static Map<TopicPartition, Long> fetchCommittedOffsets(final Set<TopicPartition> partitions,
final Consumer<byte[], byte[]> consumer) {
if (partitions.isEmpty()) {
return Collections.emptyMap();
}
final Map<Top... | @Test
public void fetchCommittedOffsetsShouldRethrowTimeoutException() {
@SuppressWarnings("unchecked")
final Consumer<byte[], byte[]> consumer = mock(Consumer.class);
when(consumer.committed(PARTITIONS)).thenThrow(new TimeoutException());
assertThrows(TimeoutException.class, () -> f... |
public void isEqualTo(@Nullable Object expected) {
standardIsEqualTo(expected);
} | @Test
@SuppressWarnings("TruthIncompatibleType") // test of a mistaken call
public void disambiguationWithSameToString() {
expectFailure.whenTesting().that(new StringBuilder("foo")).isEqualTo(new StringBuilder("foo"));
assertFailureKeys("expected", "but was");
assertFailureValue("expected", "foo");
... |
@Override
public List<PluginWrapper> getUnresolvedPlugins() {
return Collections.emptyList();
} | @Test
public void getUnresolvedPlugins() {
assertNotNull(wrappedPluginManager);
assertNotNull(wrappedPluginManager.getUnresolvedPlugins());
assertTrue(wrappedPluginManager.getUnresolvedPlugins().isEmpty());
} |
public static <T> IterableCoder<T> of(Coder<T> elemCoder) {
return new IterableCoder<>(elemCoder);
} | @Test
public void testCoderIsSerializableWithWellKnownCoderType() throws Exception {
CoderProperties.coderSerializable(ListCoder.of(GlobalWindow.Coder.INSTANCE));
} |
public static <T> RestResult<T> failed() {
return RestResult.<T>builder().withCode(500).build();
} | @Test
void testSuccessWithFull() {
RestResult<String> restResult = RestResultUtils.failed(400, "content", "test");
assertRestResult(restResult, 400, "test", "content", false);
} |
public static Iterator<Row> computeUpdates(
Iterator<Row> rowIterator, StructType rowType, String[] identifierFields) {
Iterator<Row> carryoverRemoveIterator = removeCarryovers(rowIterator, rowType);
ChangelogIterator changelogIterator =
new ComputeUpdateIterator(carryoverRemoveIterator, rowType, ... | @Test
public void testUpdatedRowsWithDuplication() {
List<Row> rowsWithDuplication =
Lists.newArrayList(
// two rows with same identifier fields(id, name)
new GenericRowWithSchema(new Object[] {1, "a", "data", DELETE, 0, 0}, null),
new GenericRowWithSchema(new Object[] ... |
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"})
public static boolean isScalablePushQuery(
final Statement statement,
final KsqlExecutionContext ksqlEngine,
final KsqlConfig ksqlConfig,
final Map<String, Object> overrides
) {
if (!isPushV2Enabled(ksqlConfig, ov... | @Test
public void isScalablePushQuery_true() {
try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) {
// Given:
expectIsSPQ(ColumnName.of("foo"), columnExtractor);
// When:
final boolean isScalablePush = ScalablePushUtil.isScalablePushQuery(
que... |
public void put(final T object) {
PortablePreconditions.checkNotNull("Object can not be null",
object);
final UUIDKey uuidKey = UUIDKey.getUUIDKey(object.keys());
if (keys.contains(uuidKey)) {
throw new IllegalArgumentException("UUID alrea... | @Test
void testReAdd() throws Exception {
assertThrows(IllegalArgumentException.class, () -> {
put(toni);
});
} |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testReadFieldsSpaces() {
String[] readFields = {" f1 ; f2 "};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, null, null, readFields, threeIntTupleType, threeIntTupleType);
... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void loginButton() {
String text = "login";
String url = "https://pengrad.herokuapp.com/hello";
SendResponse response = bot.execute(
new SendMessage(chatId, "Login button").replyMarkup(new InlineKeyboardMarkup(
new InlineKeyboardButton(tex... |
public static String get(String urlString, Charset customCharset) {
return HttpRequest.get(urlString).charset(customCharset).execute().body();
} | @Test
@Disabled
public void sinajsTest(){
final String s = HttpUtil.get("http://hq.sinajs.cn/list=sh600519");
Console.log(s);
} |
public Range<PartitionKey> handleNewSinglePartitionDesc(Map<ColumnId, Column> schema, SingleRangePartitionDesc desc,
long partitionId, boolean isTemp) throws DdlException {
Range<PartitionKey> range;
try {
range = checkAndCreateRang... | @Test(expected = DdlException.class)
public void testInt() throws DdlException, AnalysisException {
Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", "");
partitionColumns.add(k1);
singleRangePartitionDescs.add(new SingleRangePartitionDesc(false, "p1",
... |
@Override
public void destroy() {
path2Invoker.clear();
} | @Test
void testDestroy() {
Assertions.assertEquals(INVOKER, getInvokerByPath("/abc"));
{
PATH_RESOLVER.add("/bcd", INVOKER);
Assertions.assertEquals(INVOKER, getInvokerByPath("/bcd"));
}
PATH_RESOLVER.destroy();
Assertions.assertNull(getInvokerByPath("... |
@Description("decode the 64-bit big-endian binary in IEEE 754 double-precision floating-point format")
@ScalarFunction("from_ieee754_64")
@SqlType(StandardTypes.DOUBLE)
public static double fromIEEE754Binary64(@SqlType(StandardTypes.VARBINARY) Slice slice)
{
checkCondition(slice.length() == Doub... | @Test
public void testFromIEEE754Binary64()
{
assertFunction("from_ieee754_64(from_hex('0000000000000000'))", DOUBLE, 0.0);
assertFunction("from_ieee754_64(from_hex('3FF0000000000000'))", DOUBLE, 1.0);
assertFunction("from_ieee754_64(to_ieee754_64(3.1415926))", DOUBLE, 3.1415926);
... |
@Override
public SelJodaDateTimeZone assignOps(SelOp op, SelType rhs) {
if (op == SelOp.ASSIGN) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
this.val = ((SelJodaDateTimeZone) rhs).val;
return this;
}
throw new UnsupportedOperationException(type() + " DO NOT support assignment o... | @Test
public void testAssignOps() {
one.assignOps(SelOp.ASSIGN, another);
assertEquals("DATETIME_ZONE: America/Los_Angeles", one.type() + ": " + one);
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AlluxioURI)) {
return false;
}
AlluxioURI that = (AlluxioURI) o;
return mUri.equals(that.mUri);
} | @Test
public void queryEquals() {
Map<String, String> queryMap = new HashMap<>();
queryMap.put("a", "b");
queryMap.put("c", "d");
assertTrue(new AlluxioURI("scheme://host:123/a.txt?a=b&c=d")
.equals(new AlluxioURI("scheme://host:123/a.txt?a=b&c=d")));
// There is no guarantee which order ... |
public static ArchivedExecutionGraph createFrom(ExecutionGraph executionGraph) {
return createFrom(executionGraph, null);
} | @Test
void testSerialization() throws IOException, ClassNotFoundException {
ArchivedExecutionGraph archivedGraph = ArchivedExecutionGraph.createFrom(runtimeGraph);
verifySerializability(archivedGraph);
} |
@Deprecated
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype)
throws IllegalStateException {
return Types.resolveLastTypeParameter(genericContext, supertype);
} | @Test
void unboundWildcardIsObject() throws Exception {
Type context =
LastTypeParameter.class.getDeclaredField("PARAMETERIZED_DECODER_UNBOUND").getGenericType();
Type last = resolveLastTypeParameter(context, ParameterizedDecoder.class);
assertThat(last).isEqualTo(Object.class);
} |
@Override
public boolean alterOffsets(Map<String, String> config, Map<Map<String, ?>, Map<String, ?>> offsets) {
for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) {
Map<String, ?> sourceOffset = offsetEntry.getValue();
if (sourceOffset == null) {
... | @Test
public void testAlterOffsetsMultiplePartitions() {
MirrorHeartbeatConnector connector = new MirrorHeartbeatConnector();
Map<String, ?> partition1 = sourcePartition("primary", "backup");
Map<String, ?> partition2 = sourcePartition("backup", "primary");
Map<Map<String, ?>, Map<... |
@Override
public void deregisterInstance(String serviceName, String ip, int port) throws NacosException {
deregisterInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);
} | @Test
void testDeregisterInstance5() throws NacosException {
//given
String serviceName = "service1";
Instance instance = new Instance();
//when
client.deregisterInstance(serviceName, instance);
//then
verify(proxy, times(1)).deregisterService(serviceName, Con... |
@Operation(summary = "queryClusterByCode", description = "QUERY_CLUSTER_BY_CODE_NOTES")
@Parameters({
@Parameter(name = "clusterCode", description = "CLUSTER_CODE", required = true, schema = @Schema(implementation = long.class, example = "100"))
})
@GetMapping(value = "/query-by-code")
@Resp... | @Test
public void testQueryClusterByCode() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("clusterCode", clusterCode);
MvcResult mvcResult = mockMvc.perform(get("/cluster/query-by-code")
.header(SESSION_ID, sessionId)
... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void underlineStrikethroughMessageEntity() {
String cap = "<u>under1</u> <ins>under2</ins> <s>strike1</s> <strike>strike2</strike> <del>strike3</del>";
cap += " <u><del>nested-tag</del></u>";
ParseMode parseMode = ParseMode.HTML;
SendAudio sendAudio = new SendAudio(chatI... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeCreateTypeCorrectly() {
// simple statement
Assert.assertEquals("CREATE TYPE type AS INTEGER;",
anon.anonymize("CREATE TYPE ADDRESS AS INTEGER;"));
// more elaborate statement
final String output = anon.anonymize(
"CREATE TYPE ADDRESS AS STRUCT<number ... |
public ConcurrentHashMap<String, ConcurrentHashMap<Channel, ClientChannelInfo>> getGroupChannelTable() {
return groupChannelTable;
} | @Test
public void testGetGroupChannelTable() throws Exception {
producerManager.registerProducer(group, clientInfo);
Map<Channel, ClientChannelInfo> oldMap = producerManager.getGroupChannelTable().get(group);
producerManager.unregisterProducer(group, clientInfo);
assertThat(... |
@Override
public void process(Exchange exchange) throws Exception {
Object payload = exchange.getMessage().getBody();
if (payload == null) {
return;
}
JsonNode answer = computeIfAbsent(exchange);
if (answer != null) {
exchange.setProperty(SchemaHelpe... | @Test
void shouldReadSchemaFromSchema() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
exchange.setProperty(SchemaHelper.CONTENT_CLASS, Person.class.getName());
String schemaString = new String(this.getClass().getResourceAsStream("person.schema.json").readAllByte... |
@Override
Class<?> getReturnType() {
throw new IllegalArgumentException("Non applicable for PortableGetter");
} | @Test(expected = IllegalArgumentException.class)
public void getReturnType() {
new PortableGetter(null).getReturnType();
} |
@Override
public Response onApply(WriteRequest request) {
final Lock lock = readLock;
lock.lock();
try {
final InstanceStoreRequest instanceRequest = serializer.deserialize(request.getData().toByteArray());
final DataOperation operation = DataOperation.valueOf(request... | @Test
void testOnApply() {
PersistentClientOperationServiceImpl.InstanceStoreRequest request = new PersistentClientOperationServiceImpl.InstanceStoreRequest();
Service service1 = Service.newService("A", "B", "C");
request.setService(service1);
request.setClientId("xxxx");
req... |
public RemotingChannel removeProducerChannel(ProxyContext ctx, String group, Channel channel) {
return removeChannel(buildProducerKey(group), channel);
} | @Test
public void testRemoveProducerChannel() {
String group = "group";
String clientId = RandomStringUtils.randomAlphabetic(10);
{
Channel producerChannel = createMockChannel();
RemotingChannel producerRemotingChannel = this.remotingChannelManager.createProducerChan... |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test(expected = RuntimeException.class)
public void shouldThrowIfParseThrows() {
// Given:
when(ksqlEngine.parse(any())).thenThrow(new RuntimeException("Boom!"));
// When:
standaloneExecutor.startAsync();
} |
@Override
public void put(ExecutionGraphInfo serializableExecutionGraphInfo) throws IOException {
serializableExecutionGraphInfos.put(
serializableExecutionGraphInfo.getJobId(), serializableExecutionGraphInfo);
} | @Test
public void testPut() throws IOException {
assertPutJobGraphWithStatus(JobStatus.FINISHED);
} |
@Override
public boolean tryClaim(StreamProgress streamProgress) {
if (shouldStop) {
return false;
}
// We perform copy instead of assignment because we want to ensure all references of
// streamProgress gets updated.
this.streamProgress = streamProgress;
return true;
} | @Test
public void testTryClaim() {
final StreamProgress streamProgress = new StreamProgress();
final ReadChangeStreamPartitionProgressTracker tracker =
new ReadChangeStreamPartitionProgressTracker(streamProgress);
assertEquals(streamProgress, tracker.currentRestriction());
ChangeStreamContinu... |
public static double lchoose(int n, int k) {
if (k < 0 || k > n) {
throw new IllegalArgumentException(String.format("Invalid n = %d, k = %d", n, k));
}
return lfactorial(n) - lfactorial(k) - lfactorial(n - k);
} | @Test
public void testLogChoose() {
System.out.println("logChoose");
assertEquals(0.0, MathEx.lchoose(10, 0), 1E-6);
assertEquals(2.302585, MathEx.lchoose(10, 1), 1E-6);
assertEquals(3.806662, MathEx.lchoose(10, 2), 1E-6);
assertEquals(4.787492, MathEx.lchoose(10, 3), 1E-6);
... |
public static boolean webSocketHostPathMatches(String hostPath, String targetPath) {
boolean exactPathMatch = true;
if (ObjectHelper.isEmpty(hostPath) || ObjectHelper.isEmpty(targetPath)) {
// This scenario should not really be possible as the input args come from the vertx-websocket consum... | @Test
void webSocketHostWildcardPathNotMatches() {
String hostPath = "/foo/bar/cheese/wine*";
String targetPath = "/foo/bar/cheese/win";
assertFalse(VertxWebsocketHelper.webSocketHostPathMatches(hostPath, targetPath));
} |
protected boolean shouldAnalyze() {
if (analyzer instanceof FileTypeAnalyzer) {
final FileTypeAnalyzer fileTypeAnalyzer = (FileTypeAnalyzer) analyzer;
return fileTypeAnalyzer.accept(dependency.getActualFile());
}
return true;
} | @Test
public void shouldAnalyzeReturnsFalseIfTheFileTypeAnalyzerDoesNotAcceptTheDependency() {
final File dependencyFile = new File("");
new Expectations() {{
dependency.getActualFile();
result = dependencyFile;
fileTypeAnalyzer.accept(dependencyFile);
... |
public static <K, V> VersionedKeyQuery<K, V> withKey(final K key) {
Objects.requireNonNull(key, "key cannot be null.");
return new VersionedKeyQuery<>(key, Optional.empty());
} | @Test
public void shouldThrowNPEWithNullKey() {
final Exception exception = assertThrows(NullPointerException.class, () -> VersionedKeyQuery.withKey(null));
assertEquals("key cannot be null.", exception.getMessage());
} |
public static Map<String, String> toStringMap(String... pairs) {
Map<String, String> parameters = new HashMap<>();
if (ArrayUtils.isEmpty(pairs)) {
return parameters;
}
if (pairs.length > 0) {
if (pairs.length % 2 != 0) {
throw new IllegalArgument... | @Test
void testStringMap2() {
Assertions.assertThrows(IllegalArgumentException.class, () -> toStringMap("key", "value", "odd"));
} |
public boolean isFound() {
return found;
} | @Test
public void testCalcInstructionsForTurn() {
// The street turns left, but there is not turn
Weighting weighting = new SpeedWeighting(mixedCarSpeedEnc);
Path p = new Dijkstra(roundaboutGraph.g, weighting, TraversalMode.NODE_BASED)
.calcPath(11, 13);
assertTrue(p.... |
public MethodBuilder name(String name) {
this.name = name;
return getThis();
} | @Test
void name() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.name("name");
Assertions.assertEquals("name", builder.build().getName());
} |
@Override
public Response call(Request req) {
if (!logger.isDebugEnabled()) {
return delegate.call(req);
}
logger
.atDebug()
.addKeyValue("url", () -> req.uri().toString())
.addKeyValue(
"headers",
() ->
req.headers().stream()
... | @Test
void infoLevel() {
var res = new HttpClient.Response(200, List.of(), null);
var delegate = mock(HttpClient.class);
when(delegate.call(any())).thenReturn(res);
var sut = new LoggingHttpClient(delegate);
logger.setLevel(Level.INFO);
// when
sut.call(
new HttpClient.Request... |
@Override
public Optional<Track<T>> clean(Track<T> track) {
TreeSet<Point<T>> points = new TreeSet<>(track.points());
Iterator<Point<T>> iter = points.iterator();
Long tau = null;
while (iter.hasNext()) {
Point point = iter.next();
//the 1st time through t... | @Test
public void testDownSampling() {
Duration maxTimeDelta = Duration.ofSeconds(5);
TimeDownSampler<String> smoother = new TimeDownSampler<>(maxTimeDelta);
Track<String> cleanedTrack = smoother.clean(testTrack()).get();
Point last = null;
for (Point point : cleanedTrack.... |
@Override
public Collection<SlotOffer> offerSlots(
TaskManagerLocation taskManagerLocation,
TaskManagerGateway taskManagerGateway,
Collection<SlotOffer> offers) {
assertHasBeenStarted();
if (!isTaskManagerRegistered(taskManagerLocation.getResourceID())) {
... | @Test
void testSlotOfferingOfUnknownTaskManagerIsIgnored() throws Exception {
try (DeclarativeSlotPoolService declarativeSlotPoolService =
createDeclarativeSlotPoolService()) {
final Collection<SlotOffer> slotOffers =
Collections.singletonList(
... |
public List<R> scanForResourcesUri(URI classpathResourceUri) {
requireNonNull(classpathResourceUri, "classpathResourceUri must not be null");
if (CLASSPATH_SCHEME.equals(classpathResourceUri.getScheme())) {
return scanForClasspathResource(resourceName(classpathResourceUri), NULL_FILTER);
... | @Test
void scanForResourcesJarUri() {
URI jarFileUri = new File("src/test/resources/io/cucumber/core/resource/test/jar-resource.jar").toURI();
URI resourceUri = URI
.create("jar:file://" + jarFileUri.getSchemeSpecificPart() + "!/com/example/package-jar-resource.txt");
List<UR... |
@Override
public List<String> listTableNames(String dbName) {
try (Connection connection = getConnection()) {
try (ResultSet resultSet = schemaResolver.getTables(connection, dbName)) {
ImmutableList.Builder<String> list = ImmutableList.builder();
while (resultSet.... | @Test
public void testListTableNames() {
try {
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
List<String> result = jdbcMetadata.listTableNames("test");
List<String> expectResult = Lists.newArrayList("tbl1", "tbl2", "tbl3");
A... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchOduSignalTypeTest() {
OduSignalType signalType = OduSignalType.ODU2;
Criterion criterion = Criteria.matchOduSignalType(signalType);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@Override
public Point<NopHit> next() {
Point<NopHit> returnMe = nextPoint;
this.nextPoint = getNext();
return returnMe;
} | @Test
public void testNext() throws Exception {
File testFile = buildTestFile("testNopFileB.txt");
PointIterator iter = new PointIterator(new NopParser(testFile));
int numPoints = 0;
while (iter.hasNext()) {
Point next = iter.next();
if (numPoints == 0) {... |
public String table(TableIdentifier ident) {
return SLASH.join(
"v1",
prefix,
"namespaces",
RESTUtil.encodeNamespace(ident.namespace()),
"tables",
RESTUtil.encodeString(ident.name()));
} | @Test
public void testTableWithSlash() {
TableIdentifier ident = TableIdentifier.of("n/s", "tab/le");
assertThat(withPrefix.table(ident)).isEqualTo("v1/ws/catalog/namespaces/n%2Fs/tables/tab%2Fle");
assertThat(withoutPrefix.table(ident)).isEqualTo("v1/namespaces/n%2Fs/tables/tab%2Fle");
} |
public static Criterion matchSctpDst(TpPort sctpPort) {
return new SctpPortCriterion(sctpPort, Type.SCTP_DST);
} | @Test
public void testMatchSctpDstMethod() {
Criterion matchSctpDst = Criteria.matchSctpDst(tpPort1);
SctpPortCriterion sctpPortCriterion =
checkAndConvert(matchSctpDst,
Criterion.Type.SCTP_DST,
SctpPortCriterion.class);... |
@Override
public ManageSnapshots createBranch(String name) {
Snapshot currentSnapshot = transaction.currentMetadata().currentSnapshot();
if (currentSnapshot != null) {
return createBranch(name, currentSnapshot.snapshotId());
}
SnapshotRef existingRef = transaction.currentMetadata().ref(name);
... | @TestTemplate
public void testCreateBranch() {
table.newAppend().appendFile(FILE_A).commit();
long snapshotId = table.currentSnapshot().snapshotId();
// Test a basic case of creating a branch
table.manageSnapshots().createBranch("branch1", snapshotId).commit();
SnapshotRef expectedBranch = table.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.