focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public final BarcodeParameters getParams() {
return params;
} | @Test
final void testGetParams() throws IOException {
try (BarcodeDataFormat instance = new BarcodeDataFormat()) {
BarcodeParameters result = instance.getParams();
assertNotNull(result);
}
} |
@VisibleForTesting
Set<PartitionFieldNode> getRoots() {
return roots;
} | @Test
public void testProjectionCompaction() throws MetaException {
PersistenceManager mockPm = Mockito.mock(PersistenceManager.class);
List<String> projectionFields = new ArrayList<>(2);
projectionFields.add("sd.location");
projectionFields.add("sd.parameters");
projectionFields.add("createTime")... |
public abstract int status(HttpServletResponse response); | @Test void servlet25_status_cached_laterThrows() {
HttpServletResponseImpl response = new HttpServletResponseImpl();
servlet25.status(response);
response.shouldThrow = true;
assertThat(servlet25.status(response))
.isEqualTo(0);
} |
@Override
public List<String> listDbNames() {
return ImmutableList.<String>builder()
.addAll(this.normal.listDbNames())
.addAll(this.informationSchema.listDbNames())
.build();
} | @Test
void testListDbNames(@Mocked ConnectorMetadata connectorMetadata) {
new Expectations() {
{
connectorMetadata.listDbNames();
result = ImmutableList.of("test_db1", "test_db2");
times = 1;
}
};
CatalogConnectorMetada... |
String replaceMatchesWithSpace(String name) {
return replaceMatchWith(name, " ");
} | @Test
void replaceMatchWithSpace() {
assertThat(argumentPattern.replaceMatchesWithSpace("4"), is(equalTo(" ")));
} |
@Override
public void warn(final Host bookmark, final String title, final String reason,
final String defaultButton, final String cancelButton, final String preference) throws ConnectionCanceledException {
console.printf("%n%s", reason);
if(!prompt.prompt(String.format("%s (y) o... | @Test(expected = LoginCanceledException.class)
public void testWarn() throws Exception {
new TerminalLoginCallback(new TerminalPromptReader() {
@Override
public boolean prompt(final String message) {
return false;
}
}).warn(new Host(new TestProtoco... |
public static <T> T nullIsIllegal(T item, String message) {
if (item == null) {
log.error(message);
throw new IllegalArgumentException(message);
}
return item;
} | @Test
public void testNullIsIllegal() {
String input = "Foo";
String output = Tools.nullIsIllegal(input, "Not found!");
assertEquals(input, output);
assertSame(input, output);
} |
@Override
public Iterator<Map.Entry<String, Object>> getIterator() {
return variables.getIterator();
} | @Test
public void testGetIterator() {
assertThat(iteratorToMap(unmodifiables.getIterator()), CoreMatchers.is(iteratorToMap(vars.getIterator())));
} |
public int getAppTimeoutsFailedRetrieved() {
return numGetAppTimeoutsFailedRetrieved.value();
} | @Test
public void testGetAppTimeoutsRetrievedFailed() {
long totalBadBefore = metrics.getAppTimeoutsFailedRetrieved();
badSubCluster.getAppTimeoutsFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getAppTimeoutsFailedRetrieved());
} |
@Override
public void updateProject(GoViewProjectUpdateReqVO updateReqVO) {
// 校验存在
validateProjectExists(updateReqVO.getId());
// 更新
GoViewProjectDO updateObj = GoViewProjectConvert.INSTANCE.convert(updateReqVO);
goViewProjectMapper.updateById(updateObj);
} | @Test
public void testUpdateProject_success() {
// mock 数据
GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class);
goViewProjectMapper.insert(dbGoViewProject);// @Sql: 先插入出一条存在的数据
// 准备参数
GoViewProjectUpdateReqVO reqVO = randomPojo(GoViewProjectUpdateReqVO.class,... |
public String getPrivateKeyAsHex() {
return ByteUtils.formatHex(getPrivKeyBytes());
} | @Test
public void testGetPrivateKeyAsHex() {
ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); // An example private key.
assertEquals("000000000000000000000000000000000000000000000000000000000000000a", key.getPrivateKeyAsHex());
} |
public void setScheduledTaskQueueCapacity(int scheduledTaskQueueCapacity) {
this.scheduledTaskQueueCapacity = checkPositive(scheduledTaskQueueCapacity, "scheduledTaskQueueCapacity");
} | @Test
public void test_setScheduledTaskQueueCapacity_whenZero() {
ReactorBuilder builder = newBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.setScheduledTaskQueueCapacity(0));
} |
@Override
public void execute(final ConnectionSession connectionSession) {
VariableAssignSegment variableAssignSegment = setStatement.getVariableAssigns().iterator().next();
String variableName = variableAssignSegment.getVariable().getVariable().toLowerCase();
String assignValue = variableAs... | @Test
void assertExecute() {
VariableAssignSegment variableAssignSegment = new VariableAssignSegment();
VariableSegment variable = new VariableSegment(0, 0, "key");
variableAssignSegment.setVariable(variable);
variableAssignSegment.setAssignValue("value");
PostgreSQLSetStatem... |
public static void setFillInOutsideScopeExceptionStacktraces(boolean fillInStacktrace) {
if (lockdown) {
throw new IllegalStateException("Plugins can't be changed anymore");
}
fillInOutsideScopeExceptionStacktraces = fillInStacktrace;
} | @Test
public void trueStacktraceFill_shouldHaveStacktrace() {
AutoDisposePlugins.setFillInOutsideScopeExceptionStacktraces(true);
OutsideScopeException started = new OutsideScopeException("Lifecycle not started");
assertThat(started.getStackTrace()).isNotEmpty();
} |
@Override
@Nonnull
public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) {
throwRejectedExecutionExceptionIfShutdown();
ArrayList<Future<T>> result = new ArrayList<>();
for (Callable<T> task : tasks) {
try {
result.add(new Co... | @Test
void testRejectedInvokeAnyWithEmptyListAndTimeout() {
testRejectedExecutionException(
testInstance -> testInstance.invokeAll(Collections.emptyList(), 1L, TimeUnit.DAYS));
} |
public static List<Integer> getIntegerList(String property, JsonNode node) {
Preconditions.checkArgument(node.has(property), "Cannot parse missing list: %s", property);
return ImmutableList.<Integer>builder()
.addAll(new JsonIntegerArrayIterator(property, node))
.build();
} | @Test
public void getIntegerList() throws JsonProcessingException {
assertThatThrownBy(() -> JsonUtil.getIntegerList("items", JsonUtil.mapper().readTree("{}")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing list: items");
assertThatThrownBy(
() ->... |
public static void boundsCheck(int capacity, int index, int length) {
if (capacity < 0 || index < 0 || length < 0 || (index > (capacity - length))) {
throw new IndexOutOfBoundsException(String.format("index=%d, length=%d, capacity=%d", index, length, capacity));
}
} | @Test(expected = IndexOutOfBoundsException.class)
public void boundsCheck_whenIndexSmallerThanZero() {
ArrayUtils.boundsCheck(100, -1, 110);
} |
@Override
public void close() throws IOException {
if (closed) {
return;
}
super.close();
closed = true;
stream.close();
} | @Test
public void testMultipleClose() throws IOException {
GCSOutputStream stream =
new GCSOutputStream(storage, randomBlobId(), properties, MetricsContext.nullMetrics());
stream.close();
stream.close();
} |
public void notifyObservers() {
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
... | @Test
void testNotifyObservers() {
observable.addObserver(observer);
reset(observer);
observable.notifyObservers();
assertFalse(observable.hasChanged());
verify(observer, never()).update(observable);
observable.setChanged();
assertTrue(observable.hasChanged())... |
@Override
public void deleteGlobalProperty(String key, DbSession session) {
// do nothing
} | @Test
public void deleteGlobalProperty() {
underTest.deleteGlobalProperty(null, dbSession);
assertNoInteraction();
} |
@SuppressWarnings("squid:S1181")
// Yes we really do want to catch Throwable
@Override
public V apply(U input) {
int retryAttempts = 0;
while (true) {
try {
return baseFunction.apply(input);
} catch (Throwable t) {
if (!exceptionClass.i... | @Test(expected = RetryableException.class)
public void testNoRetries() {
new RetryingFunction<>(this::succeedAfterOneFailure, RetryableException.class, 0, 10).apply(null);
} |
@Override
public boolean supports(Job job) {
JobDetails jobDetails = job.getJobDetails();
return jobDetails.hasStaticFieldName();
} | @Test
void doesNotSupportJobIfJobIsNotAStaticMethodCall() {
Job job = anEnqueuedJob()
.withJobDetails(defaultJobDetails())
.build();
assertThat(backgroundStaticFieldJobWithoutIocRunner.supports(job)).isFalse();
} |
public RatingValue increment(Rating rating) {
if (value.compareTo(rating) > 0) {
value = rating;
}
this.set = true;
return this;
} | @Test
public void multiple_calls_to_increment_increments_by_the_value_of_the_arg() {
RatingValue target = new RatingValue()
.increment(new RatingValue().increment(B))
.increment(new RatingValue().increment(D));
verifySetValue(target, D);
} |
@Override
public Optional<String> getLocalHadoopConfigurationDirectory() {
final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR);
if (StringUtils.isNotBlank(hadoopConfDirEnv)) {
return Optional.of(hadoopConfDirEnv);
}
final String hadoopHomeEnv = S... | @Test
void testGetLocalHadoopConfigurationDirectoryFromHadoop2HomeEnv(@TempDir Path temporaryFolder)
throws Exception {
runTestWithEmptyEnv(
() -> {
final String hadoopHome = temporaryFolder.toAbsolutePath().toString();
Files.createDirector... |
public CompletableFuture<Acknowledge> triggerSavepoint(
AsynchronousJobOperationKey operationKey,
String targetDirectory,
SavepointFormatType formatType,
TriggerSavepointMode savepointMode,
Time timeout) {
return registerOperationIdempotently(
... | @Test
public void retryingCompletedOperationDoesNotMarkCacheEntryAsAccessed()
throws ExecutionException, InterruptedException {
handler.triggerSavepoint(
operationKey,
targetDirectory,
SavepointFormatType.CANONICAL,
... |
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> left,
final KTableHolder<K> right,
final StreamTableJoin<K> join,
final RuntimeBuildContext buildContext,
final JoinedFactory joinedFactory
) {
final Formats leftFormats = join.getInternalFormats();
final QueryConte... | @Test
public void shouldBuildJoinedCorrectly() {
// Given:
givenInnerJoin(L_KEY);
// When:
join.build(planBuilder, planInfo);
// Then:
verify(joinedFactory).create(keySerde, leftSerde, null, "jo-in");
} |
public static FileInputStream getFileInputStream(String fileName) throws IOException {
File sourceFile = getFile(fileName);
return new FileInputStream(sourceFile);
} | @Test
public void getFileInputStreamNotExisting() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> FileUtils.getFileInputStream(NOT_EXISTING_FILE));
} |
@Override
public boolean isWarProject() {
String packaging = project.getPackaging();
return "war".equals(packaging) || "gwt-app".equals(packaging);
} | @Test
public void testIsWarProject_warPackagingIsWar() {
when(mockMavenProject.getPackaging()).thenReturn("war");
assertThat(mavenProjectProperties.isWarProject()).isTrue();
} |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
// because it represents a loss, VaR is non-positive
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(-0.1), numOf(-0.2)));
assertFalse(criterion.betterThan(numOf(-0.1), numOf(0.0)));
} |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetObjectSchemaForObjectClassVariadic() {
assertThat(
UdfUtil.getVarArgsSchemaFromType(Object.class),
equalTo(ParamTypes.ANY)
);
} |
public Set<Long> calculateUsers(DelegateExecution execution, int level) {
Assert.isTrue(level > 0, "level 必须大于 0");
// 获得发起人
ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId());
Long startUserId = NumberUtils.parseLong(processInst... | @Test
public void testCalculateUsers_noParentDept() {
// 准备参数
DelegateExecution execution = mockDelegateExecution(1L);
// mock 方法(startUser)
AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L));
when(adminUserApi.getUser(eq(1L))).thenReturn(s... |
@Override
public void replay(
long offset,
long producerId,
short producerEpoch,
CoordinatorRecord record
) throws RuntimeException {
ApiMessageAndVersion key = record.key();
ApiMessageAndVersion value = record.value();
switch (key.version()) {
... | @Test
public void testReplayShareGroupMemberMetadata() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
... |
@Override
public boolean add(PipelineConfig pipelineConfig) {
verifyUniqueName(pipelineConfig);
PipelineConfigs part = this.getFirstEditablePartOrNull();
if (part == null)
throw bomb("No editable configuration sources");
return part.add(pipelineConfig);
} | @Test
public void shouldBombWhenAddPipelineAndNoEditablePartExists() {
PipelineConfig pipe1 = PipelineConfigMother.pipelineConfig("pipeline1");
BasicPipelineConfigs part1 = new BasicPipelineConfigs(pipe1);
MergePipelineConfigs group = new MergePipelineConfigs(
part1, new Bas... |
Number evaluateOutlierValue(final Number input) {
switch (outlierTreatmentMethod) {
case AS_IS:
KiePMMLLinearNorm[] limitLinearNorms;
if (input.doubleValue() < firstLinearNorm.getOrig()) {
limitLinearNorms = linearNorms.subList(0, 2).toArray(new Ki... | @Test
void evaluateOutlierValueAsIs() {
KiePMMLNormContinuous kiePMMLNormContinuous = getKiePMMLNormContinuous(null, OUTLIER_TREATMENT_METHOD.AS_IS,
null);
Number input = 23;
Number retrieved = kiePMMLNormContinuo... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchWithTopicId() {
buildFetcher();
TopicIdPartition tp = new TopicIdPartition(topicId, new TopicPartition(topicName, 0));
assignFromUser(singleton(tp.topicPartition()));
subscriptions.seek(tp.topicPartition(), 0);
assertEquals(1, sendFetches());
... |
public HttpHeaders preflightResponseHeaders() {
if (preflightHeaders.isEmpty()) {
return EmptyHttpHeaders.INSTANCE;
}
final HttpHeaders preflightHeaders = new DefaultHttpHeaders();
for (Entry<CharSequence, Callable<?>> entry : this.preflightHeaders.entrySet()) {
f... | @Test
public void preflightResponseHeadersSingleValue() {
final CorsConfig cors = forAnyOrigin().preflightResponseHeader("SingleValue", "value").build();
assertThat(cors.preflightResponseHeaders().get(of("SingleValue")), equalTo("value"));
} |
@Override
public AnalyticsPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
Capabilities capabilities = capabilities(descriptor.id());
PluggableInstanceSettings pluginSettingsAndView = getPluginSettingsAndView(descriptor, extension);
Image image = image(descriptor.id());
re... | @Test
public void shouldBuildPluginInfoWithImage() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
Image icon = new Image("content_type", "data", "hash");
when(extension.getIcon(descriptor.id())).thenReturn(icon);
AnalyticsPluginInfo pluginInfo... |
public ImmutableList<Replacement> format(
SnippetKind kind,
String source,
List<Range<Integer>> ranges,
int initialIndent,
boolean includeComments)
throws FormatterException {
RangeSet<Integer> rangeSet = TreeRangeSet.create();
for (Range<Integer> range : ranges) {
rang... | @Test
public void classMember() throws FormatterException {
String input = "void f() {\n}";
List<Replacement> replacements =
new SnippetFormatter()
.format(
SnippetKind.CLASS_BODY_DECLARATIONS,
input,
ImmutableList.of(Range.closedOpen(0, inpu... |
@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_authMethod() {
Mockito.when(config.isHeartMode()).thenReturn(true);
ClientDetailsEntity client = new ClientDetailsEntity();
Set<String> grantTypes = new LinkedHashSet<>();
grantTypes.add("implicit");
client.setGrantTypes(grantTy... |
@Override
public void revert(final Path file) throws BackgroundException {
try {
new NodesApi(session.getClient()).restoreNodes(
new RestoreDeletedNodesRequest()
.resolutionStrategy(RestoreDeletedNodesRequest.ResolutionStrategyEnum.OVERWRITE)
... | @Test
public void testRevert() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volu... |
public static boolean isKafkaInvokeBySermant(StackTraceElement[] stackTrace) {
return isInvokeBySermant(KAFKA_CONSUMER_CLASS_NAME, KAFKA_CONSUMER_CONTROLLER_CLASS_NAME, stackTrace);
} | @Test
public void testNotInvokeBySermantWithoutKafkaInvocation() {
StackTraceElement[] stackTrace = new StackTraceElement[3];
stackTrace[0] = new StackTraceElement("testClass0", "testMethod0", "testFileName0", 0);
stackTrace[1] = new StackTraceElement("testClass1", "testMethod1", "testFileNa... |
public void start(long period, TimeUnit unit) {
start(period, period, unit);
} | @Test
public void shouldStartWithSpecifiedInitialDelay() throws Exception {
reporterWithCustomMockExecutor.start(350, 100, TimeUnit.MILLISECONDS);
verify(mockExecutor).scheduleWithFixedDelay(
any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS)
);
} |
public FEELFnResult<TemporalAmount> invoke(@ParameterName( "from" ) String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
// try to parse as days/hours/minute/seconds
retu... | @Test
void invokeParamTemporalDuration() {
FunctionTestUtil.assertResult(
durationFunction.invoke(Duration.parse("P2DT3H28M15S")),
Duration.of(2, ChronoUnit.DAYS).plusHours(3).plusMinutes(28).plusSeconds(15));
} |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testPartitionAssignorExceptionOnRegularHeartbeat() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
... |
public static Duration parseDuration(String text) {
checkNotNull(text);
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while ... | @Test
void testParseDurationHours() {
assertThat(TimeUtils.parseDuration("987654h").toHours()).isEqualTo(987654);
assertThat(TimeUtils.parseDuration("987654hour").toHours()).isEqualTo(987654);
assertThat(TimeUtils.parseDuration("987654hours").toHours()).isEqualTo(987654);
assertThat(... |
@Override
public int getColumnType(final int columnIndex) throws SQLException {
return resultSetMetaData.getColumnType(columnIndex);
} | @Test
void assertGetColumnType() throws SQLException {
assertThat(queryResultMetaData.getColumnType(1), is(Types.INTEGER));
} |
@Override
public void validate(final Analysis analysis) {
try {
RULES.forEach(rule -> rule.check(analysis));
} catch (final KsqlException e) {
throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e);
}
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis... | @Test
public void shouldThrowWhenSelectClauseContainsDisallowedColumns() {
try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) {
//Given:
givenSelectClauseWithDisallowedColumnNames(columnExtractor);
// When:
final Exception e = assertThrows(
Ks... |
public static NestedField toIcebergNestedField(
PrestoIcebergNestedField nestedField,
Map<String, Integer> columnNameToIdMapping)
{
return NestedField.of(
nestedField.getId(),
nestedField.isOptional(),
nestedField.getName(),
... | @Test(dataProvider = "allTypes")
public void testToIcebergNestedField(int id, String name)
{
// Create a test TypeManager
TypeManager typeManager = createTestFunctionAndTypeManager();
// Create a mock Presto Nested Field
PrestoIcebergNestedField prestoNestedField = prestoIceberg... |
@Override
public PolicerId allocatePolicerId() {
// Init step
DriverHandler handler = handler();
// First step is to get MeterService
MeterService meterService = handler.get(MeterService.class);
// There was a problem, return none
if (meterService == null) {
... | @Test
public void testWrongDevice() {
// Get device handler
DriverHandler driverHandler = driverService.createHandler(fooDid);
// Get policer config behavior
PolicerConfigurable policerConfigurable = driverHandler.behaviour(PolicerConfigurable.class);
// Get policer id
... |
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir)))
.map(GitScmProvider::extractAbsoluteFilePaths)
.orElse(null);
} | @Test
public void branchChangedFiles_when_git_work_tree_is_above_project_basedir() throws IOException, GitAPIException {
git.branchCreate().setName("b1").call();
git.checkout().setName("b1").call();
Path projectDir = worktree.resolve("project");
Files.createDirectory(projectDir);
createAndCommitF... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertDouble() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("float8")
.dataType("float8")
.build();
Column column = Pos... |
@Override
public Reader getCharacterStream(final int columnIndex) throws SQLException {
// TODO To be supported: encrypt, mask, and so on
return mergeResultSet.getCharacterStream(columnIndex);
} | @Test
void assertGetCharacterStreamWithColumnIndex() throws SQLException {
Reader reader = mock(Reader.class);
when(mergeResultSet.getCharacterStream(1)).thenReturn(reader);
assertThat(shardingSphereResultSet.getCharacterStream(1), is(reader));
} |
public static String getPathOf( RepositoryElementMetaInterface object ) {
if ( object != null && !object.isDeleted() ) {
RepositoryDirectoryInterface directory = object.getRepositoryDirectory();
if ( directory != null ) {
String path = directory.getPath();
if ( path != null ) {
... | @Test
public void nullObject() {
assertNull( getPathOf( null ) );
} |
@Override
public HttpResponseOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final CreateFileUploadResponse uploadResponse = upload.start(file, status);
final String uploadUrl = uploadResponse.getUploadUrl();
... | @Test(expected = TransferStatusCanceledException.class)
public void testWriteCancel() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().r... |
@Override
public long getPeriodMillis() {
return STATIC;
} | @Test
public void testGetPeriodMillis() {
assertEquals(DiagnosticsPlugin.STATIC, plugin.getPeriodMillis());
} |
@Override
@Nullable
public byte[] readByteArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray);
} | @Test(expected = IncompatibleClassChangeError.class)
public void testReadFloatArray_IncompatibleClass() throws Exception {
reader.readByteArray("byte");
} |
public abstract void checkForCrash(String url); | @Test
public void testCheckForCrash() {
final CrashReporter reporter = CrashReporter.create();
assertNotNull(reporter);
reporter.checkForCrash("https://crash.cyberduck.io/report");
} |
@Override
public CompletableFuture<Void> deleteSubscriptionGroup(String address, DeleteSubscriptionGroupRequestHeader requestHeader,
long timeoutMillis) {
CompletableFuture<Void> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DE... | @Test
public void assertDeleteSubscriptionGroupWithSuccess() throws Exception {
setResponseSuccess(null);
DeleteSubscriptionGroupRequestHeader requestHeader = mock(DeleteSubscriptionGroupRequestHeader.class);
CompletableFuture<Void> actual = mqClientAdminImpl.deleteSubscriptionGroup(defaultB... |
public String convert(ILoggingEvent event) {
StringBuilder sb = new StringBuilder();
int pri = facility + LevelToSyslogSeverity.convert(event);
sb.append("<");
sb.append(pri);
sb.append(">");
sb.append(computeTimeStampString(event.getTimeStamp()));
sb.append(' ');
sb.append(localHost... | @Test
public void hostnameShouldNotIncludeDomain() throws Exception {
// RFC 3164, section 4.1.2:
// The Domain Name MUST NOT be included in the HOSTNAME field.
String host = HOSTNAME;
final int firstPeriod = host.indexOf(".");
if (firstPeriod != -1) {
host = host.substring(0, firstPeriod);
... |
@Override
public DataSerializableFactory createFactory() {
return typeId -> switch (typeId) {
case MAP_REPLICATION_UPDATE -> new WanMapAddOrUpdateEvent();
case MAP_REPLICATION_REMOVE -> new WanMapRemoveEvent();
case WAN_MAP_ENTRY_VIEW -> new WanMapEntryView<>();
... | @Test
public void testExistingTypes() {
WanDataSerializerHook hook = new WanDataSerializerHook();
IdentifiedDataSerializable mapUpdate = hook.createFactory()
.create(WanDataSerializerHook.MAP_REPLICATION_UPDATE);
assertTrue(mapUpdate instanceof WanMapAddOrUpdateEvent);
... |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void testBetweenAnd() {
String query = "a and b between 10 and 15";
List<String> list = parser.toPrefix(query);
assertEquals(Arrays.asList("a", "b", "10", "15", "between", "and"), list);
} |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldRunSetStatements() {
// Given:
final PreparedStatement<SetProperty> setProp = PreparedStatement.of("SET PROP",
new SetProperty(Optional.empty(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"));
final PreparedStatement<CreateStream> cs = PreparedStatement.of("CS",
... |
public static Duration parse(final String text) {
try {
final String[] parts = text.split("\\s");
if (parts.length != 2) {
throw new IllegalArgumentException("Expected 2 tokens, got: " + parts.length);
}
final long size = parseNumeric(parts[0]);
return buildDuration(size, part... | @Test
public void shouldThrowOnTooManyTokens() {
// Then:
// When:
final Exception e = assertThrows(
IllegalArgumentException.class,
() -> parse("10 Seconds Long")
);
// Then:
assertThat(e.getMessage(), containsString("Expected 2 tokens, got: 3"));
} |
public String getExpression() {
String column = identifier.getValue();
if (null != nestedObjectAttributes && !nestedObjectAttributes.isEmpty()) {
column = String.join(".", column, nestedObjectAttributes.stream().map(IdentifierValue::getValue).collect(Collectors.joining(".")));
}
... | @Test
void assertGetExpressionWithoutOwner() {
assertThat(new ColumnSegment(0, 0, new IdentifierValue("`col`")).getExpression(), is("col"));
} |
static void checkValidCollectionName(String databaseName, String collectionName) {
String fullCollectionName = databaseName + "." + collectionName;
if (collectionName.length() < MIN_COLLECTION_NAME_LENGTH) {
throw new IllegalArgumentException("Collection name cannot be empty.");
}
if (fullCollecti... | @Test
public void testCheckValidCollectionNameThrowsErrorWhenNameContainsDollarSign() {
assertThrows(
IllegalArgumentException.class,
() -> checkValidCollectionName("test-database", "test$collection"));
} |
@Override
public ParsedLine parse(final String line, final int cursor, final ParseContext context) {
final ParsedLine parsed = delegate.parse(line, cursor, context);
if (context != ParseContext.ACCEPT_LINE) {
return parsed;
}
if (UnclosedQuoteChecker.isUnclosedQuote(line)) {
throw new EO... | @Test
public void shouldCallDelegateWithCorrectParams() {
// Given:
EasyMock.expect(parsedLine.line()).andReturn(TERMINATED_LINE).anyTimes();
EasyMock.expect(delegate.parse("some-string", 55, ParseContext.ACCEPT_LINE))
.andReturn(parsedLine);
EasyMock.replay(delegate, parsedLine);
// Whe... |
public BrokerFileSystem getFileSystem(String path, Map<String, String> properties) {
WildcardURI pathUri = new WildcardURI(path);
String scheme = pathUri.getUri().getScheme();
if (Strings.isNullOrEmpty(scheme)) {
throw new BrokerException(TBrokerOperationStatusCode.INVALID_INPUT_FILE... | @Test
public void testGetFileSystemWithoutPassword() throws IOException {
Map<String, String> properties = new HashMap<String, String>();
properties.put("username", "user");
// properties.put("password", "changeit");
boolean haveException = false;
try {
BrokerFile... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if(directory.isRoot()) {
final AttributedList<Path> list = new AttributedList<>();
for(RootFolder root : session.roots()) {
switch(root.g... | @Test
public void testListWithHiddenFile() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new Path("/My files", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path folder = new StoregateDirectoryFeature(session, nodeid).mk... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldNotParseUnquotedEmbeddedMapKeysAsStrings() {
SchemaAndValue schemaAndValue = Values.parseString("{foo: 3}");
assertEquals(Type.STRING, schemaAndValue.schema().type());
assertEquals("{foo: 3}", schemaAndValue.value());
} |
public static String generateCode(final SqlType sqlType) {
return SqlTypeWalker.visit(sqlType, new TypeVisitor());
} | @Test
public void shouldGenerateWorkingCodeForAllSqlBaseTypes() {
for (final SqlBaseType baseType : SqlBaseType.values()) {
// When:
final String code = SqlTypeCodeGen.generateCode(TypeInstances.typeInstanceFor(baseType));
// Then:
final Object result = CodeGenTestUtil.cookAndEval(code, ... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final DownloadBuilder builder = new DbxUserFilesRequests(session.getClient(file))
.downloadBuilder(containerService.getKey(fil... | @Test
public void testReadRevision() throws Exception {
final byte[] content = RandomUtils.nextBytes(1645);
final TransferStatus status = new TransferStatus().withLength(content.length);
final Path directory = new DropboxDirectoryFeature(session).mkdir(
new Path(new Alphanume... |
public boolean isBeforeOrAt(KinesisRecord other) {
if (shardIteratorType == AT_TIMESTAMP) {
return timestamp.compareTo(other.getApproximateArrivalTimestamp()) <= 0;
}
int result = extendedSequenceNumber().compareTo(other.getExtendedSequenceNumber());
if (result == 0) {
return shardIteratorTy... | @Test
public void testComparisonWithExtendedSequenceNumber() {
assertThat(
new ShardCheckpoint("", "", new StartingPoint(LATEST))
.isBeforeOrAt(recordWith(new ExtendedSequenceNumber("100", 0L))))
.isTrue();
assertThat(
new ShardCheckpoint("", "", new StartingPo... |
public GlobalJobParameters getGlobalJobParameters() {
return configuration
.getOptional(PipelineOptions.GLOBAL_JOB_PARAMETERS)
.map(MapBasedJobParameters::new)
.orElse(new MapBasedJobParameters(Collections.emptyMap()));
} | @Test
void testGlobalParametersNotNull() {
final ExecutionConfig config = new ExecutionConfig();
assertThat(config.getGlobalJobParameters()).isNotNull();
} |
@Override
public void createIndex(String indexName, IndexOptions options, FieldIndex... fields) {
commandExecutor.get(createIndexAsync(indexName, options, fields));
} | @Test
public void testFieldTag() {
IndexOptions indexOptions = IndexOptions.defaults()
.on(IndexType.JSON)
.prefix(Arrays.asList("items"));
FieldIndex[] fields = new FieldIndex[]{
FieldIndex.tag("$.name")
.caseSensitive()
... |
@Override
public String rpcType() {
return RpcTypeEnum.WEB_SOCKET.getName();
} | @Test
public void testRpcType() {
assertEquals(RpcTypeEnum.WEB_SOCKET.getName(), shenyuClientRegisterWebSocketService.rpcType());
} |
@Override
public void transfer(V v) throws InterruptedException {
RFuture<Void> future = service.invoke(v);
commandExecutor.getInterrupted(future);
} | @Test
public void testTransfer() throws InterruptedException, ExecutionException {
RTransferQueue<Integer> queue1 = redisson.getTransferQueue("queue");
AtomicBoolean takeExecuted = new AtomicBoolean();
Future<?> f = Executors.newSingleThreadExecutor().submit(() -> {
RTransferQueu... |
@Override
public void notifyCheckpointAborted(long checkpointId) throws Exception {
super.notifyCheckpointAborted(checkpointId);
sourceReader.notifyCheckpointAborted(checkpointId);
} | @Test
void testNotifyCheckpointAborted() throws Exception {
StateInitializationContext stateContext = context.createStateContext();
operator.initializeState(stateContext);
operator.open();
operator.snapshotState(new StateSnapshotContextSynchronousImpl(100L, 100L));
operator.n... |
public static Function getFunctionOfRound(FunctionCallExpr node, Function fn, List<Type> argumentTypes) {
return getFunctionOfRound(node.getParams(), fn, argumentTypes);
} | @Test
public void testGetFnOfTruncateForDecimalAndSlotRef() {
List<Expr> params = Lists.newArrayList();
params.add(new DecimalLiteral(new BigDecimal(new BigInteger("1845076"), 2)));
TableName tableName = new TableName("db", "table");
SlotRef slotRef = new SlotRef(tableName, "v1");
... |
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
String originalString = values[0].execute();
String mode = null; // default
if (values.length > 1) {
mode = values[1].execute();
}
if(StringUtils... | @Test
public void testChangeCaseWrongModeIgnore() throws Exception {
String returnValue = execute("ab-CD eF", "Wrong");
assertEquals("ab-CD eF", returnValue);
} |
@Override
public String getSessionId() {
return sessionID;
} | @Test
public void testDeleteConfigRequestWithRunningDatastoreIdDuration() {
log.info("Starting delete-config async");
assertNotNull("Incorrect sessionId", session1.getSessionId());
try {
assertFalse("NETCONF delete-config command failed",
session1.deleteConfig... |
public static double mul(float v1, float v2) {
return mul(Float.toString(v1), Float.toString(v2)).doubleValue();
} | @Test
public void mulTest(){
final BigDecimal mul = NumberUtil.mul(new BigDecimal("10"), null);
assertEquals(BigDecimal.ZERO, mul);
} |
@Override
public List<DictTypeDO> getDictTypeList() {
return dictTypeMapper.selectList();
} | @Test
public void testGetDictTypeList() {
// 准备参数
DictTypeDO dictTypeDO01 = randomDictTypeDO();
dictTypeMapper.insert(dictTypeDO01);
DictTypeDO dictTypeDO02 = randomDictTypeDO();
dictTypeMapper.insert(dictTypeDO02);
// mock 方法
// 调用
List<DictTypeDO> d... |
Optional<String> placementGroupEc2() {
return getOptionalMetadata(ec2MetadataEndpoint.concat("/placement/group-name/"), "placement group");
} | @Test
public void failToFetchPlacementGroupEc2() {
// given
stubFor(get(urlEqualTo(GROUP_NAME_URL))
.willReturn(aResponse().withStatus(HttpURLConnection.HTTP_INTERNAL_ERROR).withBody("Service Unavailable")));
// when
Optional<String> placementGroupResult = awsMetadat... |
@Override
public List<ParagraphInfo> getParagraphList(String user, String noteId)
throws IOException, TException, ServiceException{
// Check READER permission
Set<String> userAndRoles = new HashSet<>();
userAndRoles.add(user);
boolean isAllowed = authorizationService.isReader(noteId, use... | @Test
void testGetParagraphList() throws IOException {
String noteId = null;
try {
noteId = notebook.createNote("note1", anonymous);
notebook.processNote(noteId,
note -> {
Paragraph p1 = note.addNewParagraph(anonymous);
p1.setText("%md start remote interpreter process"... |
public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) {
if (chunked) {
m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
m.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
} else {
List<String> encodings = m.headers... | @Test
public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse(message.headers().isEmpty());
HttpUtil.setTransferEn... |
public void addMetricValue(String name, RuntimeUnit unit, long value)
{
metrics.computeIfAbsent(name, k -> new RuntimeMetric(name, unit)).addValue(value);
} | @Test
public void testAddMetricValue()
{
RuntimeStats stats = new RuntimeStats();
stats.addMetricValue(TEST_METRIC_NAME_1, NONE, 2);
stats.addMetricValue(TEST_METRIC_NAME_1, NONE, 3);
stats.addMetricValue(TEST_METRIC_NAME_1, NONE, 5);
stats.addMetricValue(TEST_METRIC_NAME... |
@SuppressWarnings("unchecked")
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
final String windowedInnerClassSerdeConfig = (String) configs.get(StreamsConfig.WINDOWED_INNER_CLASS_SERDE);
Serde<T> windowInnerClassSerde = null;
if (windowedInnerClass... | @Test
public void shouldThrowErrorIfWindowInnerClassDeserialiserIsNotSet() {
final SessionWindowedDeserializer<?> deserializer = new SessionWindowedDeserializer<>();
assertThrows(IllegalArgumentException.class, () -> deserializer.configure(props, false));
} |
public static String localIP() {
if (!StringUtils.isEmpty(localIp)) {
return localIp;
}
if (System.getProperties().containsKey(CLIENT_LOCAL_IP_PROPERTY)) {
return localIp = System.getProperty(CLIENT_LOCAL_IP_PROPERTY, getAddress());
}
localIp = getAddress(... | @Test
void testLocalIpWithPreferHostname() throws Exception {
InetAddress inetAddress = invokeGetInetAddress();
String hostname = inetAddress.getHostName();
System.setProperty("com.alibaba.nacos.client.local.preferHostname", "true");
assertEquals(hostname, NetUtils.localIP());
} |
@Override
public Timed start() {
return new DefaultTimed(this, timeUnit);
} | @Test
public void multipleStops() {
Timer timer = new DefaultTimer(TimeUnit.NANOSECONDS);
Timer.Timed timed = timer.start();
timed.stop();
// we didn't start the timer again
assertThatThrownBy(timed::stop)
.isInstanceOf(IllegalStateException.class)
.hasMessage("stop() called multip... |
File getHomeDir() {
return homeDir;
} | @Test
public void detectHomeDir_returns_existing_dir() {
assertThat(new AppSettingsLoaderImpl(system, new String[0], serviceLoaderWrapper).getHomeDir()).exists().isDirectory();
} |
public boolean isAllowedNamespace(String tenant, String namespace, String fromTenant, String fromNamespace) {
return true;
} | @Test
void isAllowedNamespace() {
assertTrue(flowService.isAllowedNamespace("tenant", "namespace", "fromTenant", "fromNamespace"));
} |
public static ImmutableList<String> splitToLowercaseTerms(String identifierName) {
if (ONLY_UNDERSCORES.matcher(identifierName).matches()) {
// Degenerate case of names which contain only underscore
return ImmutableList.of(identifierName);
}
return TERM_SPLITTER
.splitToStream(identifier... | @Test
public void splitToLowercaseTerms_separatesTrailingDigits_withoutDelimiter() {
String identifierName = "term123";
ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName);
assertThat(terms).containsExactly("term", "123");
} |
static List<ObjectCreationExpr> getMiningFieldsObjectCreations(final List<MiningField> miningFields) {
return miningFields.stream()
.map(miningField -> {
ObjectCreationExpr toReturn = new ObjectCreationExpr();
toReturn.setType(MiningField.class.getCanonica... | @Test
void getMiningFieldsObjectCreations() {
List<MiningField> miningFields = IntStream.range(0, 3)
.mapToObj(i -> ModelUtils.convertToKieMiningField(getRandomMiningField(),
getRandomDataField()))
.collect(Col... |
public T initialBufferSize(int value) {
if (value <= 0) {
throw new IllegalArgumentException("initialBufferSize must be strictly positive");
}
this.initialBufferSize = value;
return get();
} | @Test
void initialBufferSize() {
checkDefaultInitialBufferSize(conf);
conf.initialBufferSize(123);
assertThat(conf.initialBufferSize()).as("initial buffer size").isEqualTo(123);
checkDefaultMaxInitialLineLength(conf);
checkDefaultMaxHeaderSize(conf);
checkDefaultMaxChunkSize(conf);
checkDefaultValidat... |
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about_menu_option:
Navigation.findNavController(requireView())
.navigate(MainFragmentDirections.actionMainFragmentToAboutAnySoftKeyboardFragment());
return true;
case R.id.... | @Test
public void testTweaksMenuCommand() throws Exception {
final MainFragment fragment = startFragment();
final FragmentActivity activity = fragment.getActivity();
Menu menu = Shadows.shadowOf(activity).getOptionsMenu();
Assert.assertNotNull(menu);
final MenuItem item = menu.findItem(R.id.tweak... |
public static ConfigDiskService getInstance() {
if (configDiskService == null) {
synchronized (ConfigDiskServiceFactory.class) {
if (configDiskService == null) {
String type = System.getProperty("config_disk_type", TYPE_RAW_DISK);
if (type.equa... | @Test
void getRawDiskInstance() {
System.setProperty("config_disk_type", "rawdisk");
ConfigDiskService instance = ConfigDiskServiceFactory.getInstance();
assertTrue(instance instanceof ConfigRawDiskService);
} |
public synchronized boolean isServing() {
return mWebServer != null && mWebServer.getServer().isRunning();
} | @Test
public void alwaysOnTest() {
Configuration.set(PropertyKey.STANDBY_MASTER_WEB_ENABLED, true);
WebServerService webService =
WebServerService.Factory.create(mWebAddress, mMasterProcess);
Assert.assertTrue(webService instanceof AlwaysOnWebServerService);
Assert.assertTrue(waitForFree());
... |
public String authorizationId() {
return authorizationId;
} | @Test
public void testAuthorizationId() throws Exception {
String message = "n,a=myuser,\u0001auth=Bearer 345\u0001\u0001";
OAuthBearerClientInitialResponse response = new OAuthBearerClientInitialResponse(message.getBytes(StandardCharsets.UTF_8));
assertEquals("345", response.tokenValue());
... |
@Override
public AverageAccumulator clone() {
AverageAccumulator average = new AverageAccumulator();
average.count = this.count;
average.sum = this.sum;
return average;
} | @Test
void testClone() {
AverageAccumulator average = new AverageAccumulator();
average.add(1);
AverageAccumulator averageNew = average.clone();
assertThat(averageNew.getLocalValue()).isCloseTo(1, within(0.0));
} |
@Override
public State getState() {
if (terminalState != null) {
return terminalState;
}
return delegate.getState();
} | @Test
public void givenNotTerminated_reportsState() {
PipelineResult delegate = mock(PipelineResult.class);
when(delegate.getState()).thenReturn(PipelineResult.State.RUNNING);
PrismPipelineResult underTest = new PrismPipelineResult(delegate, exec::stop);
assertThat(underTest.getState()).isEqualTo(Pipe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.