focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public TopicName createTopic(String topicName) {
checkArgument(!topicName.isEmpty(), "topicName can not be empty");
checkIsUsable();
TopicName name = getTopicName(topicName);
return createTopicInternal(name);
} | @Test
public void testCreateTopicWithInvalidNameShouldFail() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> testManager.createTopic(""));
assertThat(exception).hasMessageThat().contains("topicName can not be empty");
} |
public static Date strToDate(String dateStr) throws ParseException {
return strToDate(dateStr, DATE_FORMAT_TIME);
} | @Test
public void strToDate1() throws Exception {
long d0 = 0l;
long d1 = 1501127802975l; // 2017-07-27 11:56:42:975 +8
long d2 = 1501127835658l; // 2017-07-27 11:57:15:658 +8
TimeZone timeZone = TimeZone.getDefault();
Date date0 = new Date(d0 - timeZone.getOffset(d0));
... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void instanceOfExpression() {
String inputExpression = "\"foo\" instance of string";
BaseNode instanceOfBase = parse( inputExpression );
assertThat( instanceOfBase).isInstanceOf(InstanceOfNode.class);
assertThat( instanceOfBase.getText()).isEqualTo(inputExpression);
as... |
public static boolean isNameCoveredByPattern( String name, String pattern )
{
if ( name == null || name.isEmpty() || pattern == null || pattern.isEmpty() )
{
throw new IllegalArgumentException( "Arguments cannot be null or empty." );
}
final String needle = name.toLowerC... | @Test
public void testNameCoveragePartialMatchButNoSubdomain() throws Exception
{
// setup
final String name = "xmppexample.org";
final String pattern = "example.org";
// do magic
final boolean result = DNSUtil.isNameCoveredByPattern( name, pattern );
// verify
... |
@Override
public List<MenuDO> getMenuList() {
return menuMapper.selectList();
} | @Test
public void testGetMenuList_ids() {
// mock 数据
MenuDO menu100 = randomPojo(MenuDO.class);
menuMapper.insert(menu100);
MenuDO menu101 = randomPojo(MenuDO.class);
menuMapper.insert(menu101);
// 准备参数
Collection<Long> ids = Collections.singleton(menu100.getI... |
@Override
public String telnet(Channel channel, String message) {
if (StringUtils.isEmpty(message)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
StringBuilder buf = new StringBuilder();
if ("/".equals(message) || "..".equals(mess... | @Test
void testChangeServiceNotExport() throws RemotingException {
String result = change.telnet(mockChannel, "demo");
assertEquals("No such service demo", result);
} |
public String convertMultipleArguments(Object... objectList) {
StringBuilder buf = new StringBuilder();
Converter<Object> c = headTokenConverter;
while (c != null) {
if (c instanceof MonoTypedConverter) {
MonoTypedConverter monoTyped = (MonoTypedConverter) c;
... | @Test
public void objectListConverter() {
Calendar cal = Calendar.getInstance();
cal.set(2003, 4, 20, 17, 55);
FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context);
assertEquals("foo-2003.05.20-79.txt", fnp.convertMultipleArguments(cal.getTime(), 79));
... |
@Override
public void validateOffsetFetch(
String memberId,
int memberEpoch,
long lastCommittedOffset
) throws UnknownMemberIdException, StaleMemberEpochException, IllegalGenerationException {
// When the member id is null and the member epoch is -1, the request either comes
... | @Test
public void testValidateOffsetFetch() {
SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
ConsumerGroup group = new ConsumerGroup(
snapshotRegistry,
"group-foo",
mock(GroupCoordinatorMetricsShard.class)
);
// Simula... |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionMap)
throws InterruptedException {
String hadoopVersion;
try {
hadoopVersion = getHadoopVersion();
} catch (IOException e) {
return new ValidationTaskResult(ValidationUtils.State.FAILED, getName(),
... | @Test
public void versionNotMatched() throws Exception {
PowerMockito.mockStatic(ShellUtils.class);
String[] cmd = new String[]{"hadoop", "version"};
BDDMockito.given(ShellUtils.execCommand(cmd)).willReturn("Hadoop 2.7");
CONF.set(PropertyKey.UNDERFS_VERSION, "2.6");
HdfsVersionValidationTask tas... |
@Override
public void executor(final Collection<MetaDataRegisterDTO> metaDataRegisterDTOList) {
for (MetaDataRegisterDTO metaDataRegisterDTO : metaDataRegisterDTOList) {
shenyuClientRegisterRepository.persistInterface(metaDataRegisterDTO);
}
} | @Test
public void testExecutorWithEmptyData() {
Collection<MetaDataRegisterDTO> metaDataRegisterDTOList = new ArrayList<>();
executorSubscriber.executor(metaDataRegisterDTOList);
verify(shenyuClientRegisterRepository, never()).persistInterface(any());
} |
@SuppressWarnings("unchecked") // safe because we only read, not write
/*
* non-final because it's overridden by MultimapWithProtoValuesSubject.
*
* If we really, really wanted it to be final, we could investigate whether
* MultimapWithProtoValuesFluentAssertion could provide its own valuesForKey method. ... | @Test
public void valuesForKey() {
ImmutableMultimap<Integer, String> multimap =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
assertThat(multimap).valuesForKey(3).hasSize(3);
assertThat(multimap).valuesForKey(4).containsExactly("four", "five");
assertThat(multimap... |
public void addShipFiles(List<Path> shipFiles) {
checkArgument(
!isUsrLibDirIncludedInShipFiles(shipFiles, yarnConfiguration),
"User-shipped directories configured via : %s should not include %s.",
YarnConfigOptions.SHIP_FILES.key(),
ConfigConstant... | @Test
void testDisableSystemClassPathIncludeUserJarAndWithIllegalShipDirectoryName() {
final Configuration configuration = new Configuration();
configuration.set(CLASSPATH_INCLUDE_USER_JAR, YarnConfigOptions.UserJarInclusion.DISABLED);
final YarnClusterDescriptor yarnClusterDescriptor =
... |
public static byte[] max(final byte[] a, final byte[] b) {
return getDefaultByteArrayComparator().compare(a, b) > 0 ? a : b;
} | @Test
public void testMax() {
byte[] array = new byte[] { 3, 4 };
Assert.assertArrayEquals(array, BytesUtil.max(array, array));
Assert.assertArrayEquals(array, BytesUtil.max(new byte[] { 1, 2 }, array));
} |
@SuppressWarnings("unchecked")
public V put(int key, V value) {
byte[] states = this.states;
int[] keys = this.keys;
int mask = keys.length - 1;
int i = key & mask;
while (states[i] > FREE) { // states[i] == FULL
if (keys[i] == key) {
V oldValue =... | @Test
public void testPut() {
removeOdd();
for (int i = 0; i < 45; i++)
map.put(i, Integer.valueOf(i));
assertEquals(45, map.size());
for (int i = 0; i < 45; i++)
assertEquals(Integer.valueOf(i), map.get(i));
} |
public static <T> NavigableSet<Point<T>> fastKNearestPoints(SortedSet<Point<T>> points, Instant time, int k) {
checkNotNull(points, "The input SortedSet of Points cannot be null");
checkNotNull(time, "The input time cannot be null");
checkArgument(k >= 0, "k (" + k + ") must be non-negative");
... | @Test
public void testFastKNearestPoints_7() {
NavigableSet<Point<String>> knn = fastKNearestPoints(points, EPOCH.plusSeconds(5), 0);
assertEquals(0, knn.size());
assertEquals(12, points.size());
} |
@Override
public void syncHoodieTable() {
switch (bqSyncClient.getTableType()) {
case COPY_ON_WRITE:
case MERGE_ON_READ:
syncTable(bqSyncClient);
break;
default:
throw new UnsupportedOperationException(bqSyncClient.getTableType() + " table type is not supported yet.");
... | @Test
void useBQManifestFile_existingNonPartitionedTable() {
properties.setProperty(BigQuerySyncConfig.BIGQUERY_SYNC_USE_BQ_MANIFEST_FILE.key(), "true");
when(mockBqSyncClient.getTableType()).thenReturn(HoodieTableType.COPY_ON_WRITE);
when(mockBqSyncClient.getBasePath()).thenReturn(TEST_TABLE_BASE_PATH);
... |
@Override
public boolean supports(Ref ref) {
Assert.notNull(ref, "Subject ref must not be null.");
GroupVersionKind groupVersionKind =
new GroupVersionKind(ref.getGroup(), ref.getVersion(), ref.getKind());
return GroupVersionKind.fromExtension(SinglePage.class).equals(groupVersio... | @Test
void supports() {
SinglePage singlePage = new SinglePage();
singlePage.setMetadata(new Metadata());
singlePage.getMetadata().setName("test");
boolean supports = singlePageCommentSubject.supports(Ref.of(singlePage));
assertThat(supports).isTrue();
FakeExtension ... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void testConstructor() {
try {
ConcurrentLongPairSet.newBuilder()
.expectedItems(0)
.build();
fail("should have thrown exception");
} catch (IllegalArgumentException e) {
// ok
}
try {
... |
public static Collection<ExecutionUnit> build(final ShardingSphereDatabase database, final SQLRewriteResult sqlRewriteResult, final SQLStatementContext sqlStatementContext) {
return sqlRewriteResult instanceof GenericSQLRewriteResult
? build(database, (GenericSQLRewriteResult) sqlRewriteResult, ... | @Test
void assertBuildRouteSQLRewriteResult() {
RouteUnit routeUnit1 = new RouteUnit(new RouteMapper("logicName1", "actualName1"), Collections.singletonList(new RouteMapper("logicName1", "actualName1")));
SQLRewriteUnit sqlRewriteUnit1 = new SQLRewriteUnit("sql1", Collections.singletonList("paramete... |
void onAddSendDestination(final long registrationId, final String destinationChannel, final long correlationId)
{
final ChannelUri channelUri = ChannelUri.parse(destinationChannel);
validateDestinationUri(channelUri, destinationChannel);
validateSendDestinationUri(channelUri, destinationChan... | @Test
void shouldThrowExceptionWhenSendDestinationHasResponseCorrelationIdSet()
{
final Exception exception = assertThrowsExactly(InvalidChannelException.class,
() -> driverConductor.onAddSendDestination(4, "aeron:udp?response-correlation-id=1234", 8)
);
assertThat(exception... |
@Override
public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) {
traceIfNecessary(grpcRequest, true);
String type = grpcRequest.getMetadata().getType();
long startTime = System.nanoTime();
//server is on starting.
if (!Applicati... | @Test
void testHandleRequestError() {
ApplicationUtils.setStarted(true);
Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler);
Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true);
RequestMeta metadata = new... |
public static long calculateTotalProcessMemoryFromComponents(Configuration config) {
Preconditions.checkArgument(config.contains(TaskManagerOptions.JVM_METASPACE));
Preconditions.checkArgument(config.contains(TaskManagerOptions.JVM_OVERHEAD_MAX));
Preconditions.checkArgument(config.contains(Task... | @Test
void testCalculateTotalProcessMemoryWithMissingFactors() {
Configuration config = new Configuration();
config.set(TaskManagerOptions.FRAMEWORK_HEAP_MEMORY, new MemorySize(1));
config.set(TaskManagerOptions.FRAMEWORK_OFF_HEAP_MEMORY, new MemorySize(3));
config.set(TaskManagerOp... |
public static void verifyIncrementPubContent(String content) {
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("publish/delete content can not be null");
}
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);... | @Test
void testVerifyIncrementPubContentFail3() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
String content = "";
ContentUtils.verifyIncrementPubContent(content);
});
assertTrue(exception.getMessage().contains("publish/delete content ca... |
@Override
public AppToken createAppToken(long appId, String privateKey) {
Algorithm algorithm = readApplicationPrivateKey(appId, privateKey);
LocalDateTime now = LocalDateTime.now(clock);
// Expiration period is configurable and could be greater if needed.
// See https://developer.github.com/apps/buil... | @Test
public void createAppToken_fails_with_IAE_if_privateKey_content_is_garbage() {
String garbage = randomAlphanumeric(555);
GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(garbage);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), gi... |
@Override
public Serde<GenericRow> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
final Optiona... | @Test
public void shouldWrapInLoggingSerde() {
// When:
factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
verify(innerFactory).wrapInLoggingSerde(any(), eq(LOGGER_PREFIX), eq(processingLogCxt), eq(Optional.of(queryId)));
} |
@Override
@MethodNotAvailable
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor,
Object... arguments) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testInvokeAll() {
Set<Integer> keys = new HashSet<>(asList(23, 65, 88));
adapter.invokeAll(keys, new ICacheReplaceEntryProcessor(), "value", "newValue");
} |
public static PropertyKey fromString(String input) {
// First try to parse it as default key
PropertyKey key = DEFAULT_KEYS_MAP.get(input);
if (key != null) {
return key;
}
// Try to match input with alias
key = DEFAULT_ALIAS_MAP.get(input);
if (key != null) {
return key;
}
... | @Test
public void fromString() throws Exception {
assertEquals(PropertyKey.VERSION, PropertyKey.fromString(PropertyKey.VERSION.toString()));
PropertyKey.fromString(PropertyKey.VERSION.toString());
assertEquals(mTestProperty, PropertyKey.fromString("alluxio.test.property.alias1"));
assertEquals(mTestPr... |
@VisibleForTesting
AdminUserDO validateUserExists(Long id) {
if (id == null) {
return null;
}
AdminUserDO user = userMapper.selectById(id);
if (user == null) {
throw exception(USER_NOT_EXISTS);
}
return user;
} | @Test
public void testValidateUserExists_notExists() {
assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS);
} |
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 getTypeNameInputPositiveOutputNotNull37() {
// Arrange
final int type = 1;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Start_v3", actual);
} |
@Override
public boolean canPass(Node node, int acquireCount) {
return canPass(node, acquireCount, false);
} | @Test
public void testThrottlingControllerNormal() throws InterruptedException {
ThrottlingController paceController = new ThrottlingController(500, 10d);
Node node = mock(Node.class);
long start = TimeUtil.currentTimeMillis();
for (int i = 0; i < 6; i++) {
assertTrue(pa... |
public static Result label(long durationInMillis) {
double nbSeconds = durationInMillis / 1000.0;
double nbMinutes = nbSeconds / 60;
double nbHours = nbMinutes / 60;
double nbDays = nbHours / 24;
double nbYears = nbDays / 365;
return getMessage(nbSeconds, nbMinutes, nbHours, nbDays, nbYears);
... | @Test
public void age_in_hour() {
DurationLabel.Result result = DurationLabel.label(now() - ago(HOUR));
assertThat(result.key()).isEqualTo("duration.hour");
assertThat(result.value()).isNull();
} |
public AdminStatisticsJobRequestHandler(RepositoryService repositories, AdminStatisticsService service) {
this.repositories = repositories;
this.service = service;
} | @Test
public void testAdminStatisticsJobRequestHandler() throws Exception {
var expectedStatistics = mockAdminStatistics();
var request = new AdminStatisticsJobRequest(2023, 11);
handler.run(request);
Mockito.verify(service).saveAdminStatistics(expectedStatistics);
} |
@Override
protected Result check() throws IOException {
final boolean isHealthy = tcpCheck(host, port);
if (isHealthy) {
LOGGER.debug("Health check against url={}:{} successful", host, port);
return Result.healthy();
}
LOGGER.debug("Health check against url=... | @Test
void tcpHealthCheckShouldReturnUnhealthyIfCannotConnect() throws IOException {
serverSocket.close();
assertThatThrownBy(() -> tcpHealthCheck.check()).isInstanceOfAny(ConnectException.class, SocketTimeoutException.class);
} |
public boolean unreference() {
int newVal = status.decrementAndGet();
Preconditions.checkState(newVal != 0xffffffff,
"called unreference when the reference count was already at 0.");
return newVal == STATUS_CLOSED_MASK;
} | @Test
public void testUnreference() throws ClosedChannelException {
CloseableReferenceCount clr = new CloseableReferenceCount();
clr.reference();
clr.reference();
assertFalse("New reference count should not equal STATUS_CLOSED_MASK",
clr.unreference());
assertEquals("Incorrect reference co... |
public boolean matches(Evidence evidence) {
return sourceMatches(evidence)
&& confidenceMatches(evidence)
&& name.equalsIgnoreCase(evidence.getName())
&& valueMatches(evidence);
} | @Test
public void testRegExWildcardSourceMatching() throws Exception {
final EvidenceMatcher regexMediumWildcardSourceMatcher = new EvidenceMatcher(null, "name", "^.*v[al]{2,2}ue[a-z ]+$", true, Confidence.MEDIUM);
assertFalse("regex medium wildcard source matcher should not match REGEX_EVIDENCE_HIG... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testOffsetAssignmentAfterUpConversionV0ToV1NonCompressed() {
MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V0, RecordBatch.NO_TIMESTAMP, Compression.NONE);
checkOffsets(records, 0);
long offset = 1234567;
LogValidator.ValidationResult validatedResu... |
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 shouldThrowOnPossibleSyntheticKeyColumnIfNotPossible() {
// Given:
analyzer = new ColumnReferenceValidator(sourceSchemas, false);
// When:
final Exception e = assertThrows(
UnknownColumnException.class,
() -> analyzer.analyzeExpression(POSSIBLE_SYNTHETIC_KEY, "SELECT... |
@PutMapping
@Secured(resource = AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE)
public Object updateUser(@RequestParam String username, @RequestParam String newPassword,
HttpServletResponse response, HttpServletRequest request) throws IOException {
// admin or same use... | @Test
void testUpdateUser2() {
when(authConfigs.isAuthEnabled()).thenReturn(false);
when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(null);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
MockHttpServletResponse mockHttpServl... |
@Override
public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception {
final List<String> loggerNames = getLoggerNames(parameters);
final Level loggerLevel = getLoggerLevel(parameters);
final Duration duration = getDuration(parameters);
for (Strin... | @Test
void configuresSpecificLevelForALogger() throws Exception {
// given
Level twoEffectiveBefore = logger2.getEffectiveLevel();
Map<String, List<String>> parameters = Map.of(
"logger", List.of("logger.one"),
"level", List.of("debug"));
// when
... |
public static <T> T loadObject(String content, Class<T> type) {
return new Yaml(new YamlParserConstructor(), new CustomRepresenter()).loadAs(content, type);
} | @Test
void testLoadObject() {
ConfigMetadata configMetadata = YamlParserUtil.loadObject(CONFIG_METADATA_STRING, ConfigMetadata.class);
assertNotNull(configMetadata);
List<ConfigMetadata.ConfigExportItem> metadataList = configMetadata.getMetadata();
assertNotNull(metadataList... |
@Override
public void apply(IntentOperationContext<DomainIntent> context) {
Optional<IntentData> toUninstall = context.toUninstall();
Optional<IntentData> toInstall = context.toInstall();
List<DomainIntent> uninstallIntents = context.intentsToUninstall();
List<DomainIntent> installI... | @Test
public void testInstall() {
List<Intent> intentsToUninstall = Lists.newArrayList();
List<Intent> intentsToInstall = createDomainIntents();
IntentData toUninstall = null;
IntentData toInstall = new IntentData(createP2PIntent(),
Inten... |
public static boolean check(@NonNull Fragment fragment, int requestCode) {
final String[] permissions = getPermissionsStrings(requestCode);
if (EasyPermissions.hasPermissions(fragment.requireContext(), permissions)) {
return true;
} else {
// Do not have permissions, request them now
EasyP... | @Test
@Config(sdk = Build.VERSION_CODES.KITKAT)
public void testCheckAlreadyHasPermissionsBeforeM() {
try (var scenario = ActivityScenario.launch(TestFragmentActivity.class)) {
scenario.onActivity(
activity -> {
Assert.assertTrue(
PermissionRequestHelper.check(
... |
public void isIn(@Nullable Iterable<?> iterable) {
checkNotNull(iterable);
if (!contains(iterable, actual)) {
failWithActual("expected any of", iterable);
}
} | @Test
public void isInNullInListWithNull() {
assertThat((String) null).isIn(oneShotIterable("a", "b", (String) null));
} |
@Override
public Object deserialize(Writable writable) {
return ((Container<?>) writable).get();
} | @Test
public void testDeserialize() {
HiveIcebergSerDe serDe = new HiveIcebergSerDe();
Record record = RandomGenericData.generate(schema, 1, 0).get(0);
Container<Record> container = new Container<>();
container.set(record);
Assert.assertEquals(record, serDe.deserialize(container));
} |
@SneakyThrows
@Override
public Integer call() throws Exception {
super.call();
PicocliRunner.call(App.class, "namespace", "files", "--help");
return 0;
} | @Test
void runWithNoParam() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) {
String[] args = {};
Integer call = PicocliRunner... |
public static boolean isNodeAttributesEquals(
Set<NodeAttribute> leftNodeAttributes,
Set<NodeAttribute> rightNodeAttributes) {
if (leftNodeAttributes == null && rightNodeAttributes == null) {
return true;
} else if (leftNodeAttributes == null || rightNodeAttributes == null
|| leftNodeA... | @Test
void testIsNodeAttributesEquals() {
NodeAttribute nodeAttributeCK1V1 = NodeAttribute
.newInstance(NodeAttribute.PREFIX_CENTRALIZED, "K1",
NodeAttributeType.STRING, "V1");
NodeAttribute nodeAttributeCK1V1Copy = NodeAttribute
.newInstance(NodeAttribute.PREFIX_CENTRALIZED, "K1",... |
public void isNotNull() {
standardIsNotEqualTo(null);
} | @Test
public void isNotNullWhenSubjectForbidsIsEqualToFail() {
expectFailure.whenTesting().about(objectsForbiddingEqualityCheck()).that(null).isNotNull();
} |
@SqlNullable
@Description("Returns TRUE if and only if the line is closed and simple")
@ScalarFunction("ST_IsRing")
@SqlType(BOOLEAN)
public static Boolean stIsRing(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
OGCGeometry geometry = EsriGeometrySerde.deserialize(input);
validateType("... | @Test
public void testSTIsRing()
{
assertFunction("ST_IsRing(ST_GeometryFromText('LINESTRING (8 4, 4 8)'))", BOOLEAN, false);
assertFunction("ST_IsRing(ST_GeometryFromText('LINESTRING (0 0, 1 1, 0 2, 0 0)'))", BOOLEAN, true);
assertInvalidFunction("ST_IsRing(ST_GeometryFromText('POLYGON ... |
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("SEMAPHORE_GIT_SHA");
return new CiConfigurationImpl(revision, getName());
} | @Test
public void loadConfiguration() {
setEnvVariable("SEMAPHORE", "true");
setEnvVariable("SEMAPHORE_PROJECT_ID", "d782a107-aaf9-494d-8153-206b1a6bc8e9");
setEnvVariable("SEMAPHORE_GIT_SHA", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
} |
public static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName) {
if (values == null) {
// pass
return;
}
for (String value : values) {
Preconditions.checkNotNull(
value, "Property '" + propertyName + "' cannot contain null en... | @Test
public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyKeyFail() {
try {
Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap(" ", "val1"), "test");
Assert.fail();
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Property 'test' cannot contain empty stri... |
@Override
public Map<String, String[]> getParameterMap() {
return stringMap;
} | @Test
void testGetParameterMap() {
Map<String, String[]> parameterMap = reuseHttpServletRequest.getParameterMap();
assertNotNull(parameterMap);
assertEquals(2, parameterMap.size());
assertEquals("test", parameterMap.get("name")[0]);
assertEquals("123", parameterMap.get("value... |
public int read()
{
int b = -1;
if (position < length)
{
b = buffer.getByte(offset + position) & 0xFF;
++position;
}
return b;
} | @Test
void shouldReturnMinusOneOnEndOfStream()
{
final byte[] data = { 1, 2 };
final DirectBuffer buffer = new UnsafeBuffer(data);
final DirectBufferInputStream inputStream = new DirectBufferInputStream(buffer);
assertEquals(inputStream.read(), 1);
assertEquals(inputStr... |
public static InternalLogger getInstance(Class<?> clazz) {
return getInstance(clazz.getName());
} | @Test
public void testWarn() {
final InternalLogger logger = InternalLoggerFactory.getInstance("mock");
logger.warn("a");
verify(mockLogger).warn("a");
} |
@Override
public void run() {
JobRunrMetadata metadata = storageProvider.getMetadata("database_version", "cluster");
if (metadata != null && "6.0.0".equals(metadata.getValue())) return;
migrateScheduledJobsIfNecessary();
storageProvider.saveMetadata(new JobRunrMetadata("database_ve... | @Test
void doesMigrationsOfAllScheduledJobsIfStorageProviderIsAnSqlStorageProvider() {
doReturn(PostgresStorageProvider.class).when(storageProviderInfo).getImplementationClass();
when(storageProvider.getScheduledJobs(any(), any()))
.thenAnswer(i -> aLotOfScheduledJobs(i.getArgument(... |
public void writePDF( OutputStream output ) throws IOException
{
output.write(String.valueOf(value).getBytes(StandardCharsets.ISO_8859_1));
} | @Test
void testWritePDF()
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int index = 0;
try
{
for (int i = -1000; i < 3000; i += 200)
{
index = i;
COSInteger cosInt = COSInteger.get(i);
cosI... |
@Override
public void judgeContinueToExecute(final SQLStatement statement) throws SQLException {
ShardingSpherePreconditions.checkState(statement instanceof CommitStatement || statement instanceof RollbackStatement,
() -> new SQLFeatureNotSupportedException("Current transaction is aborted, c... | @Test
void assertJudgeContinueToExecuteWithRollbackStatement() {
assertDoesNotThrow(() -> allowedSQLStatementHandler.judgeContinueToExecute(mock(RollbackStatement.class)));
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(log.isWarnEnabled()) {
log.warn(String.format("Disable checksum verification for %s", file));
// Do not set che... | @Test(expected = NotfoundException.class)
public void testReadNotFound() throws Exception {
final TransferStatus status = new TransferStatus();
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
... |
private ByteBuf buffer(int i) {
ByteBuf b = buffers[i];
return b instanceof Component ? ((Component) b).buf : b;
} | @Test
public void testGatheringWritesHeap() throws Exception {
testGatheringWrites(buffer(), buffer());
} |
@Override
public DictDataDO getDictData(Long id) {
return dictDataMapper.selectById(id);
} | @Test
public void testGetDictData() {
// mock 数据
DictDataDO dbDictData = randomDictDataDO();
dictDataMapper.insert(dbDictData);
// 准备参数
Long id = dbDictData.getId();
// 调用
DictDataDO dictData = dictDataService.getDictData(id);
// 断言
assertPojo... |
AwsCredentials credentials() {
if (!StringUtil.isNullOrEmptyAfterTrim(awsConfig.getAccessKey())) {
return AwsCredentials.builder()
.setAccessKey(awsConfig.getAccessKey())
.setSecretKey(awsConfig.getSecretKey())
.build();
}
if (!StringUt... | @Test(expected = InvalidConfigurationException.class)
public void credentialsEc2Exception() {
// given
String iamRole = "sample-iam-role";
AwsConfig awsConfig = AwsConfig.builder()
.setIamRole(iamRole)
.build();
given(awsMetadataApi.credentialsEc2(iamRole)).wi... |
@Udf
public String lpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnNullForNullInputBytes() {
final ByteBuffer result = udf.lpad(null, 4, BYTES_45);
assertThat(result, is(nullValue()));
} |
public static String decodeReferenceToken(final String s) {
String decoded = s;
List<String> reverseOrderedKeys = new ArrayList<String>(SUBSTITUTIONS.keySet());
Collections.reverse(reverseOrderedKeys);
for (String key : reverseOrderedKeys) {
decoded = decoded.replace(SUBSTIT... | @Test
public void testDecodeReferenceToken() {
assertThat(JsonPointerUtils.decodeReferenceToken("com~1vsv~2~3~3~3~4"), is("com/vsv#...?"));
assertThat(JsonPointerUtils.decodeReferenceToken("~01~02~001~03~04"), is("~1~2~01~3~4"));
} |
static List<byte[]> readCertificates(Path path) throws CertificateException {
final byte[] bytes;
try {
bytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new CertificateException("Couldn't read certificates from file: " + path, e);
}
final... | @Test
public void readCertificatesHandlesSingleCertificate() throws Exception {
final URL url = Resources.getResource("org/graylog2/shared/security/tls/single.crt");
final List<byte[]> certificates = PemReader.readCertificates(Paths.get(url.toURI()));
assertThat(certificates).hasSize(1);
... |
@Override
protected Set<StepField> getUsedFields( RestMeta stepMeta ) {
Set<StepField> usedFields = new HashSet<>();
// add url field
if ( stepMeta.isUrlInField() && StringUtils.isNotEmpty( stepMeta.getUrlField() ) ) {
usedFields.addAll( createStepFields( stepMeta.getUrlField(), getInputs() ) );
... | @Test
public void testGetUsedFields_methodInFieldNoFieldSet() throws Exception {
Set<StepField> fields = new HashSet<>();
when( meta.isDynamicMethod() ).thenReturn( true );
when( meta.getMethodFieldName() ).thenReturn( null );
Set<StepField> usedFields = analyzer.getUsedFields( meta );
verify( a... |
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI.
public long parse(final String text) {
final String date;
final String time;
final String timezone;
if (text.contains("T")) {
date = text.substring(0, text.indexOf('T'));
final String withTimezone = text.substring(text.i... | @Test
public void shouldParseFullDateTime() {
// When:
assertThat(parser.parse("2020-12-02T13:59:58.123"), is(fullParse("2020-12-02T13:59:58.123+0000")));
assertThat(parser.parse("2020-12-02T13:59:58.123Z"), is(fullParse("2020-12-02T13:59:58.123+0000")));
} |
@Override
public boolean getTcpNoDelay() {
return clientConfig.getPropertyAsBoolean(TCP_NO_DELAY, false);
} | @Test
void testGetTcpNoDelay() {
assertFalse(connectionPoolConfig.getTcpNoDelay());
} |
@GetMapping("/enum")
public ShenyuAdminResult queryEnums() {
return ShenyuAdminResult.success(enumService.list());
} | @Test
public void testQueryEnums() throws Exception {
final String queryEnumsUri = "/platform/enum";
this.mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, queryEnumsUri))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code", is(CommonErrorCode.SUCCE... |
synchronized void unlock(final TaskId taskId) {
final Thread lockOwner = lockedTasksToOwner.get(taskId);
if (lockOwner != null && lockOwner.equals(Thread.currentThread())) {
lockedTasksToOwner.remove(taskId);
log.debug("{} Released state dir lock for task {}", logPrefix(), taskId... | @Test
public void shouldBeAbleToUnlockEvenWithoutLocking() {
final TaskId taskId = new TaskId(0, 0);
directory.unlock(taskId);
} |
public boolean add(final Integer value)
{
return add(value.intValue());
} | @Test
void forEachShouldInvokeConsumerWithTheMissingValueAtTheIfOneWasAddedToTheSet()
{
@SuppressWarnings("unchecked") final Consumer<Integer> consumer = mock(Consumer.class);
testSet.add(MISSING_VALUE);
testSet.add(15);
testSet.add(MISSING_VALUE);
testSet.forEach(consu... |
@Override
public void encode(final ChannelHandlerContext context, final DatabasePacket message, final ByteBuf out) {
boolean isIdentifierPacket = message instanceof PostgreSQLIdentifierPacket;
if (isIdentifierPacket) {
prepareMessageHeader(out, ((PostgreSQLIdentifierPacket) message).getI... | @Test
void assertEncodePostgreSQLPacket() {
PostgreSQLPacket packet = mock(PostgreSQLPacket.class);
new PostgreSQLPacketCodecEngine().encode(context, packet, byteBuf);
verify(packet).write(any(PostgreSQLPacketPayload.class));
} |
@Override
public void setOriginalFile(Component file, OriginalFile originalFile) {
storeOriginalFileInCache(originalFiles, file, originalFile);
} | @Test
public void setOriginalFile_does_not_fail_if_same_original_file_is_added_multiple_times_for_the_same_component() {
underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE);
for (int i = 0; i < 1 + Math.abs(new Random().nextInt(10)); i++) {
underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE);... |
public String getString(String path) {
return ObjectConverter.convertObjectTo(get(path), String.class);
} | @Test
public void
can_parse_multiple_values() {
// Given
final JsonPath jsonPath = new JsonPath(JSON);
// When
final String category1 = jsonPath.getString("store.book.category[0]");
final String category2 = jsonPath.getString("store.book.category[1]");
// Then
... |
public Histogram histogram(String name) {
return histogram(MetricName.build(name));
} | @Test
public void accessingAHistogramRegistersAndReusesIt() throws Exception {
final Histogram histogram1 = registry.histogram(THING);
final Histogram histogram2 = registry.histogram(THING);
assertThat(histogram1)
.isSameAs(histogram2);
verify(listener).onHistogramA... |
@Override
public DataSourceProvenance getProvenance() {
return new DemoLabelDataSourceProvenance(this);
} | @Test
public void testNoisyInterlockingCrescents() {
// Check zero samples throws
assertThrows(PropertyException.class, () -> new NoisyInterlockingCrescentsDataSource(0, 1, 0.1));
// Check invalid variance throws
assertThrows(PropertyException.class, () -> new NoisyInterlockingCresce... |
public static String toIpAddress(SocketAddress address) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
return inetSocketAddress.getAddress().getHostAddress();
} | @Test
public void testToIpAddress() throws UnknownHostException {
assertThat(NetUtil.toIpAddress(ipv4)).isEqualTo(ipv4.getAddress().getHostAddress());
assertThat(NetUtil.toIpAddress(ipv6)).isEqualTo(ipv6.getAddress().getHostAddress());
} |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldNotAllowInsertOnMultipleKeySchemaDefinitionsWithDifferentOrder() throws Exception {
final String protoMultiSchema = "syntax = \"proto3\";\n"
+ "package io.proto;\n"
+ "\n"
+ "message SingleKey {\n"
+ " string k0 = 1;\n"
+ "}\n"
+ "message Mu... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
super.doFilter(request, response, chain);
return;
}
final HttpServletRequest httpRequest = (HttpServletRequest) reque... | @Test
public void testWithSessionCreated() throws IOException, ServletException {
final int sessionCount = SessionListener.getSessionCount();
final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
final Filter... |
public Labels withAdditionalLabels(Map<String, String> additionalLabels) {
if (additionalLabels == null || additionalLabels.isEmpty()) {
return this;
} else {
Map<String, String> newLabels = new HashMap<>(labels.size());
newLabels.putAll(labels);
newLabels... | @Test
public void testWithInvalidUserSuppliedLabels() {
Map<String, String> userLabelsWithStrimzi = new HashMap<>(3);
userLabelsWithStrimzi.put("key1", "value1");
userLabelsWithStrimzi.put("key2", "value2");
userLabelsWithStrimzi.put(Labels.STRIMZI_DOMAIN + "something", "value3");
... |
public LionBundle stitch(String id) {
String source = base + SLASH + CONFIG_DIR + SLASH + id + SUFFIX;
// the following may throw IllegalArgumentException...
LionConfig cfg = new LionConfig().load(source);
LionBundle.Builder builder = new LionBundle.Builder(id);
int total = 0;
... | @Test
public void cardGame1English() {
title("cardGame1English");
// use default locale (en_US)
lion = testStitcher().stitch("CardGame1");
print(lion);
assertEquals("wrong key", "CardGame1", lion.id());
assertEquals("bad key count", 12, lion.size());
verifyIt... |
public FEELFnResult<Boolean> invoke(@ParameterName("string") String string, @ParameterName("match") String match) {
if ( string == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null"));
}
if ( match == null ) {
return... | @Test
void invokeEmptyString() {
FunctionTestUtil.assertResult(startsWithFunction.invoke("", ""), true);
FunctionTestUtil.assertResult(startsWithFunction.invoke("", "test"), false);
FunctionTestUtil.assertResult(startsWithFunction.invoke("test", ""), true);
} |
public static boolean isSupportPrometheus() {
return isClassPresent("io.micrometer.prometheus.PrometheusConfig")
&& isClassPresent("io.prometheus.client.exporter.BasicAuthHttpConnectionFactory")
&& isClassPresent("io.prometheus.client.exporter.HttpConnectionFactory")
... | @Test
void isSupportPrometheus() {
boolean supportPrometheus =
new DefaultApplicationDeployer(ApplicationModel.defaultModel()).isSupportPrometheus();
Assert.assertTrue(supportPrometheus, "DefaultApplicationDeployer.isSupportPrometheus() should return true");
} |
@Override
public double rand() {
return inverseTransformSampling();
} | @Test
public void testSd() {
System.out.println("sd");
FDistribution instance = new FDistribution(10, 20);
instance.rand();
assertEquals(0.6573422, instance.sd(), 1E-7);
} |
@Override
public ShardingSphereSchema swapToObject(final YamlShardingSphereSchema yamlConfig) {
return Optional.ofNullable(yamlConfig).map(this::swapSchema).orElseGet(() -> new ShardingSphereSchema(yamlConfig.getName()));
} | @Test
void assertSwapToShardingSphereSchema() {
YamlShardingSphereSchema yamlSchema = YamlEngine.unmarshal(readYAML(YAML), YamlShardingSphereSchema.class);
ShardingSphereSchema actualSchema = new YamlSchemaSwapper().swapToObject(yamlSchema);
assertThat(actualSchema.getAllTableNames(), is(Col... |
@Override
public boolean createTopic(
final String topic,
final int numPartitions,
final short replicationFactor,
final Map<String, ?> configs,
final CreateTopicsOptions createOptions
) {
final Optional<Long> retentionMs = KafkaTopicClient.getRetentionMs(configs);
if (isTopicE... | @Test
public void shouldCreateTopic() {
// When:
kafkaTopicClient.createTopic("someTopic", 1, (short) 2, configs);
// Then:
verify(adminClient).createTopics(
eq(ImmutableSet.of(newTopic("someTopic", 1, 2, configs))),
argThat(createOptions -> !createOptions.shouldValidateOnly())
);... |
public static String toString(String unicode) {
if (StrUtil.isBlank(unicode)) {
return unicode;
}
final int len = unicode.length();
StringBuilder sb = new StringBuilder(len);
int i;
int pos = 0;
while ((i = StrUtil.indexOfIgnoreCase(unicode, "\\u", pos)) != -1) {
sb.append(unicode, pos, i);//写入Unic... | @Test
public void convertTest2() {
String str = "aaaa\\u0026bbbb\\u0026cccc";
String unicode = UnicodeUtil.toString(str);
assertEquals("aaaa&bbbb&cccc", unicode);
} |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldBeAbleToExplicitlyLockAPipeline() throws Exception {
String pipelineXmlPartial =
("""
<pipeline name="pipeline" lockBehavior="%s">
<materials>
<hg url="/hgrepo"/>
</materi... |
public void store(String sourceAci, UUID messageGuid) {
try {
Objects.requireNonNull(sourceAci);
reportMessageDynamoDb.store(hash(messageGuid, sourceAci));
} catch (final Exception e) {
logger.warn("Failed to store hash", e);
}
} | @Test
void testStore() {
assertDoesNotThrow(() -> reportMessageManager.store(null, messageGuid));
verifyNoInteractions(reportMessageDynamoDb);
reportMessageManager.store(sourceAci.toString(), messageGuid);
verify(reportMessageDynamoDb).store(any());
doThrow(RuntimeException.class)
.whe... |
public static FieldScope allowingFields(int firstFieldNumber, int... rest) {
return FieldScopeImpl.createAllowingFields(asList(firstFieldNumber, rest));
} | @Test
public void testIgnoringTopLevelAnyField_fieldScopes_allowingFields() {
String typeUrl =
isProto3()
? "type.googleapis.com/com.google.common.truth.extensions.proto.SubTestMessage3"
: "type.googleapis.com/com.google.common.truth.extensions.proto.SubTestMessage2";
Message m... |
public static int createEdgeKey(int edgeId, boolean reverse) {
// edge state in storage direction -> edge key is even
// edge state against storage direction -> edge key is odd
return (edgeId << 1) + (reverse ? 1 : 0);
} | @Test
public void testEdgeStuff() {
assertEquals(2, GHUtility.createEdgeKey(1, false));
assertEquals(3, GHUtility.createEdgeKey(1, true));
} |
static void populateGeneratedResources(GeneratedResources toPopulate, EfestoCompilationOutput compilationOutput) {
toPopulate.add(getGeneratedResource(compilationOutput));
if (compilationOutput instanceof EfestoClassesContainer) {
toPopulate.addAll(getGeneratedResources((EfestoClassesContain... | @Test
void populateGeneratedResources() {
GeneratedResources toPopulate = new GeneratedResources();
assertThat(toPopulate).isEmpty();
CompilationManagerUtils.populateGeneratedResources(toPopulate, finalOutput);
int expectedResources = 4; // 1 final resource + 3 intermediate resources... |
@Override
protected Map<String, ConfigValue> validateSourceConnectorConfig(SourceConnector connector, ConfigDef configDef, Map<String, String> config) {
Map<String, ConfigValue> result = super.validateSourceConnectorConfig(connector, configDef, config);
validateSourceConnectorExactlyOnceSupport(conf... | @Test
public void testExactlyOnceSourceSupportValidationOnUnknownConnector() {
herder = exactlyOnceHerder();
Map<String, String> config = new HashMap<>();
config.put(SourceConnectorConfig.EXACTLY_ONCE_SUPPORT_CONFIG, REQUIRED.toString());
SourceConnector connectorMock = mock(SourceC... |
public static Map<AbilityKey, Boolean> getStaticAbilities() {
return INSTANCE.getSupportedAbilities();
} | @Test
void testGetStaticAbilities() {
// TODO add the cluster client abilities.
assertTrue(ClusterClientAbilities.getStaticAbilities().isEmpty());
} |
public Command create(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext context) {
return create(statement, context.getServiceContext(), context);
} | @Test
public void shouldValidateTerminateCluster() {
// Given:
configuredStatement = configuredStatement(
TerminateCluster.TERMINATE_CLUSTER_STATEMENT_TEXT,
terminateQuery
);
// When:
final Command command = commandFactory.create(configuredStatement, executionContext);
// The... |
public Set<GsonUser> getDirectGroupMembers(String gitlabUrl, String token, String groupId) {
return getMembers(gitlabUrl, token, format(GITLAB_GROUPS_MEMBERS_ENDPOINT, groupId));
} | @Test
public void getDirectGroupMembers_whenCallIsSuccessful_deserializesAndReturnsCorrectlyGroupMembers() throws IOException {
ArgumentCaptor<Function<String, List<GsonUser>>> deserializerCaptor = ArgumentCaptor.forClass(Function.class);
String token = "token-toto";
GitlabToken gitlabToken = new GitlabT... |
private ExitStatus run() {
try {
init();
return new Processor().processNamespace().getExitStatus();
} catch (IllegalArgumentException e) {
System.out.println(e + ". Exiting ...");
return ExitStatus.ILLEGAL_ARGUMENTS;
} catch (IOException e) {
System.out.println(e + ". Exiting... | @Test(timeout=100000)
public void testBalancerMaxIterationTimeNotAffectMover() throws Exception {
long blockSize = 10*1024*1024;
final Configuration conf = new HdfsConfiguration();
initConf(conf);
conf.setInt(DFSConfigKeys.DFS_MOVER_MOVERTHREADS_KEY, 1);
conf.setInt(
DFSConfigKeys.DFS_DATA... |
@ExecuteOn(TaskExecutors.IO)
@Delete(uri = "{namespace}/files")
@Operation(tags = {"Files"}, summary = "Delete a file or directory")
public void delete(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The internal storage uri of the file... | @Test
void delete() throws IOException {
storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folder/file.txt")), new ByteArrayInputStream("Hello".getBytes()));
client.toBlocking().exchange(HttpRequest.DELETE("/api/v1/namespaces/" + NAMESPACE + "/files?path=/folder/file.txt", nu... |
@Override
public String getName() {
return this.name;
} | @Test
public void shouldReturnTheCorrectName() {
assertThat(bulkhead.getName()).isEqualTo("test");
} |
@Override
public boolean offset(final Path file) {
return false;
} | @Test
public void testOffsetSupport() {
assertFalse(new SpectraReadFeature(session).offset(null));
} |
@Udf
public String concatWS(
@UdfParameter(description = "Separator string and values to join") final String... inputs) {
if (inputs == null || inputs.length < 2) {
throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments.");
}
final String separator = inputs[0... | @Test
public void shouldSkipAnyNullInputs() {
assertThat(udf.concatWS("SEP", "foo", null, "bar"), is("fooSEPbar"));
assertThat(udf.concatWS(ByteBuffer.wrap(new byte[] {1}), ByteBuffer.wrap(new byte[] {2}), null, ByteBuffer.wrap(new byte[] {3})),
is(ByteBuffer.wrap(new byte[] {2, 1, 3})));
} |
public boolean test(final IndexRange indexRange,
final Set<Stream> validStreams) {
// If index range is incomplete, check the prefix against the valid index sets.
if (indexRange.streamIds() == null) {
return validStreams.stream()
.map(Stream::getIn... | @Test
public void closedIndexRangeShouldNotMatchIfNotContainingAnyStreamId() {
when(indexRange.streamIds()).thenReturn(Collections.emptyList());
when(stream1.getId()).thenReturn("stream1");
when(stream2.getId()).thenReturn("stream2");
assertThat(toTest.test(indexRange, Set.of(stream... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.