focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public WsResponse call(WsRequest request) {
checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode");
WsResponse response = target.wsConnector().call(request);
failIfUnauthorized(response);
checkAuthenticationWarnings(response);
return response;
} | @Test
public void call_whenInvalidCredentials_shouldFailWithMsg() {
WsRequest request = newRequest();
server.stubFor(get(urlEqualTo(URL_ENDPOINT))
.willReturn(aResponse()
.withStatus(401)
.withBody("Invalid credentials")));
DefaultScannerWsClient client = new DefaultScannerWsClient(... |
public Set<String> emptyLogDirs() {
return emptyLogDirs;
} | @Test
public void testEmptyLogDirsForEmpty() {
assertEquals(new HashSet<>(), EMPTY.emptyLogDirs());
} |
@SuppressWarnings("java:S2583")
public static boolean verify(@NonNull JWKSet jwks, @NonNull JWSObject jws) {
if (jwks == null) {
throw new IllegalArgumentException("no JWKS provided to verify JWS");
}
if (jwks.getKeys() == null || jwks.getKeys().isEmpty()) {
return false;
}
var head... | @Test
void verifyUnknownKey() throws ParseException, JOSEException {
var signerJwks = new ECKeyGenerator(Curve.P_256).generate();
var jws = toJws(signerJwks, "test").serialize();
jws = tamperSignature(jws);
var in = JWSObject.parse(jws);
// when & then
assertFalse(JwsVerifier.verify(JWKS,... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public HistoryInfo get() {
return getHistoryInfo();
} | @Test
public void testHSDefault() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history/")
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
response.getType().toString());
... |
@Override
public void build(T instance) {
super.build(instance);
if (check != null) {
instance.setCheck(check);
}
if (init != null) {
instance.setInit(init);
}
if (!StringUtils.isEmpty(generic)) {
instance.setGeneric(generic);
... | @Test
void build() {
ReferenceBuilder builder = new ReferenceBuilder();
builder.check(true)
.init(false)
.generic(true)
.injvm(false)
.lazy(true)
.reconnect("reconnect")
.sticky(false)
.ve... |
@Nullable
public static Field findPropertyField(Class<?> clazz, String fieldName) {
Field field;
try {
field = clazz.getField(fieldName);
} catch (NoSuchFieldException e) {
return null;
}
if (!Modifier.isPublic(field.getModifiers()) || Modifier.isStat... | @Test
public void when_findPropertyField_nonExistent_then_returnsNull() {
assertNull(findPropertyField(JavaFields.class, "nonExistentField"));
} |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariablesStatement sqlStatement, final ContextManager contextManager) {
ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData();
Collection<LocalDataQueryResultRow> result = ConfigurationPropertyK... | @Test
void assertExecuteWithLike() {
when(contextManager.getMetaDataContexts().getMetaData().getProps()).thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property("system-log-level", "INFO"))));
when(contextManager.getMetaDataContexts().getMetaData().getTemporaryProps())
... |
@Override
public boolean hasNext() {
synchronized (lock) {
try {
return parser.peek() != JsonToken.END_DOCUMENT;
} catch (MalformedJsonException e) {
throw new JsonSyntaxException(e);
} catch (IOException e) {
throw new JsonIOException(e);
}
}
} | @Test
public void testIncompleteInput() {
JsonStreamParser parser = new JsonStreamParser("[");
assertThat(parser.hasNext()).isTrue();
assertThrows(JsonSyntaxException.class, parser::next);
} |
@Override
public @Nullable State waitUntilFinish() {
return waitUntilFinish(Duration.millis(-1));
} | @Test
public void testWaitUntilFinishNoRepeatedLogs() throws Exception {
DataflowPipelineJob job = new DataflowPipelineJob(mockDataflowClient, JOB_ID, options, null);
Sleeper sleeper = new ZeroSleeper();
NanoClock nanoClock = mock(NanoClock.class);
Instant separatingTimestamp = new Instant(42L);
... |
public long getMaxSize() {
return maxSize;
} | @Test
public void fileMaxSizeTest() {
FileSegment fileSegment = new PosixFileSegment(
storeConfig, FileSegmentType.COMMIT_LOG, MessageStoreUtil.toFilePath(mq), 100L);
Assert.assertEquals(storeConfig.getTieredStoreCommitLogMaxSize(), fileSegment.getMaxSize());
fileSegment.destroyF... |
public static Map<String, String> getParamsFromFileStoreInfo(FileStoreInfo fsInfo) {
Map<String, String> params = new HashMap<>();
switch (fsInfo.getFsType()) {
case S3:
S3FileStoreInfo s3FileStoreInfo = fsInfo.getS3FsInfo();
params.put(CloudConfigurationConst... | @Test
public void testGetParamsFromFileStoreInfo() {
AwsCredentialInfo.Builder awsCredBuilder = AwsCredentialInfo.newBuilder();
awsCredBuilder.getSimpleCredentialBuilder()
.setAccessKey("ak")
.setAccessKeySecret("sk")
.build();
FileStoreInfo.B... |
protected void revertImmutableChanges(PersistentVolumeClaim current, PersistentVolumeClaim desired) {
desired.getSpec().setVolumeName(current.getSpec().getVolumeName());
desired.getSpec().setStorageClassName(current.getSpec().getStorageClassName());
desired.getSpec().setAccessModes(current.get... | @Test
public void testRevertingImmutableFields() {
PersistentVolumeClaim desired = new PersistentVolumeClaimBuilder()
.withNewMetadata()
.withName("my-pvc")
.withNamespace("my-namespace")
.endMetadata()
.withNewSpec()
... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertCompressedStreamMessageToAmqpMessageWithAmqpSequencey() throws Exception {
ActiveMQStreamMessage outbound = createStreamMessage(true);
outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_SEQUENCE);
outbound.writeBoolean(false);
outbound.writeString... |
@Override
@SuppressFBWarnings(value = "EI_EXPOSE_REP")
public KsqlConfig getKsqlConfig() {
return ksqlConfig;
} | @Test
public void shouldUseFirstPolledConfig() {
// Given:
addPollResult(KafkaConfigStore.CONFIG_MSG_KEY, savedProperties, badProperties);
expectRead(consumerBefore);
// When:
final KsqlConfig mergedConfig = getKsqlConfig();
// Then:
verifyMergedConfig(mergedConfig);
} |
@Override
public ValidationResult getConfigurationValidationResultFromResponseBody(String responseBody) {
return new JSONResultMessageHandler().toValidationResult(responseBody);
} | @Test
public void getConfigurationValidationResultFromResponseBody_shouldDeserializeJsonToValidationResult() {
final ArtifactMessageConverterV2 converter = new ArtifactMessageConverterV2();
String responseBody = "[{\"message\":\"Url must not be blank.\",\"key\":\"Url\"},{\"message\":\"SearchBase mus... |
@Override
public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext,
final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException {
if (1 == queryResults.size() && !isNeedAggregateRewri... | @Test
void assertBuildOrderByStreamMergedResultWithMySQLLimit() throws SQLException {
final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL"));
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_ST... |
public static void rename(FileSystem fs, String oldName, String newName)
throws IOException {
Path oldDir = new Path(oldName);
Path newDir = new Path(newName);
if (!fs.rename(oldDir, newDir)) {
throw new IOException("Could not rename " + oldDir + " to " + newDir);
}
} | @Test
public void testRenameWithFalse() {
final String ERROR_MESSAGE = "Could not rename";
final String NEW_FILE_NAME = "test-new.mapfile";
final String OLD_FILE_NAME = "test-old.mapfile";
MapFile.Writer writer = null;
try {
FileSystem fs = FileSystem.getLocal(conf);
FileSystem spyFs =... |
@Override
public byte readByte()
throws EOFException {
if (availableLong() < 1) {
throw new EOFException();
}
return _dataBuffer.getByte(_currentOffset++);
} | @Test
void testReadByte()
throws EOFException {
int read = _dataBufferPinotInputStream.readByte();
assertEquals(read, _byteBuffer.get(0) & 0xFF);
assertEquals(_dataBufferPinotInputStream.getCurrentOffset(), 1);
} |
public Path makeQualified(FileSystem fs) {
Path path = this;
if (!isAbsolute()) {
path = new Path(fs.getWorkingDirectory(), this);
}
final URI pathUri = path.toUri();
final URI fsUri = fs.getUri();
String scheme = pathUri.getScheme();
String authorit... | @Test
void testMakeQualified() throws IOException {
// make relative path qualified
String path = "test/test";
Path p = new Path(path).makeQualified(FileSystem.getLocalFileSystem());
URI u = p.toUri();
assertThat(u.getScheme()).isEqualTo("file");
assertThat(u.getAuth... |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile,
String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
// 1. 执行请求
// 参考链接 https://cloud.tencent.com/document/product/382/55981
TreeMap<String, Object> bod... | @Test
public void testDoSendSms_success() throws Throwable {
try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
... |
@Override
public void revert(final Path file) throws BackgroundException {
if(file.isFile()) {
try {
final S3Object destination = new S3Object(containerService.getKey(file));
// Keep same storage class
destination.setStorageClass(file.attributes().... | @Test
public void testRevert() throws Exception {
final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path directory = new S3DirectoryF... |
public static CharSequence trimOws(CharSequence value) {
final int length = value.length();
if (length == 0) {
return value;
}
int start = indexOfFirstNonOwsChar(value, length);
int end = indexOfLastNonOwsChar(value, start, length);
return start == 0 && end ==... | @Test
public void trimOws() {
assertSame("", StringUtil.trimOws(""));
assertEquals("", StringUtil.trimOws(" \t "));
assertSame("a", StringUtil.trimOws("a"));
assertEquals("a", StringUtil.trimOws(" a"));
assertEquals("a", StringUtil.trimOws("a "));
assertEquals("a", St... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{
PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name()));
if (userSession.hasSession() && userSession.isLoggedIn()
&& userSess... | @Test
public void doFilter_givenLoggedInAdminAndConsentRequired_redirect() throws Exception {
PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession);
when(userSession.hasSession()).thenReturn(true);
when(userSession.isLoggedIn()).thenReturn(true);
when(userS... |
@Override
public void start() {
this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getClass().getCanonicalName() + "-thread-%d")
.build());
for (MonitoringTask task : monitoringTasks) {
sche... | @Test
public void start_givenTwoTasks_callsGetsDelayAndPeriodFromTasks() {
underTest.start();
verify(task1, times(1)).getDelay();
verify(task1, times(1)).getPeriod();
verify(task2, times(1)).getDelay();
verify(task2, times(1)).getPeriod();
} |
@Override
protected InputStream openObjectInputStream(
long position, int bytesToRead) throws IOException {
OSSObject object;
try {
GetObjectRequest getObjectRequest = new GetObjectRequest(mBucketName, mPath);
getObjectRequest.setRange(position, position + bytesToRead - 1);
object = mC... | @Test
public void openObjectInputStream() throws Exception {
OSSObject object = Mockito.mock(OSSObject.class);
InputStream inputStream = Mockito.mock(InputStream.class);
Mockito.when(mClient.getObject(ArgumentMatchers.any(
GetObjectRequest.class))).thenReturn(object);
Mockito.when(object.getOb... |
public static void trace(Throwable e) {
traceContext(e, ContextUtil.getContext());
} | @Test
public void testTraceWhenContextSizeExceedsThreshold() {
int i = 0;
for (; i < Constants.MAX_CONTEXT_NAME_SIZE; i++) {
ContextUtil.enter("test-context-" + i);
ContextUtil.exit();
}
try {
ContextUtil.enter("test-context-" + i);
th... |
public synchronized void clear() {
this.buckets = new long[bucketType.getNumBuckets()];
this.numBoundedBucketRecords = 0;
this.numTopRecords = 0;
this.topRecordsSum = 0;
this.numBottomRecords = 0;
this.bottomRecordsSum = 0;
this.mean = 0;
this.sumOfSquaredDeviations = 0;
} | @Test
public void testClear() {
HistogramData histogramData = HistogramData.linear(0, 0.2, 50);
histogramData.record(-1, 1, 2, 3);
assertThat(histogramData.getTotalCount(), equalTo(4L));
assertThat(histogramData.getCount(5), equalTo(1L));
histogramData.clear();
assertThat(histogramData.getTota... |
ContainerLaunchContext setupApplicationMasterContainer(
String yarnClusterEntrypoint, boolean hasKrb5, JobManagerProcessSpec processSpec) {
// ------------------ Prepare Application Master Container ------------------------------
// respect custom JVM options in the YAML file
List<... | @Test
void testSetupApplicationMasterContainer() {
Configuration cfg = new Configuration();
YarnClusterDescriptor clusterDescriptor = createYarnClusterDescriptor(cfg);
final JobManagerProcessSpec jobManagerProcessSpec =
createDefaultJobManagerProcessSpec(1024);
final... |
@Deprecated
@Override public void toXML(Object obj, OutputStream out) {
super.toXML(obj, out);
} | @Issue("JENKINS-71182")
@Test
public void writeEmoji() throws Exception {
Bar b = new Bar();
String text = "Fox 🦊";
b.s = text;
StringWriter w = new StringWriter();
XStream2 xs = new XStream2();
xs.toXML(b, w);
String xml = w.toString();
assertTha... |
@VisibleForTesting
void validateMenu(Long parentId, String name, Long id) {
MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name);
if (menu == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的菜单
if (id == null) {
throw exception(MENU_NAME_DUPLI... | @Test
public void testValidateMenu_success() {
// mock 父子菜单
MenuDO sonMenu = createParentAndSonMenu();
// 准备参数
Long parentId = sonMenu.getParentId();
Long otherSonMenuId = randomLongId();
String otherSonMenuName = randomString();
// 调用,无需断言
menuServic... |
@Override
public Long aggregate(final Object currentValue, final Long aggregateValue) {
if (currentValue == null) {
return aggregateValue;
}
return aggregateValue + 1;
} | @Test
public void shouldHandleNullCount() {
final CountKudaf doubleCountKudaf = getDoubleCountKudaf();
final double[] values = new double[]{3.0, 5.0, 8.0, 2.2, 3.5, 4.6, 5.0};
Long currentCount = 0L;
// aggregate null before any aggregation
currentCount = doubleCountKudaf.aggregate(null, currentC... |
public Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> getPluggableSCMMaterialUsageInPipelines() {
if (pluggableSCMMaterialToPipelineMap == null) {
synchronized (this) {
if (pluggableSCMMaterialToPipelineMap == null) {
pluggableSCMMaterialToPipelineMap = ... | @Test
public void shouldGetPluggableSCMMaterialUsageInPipelines() throws Exception {
PluggableSCMMaterialConfig pluggableSCMMaterialOne = new PluggableSCMMaterialConfig("scm-id-one");
PluggableSCMMaterialConfig pluggableSCMMaterialTwo = new PluggableSCMMaterialConfig("scm-id-two");
final Pip... |
public static ReadonlyConfig replaceTablePlaceholder(
ReadonlyConfig config, CatalogTable table) {
return replaceTablePlaceholder(config, table, Collections.emptyList());
} | @Test
public void testSinkOptionsWithMultiTable() {
ReadonlyConfig config = createConfig();
CatalogTable table1 = createTestTable();
CatalogTable table2 = createTestTableWithNoDatabaseAndSchemaName();
ReadonlyConfig newConfig1 =
TablePlaceholder.replaceTablePlaceholde... |
@Override
public VersionedRecord<V> delete(final K key, final long timestamp) {
final ValueAndTimestamp<V> valueAndTimestamp = internal.delete(key, timestamp);
return valueAndTimestamp == null
? null
: new VersionedRecord<>(valueAndTimestamp.value(), valueAndTimestamp.timesta... | @Test
public void shouldThrowNullPointerOnDeleteIfKeyIsNull() {
assertThrows(NullPointerException.class, () -> store.delete(null, TIMESTAMP));
} |
public void isPresent() {
if (actual == null) {
failWithActual(simpleFact("expected present optional"));
} else if (!actual.isPresent()) {
failWithoutActual(simpleFact("expected to be present"));
}
} | @Test
public void isPresentFailingNull() {
expectFailureWhenTestingThat(null).isPresent();
assertFailureKeys("expected present optional", "but was");
} |
public static int[] parseInts(String nums, String sperator) {
String[] ss = StringUtils.split(nums, sperator);
int[] ints = new int[ss.length];
for (int i = 0; i < ss.length; i++) {
ints[i] = Integer.parseInt(ss[i]);
}
return ints;
} | @Test
public void parseInts() {
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, CommonUtils.parseInts("1,2,3", ","));
} |
@Override
public String getTableAlias() {
return ast.getTableSource().getAlias();
} | @Test
public void testGetTableAlias() {
String sql = "update t set a = ?, b = ?, c = ?";
SQLStatement sqlStatement = getSQLStatement(sql);
SqlServerUpdateRecognizer recognizer = new SqlServerUpdateRecognizer(sql, sqlStatement);
Assertions.assertNull(recognizer.getTableAlias());
... |
@Override
public boolean supports(Job job) {
if (jobActivator == null) return false;
JobDetails jobDetails = job.getJobDetails();
return !jobDetails.hasStaticFieldName() && jobActivator.activateJob(toClass(jobDetails.getClassName())) != null;
} | @Test
void doesNotSupportJobIfNoJobActivatorIsRegistered() {
backgroundIoCJobWithIocRunner = new BackgroundJobWithIocRunner(null);
Job job = anEnqueuedJob()
.withJobDetails(defaultJobDetails())
.build();
assertThat(backgroundIoCJobWithIocRunner.supports(job)... |
@Override
public void connect() throws IllegalStateException, IOException {
if (isConnected()) {
throw new IllegalStateException("Already connected");
}
try {
connection = connectionFactory.newConnection();
} catch (TimeoutException e) {
throw new... | @Test
public void shouldConnectToGraphiteServer() throws Exception {
graphite.connect();
verify(connectionFactory, atMost(1)).newConnection();
verify(connection, atMost(1)).createChannel();
} |
@Override
public void onProjectBranchesChanged(Set<Project> projects, Set<String> impactedBranches) {
checkNotNull(projects, "projects can't be null");
if (projects.isEmpty()) {
return;
}
Arrays.stream(listeners)
.forEach(safelyCallListener(listener -> listener.onProjectBranchesChanged(pr... | @Test
public void onProjectBranchesChanged_throws_NPE_if_set_is_null() {
assertThatThrownBy(() -> underTestWithListeners.onProjectBranchesChanged(null, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("projects can't be null");
} |
@Override public Message postProcessMessage(Message message) {
MessageProducerRequest request = new MessageProducerRequest(message);
TraceContext maybeParent = currentTraceContext.get();
// Unlike message consumers, we try current span before trying extraction. This is the proper
// order because the s... | @Test void should_resume_headers() {
Message message = MessageBuilder.withBody(new byte[0]).build();
message.getMessageProperties().setHeader("b3", B3SingleFormat.writeB3SingleFormat(parent));
Message postProcessMessage = tracingMessagePostProcessor.postProcessMessage(message);
assertThat(spans.get(0)... |
@Override
public void onCreating(AbstractJob job) {
JobDetails jobDetails = job.getJobDetails();
Optional<Job> jobAnnotation = getJobAnnotation(jobDetails);
setJobName(job, jobAnnotation);
setAmountOfRetries(job, jobAnnotation);
setLabels(job, jobAnnotation);
} | @Test
void testDisplayNameIsUsedIfProvidedByJobBuilder() {
Job job = anEnqueuedJob()
.withName("My job name")
.withJobDetails(jobDetails()
.withClassName(TestService.class)
.withMethodName("doWork")
.with... |
@Override
public Optional<DispatchEvent> build(final DataChangedEvent event) {
if (Strings.isNullOrEmpty(event.getValue())) {
return Optional.empty();
}
Optional<QualifiedDataSource> qualifiedDataSource = QualifiedDataSourceNode.extractQualifiedDataSource(event.getKey());
... | @Test
void assertCreateEmptyEvent() {
Optional<DispatchEvent> actual = new QualifiedDataSourceDispatchEventBuilder().build(
new DataChangedEvent("/nodes/qualified_data_sources/replica_query_db.readwrite_ds.replica_ds_0", "", Type.ADDED));
assertFalse(actual.isPresent());
} |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testMissingOutputDirArgument() throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
createArgumentHandler();
String[] args = new String[] {"-y",
FSConfigConverterTestCommons.YARN_SITE_XML};
int retVal = argument... |
@Override
public void execute(SensorContext context) {
Set<String> reportPaths = loadReportPaths();
Map<String, SarifImportResults> filePathToImportResults = new HashMap<>();
for (String reportPath : reportPaths) {
try {
SarifImportResults sarifImportResults = processReport(context, reportP... | @Test
public void execute_whenDeserializationFails_shouldSkipReport() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
failDeserializingReport(FILE_1);
ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
SarifIssues... |
public Bson parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) {
final Filter filter = singleFilterParser.parseSingleExpression(filterExpression, attributes);
return filter.toBson();
} | @Test
void throwsExceptionOnFieldThatDoesNotExistInAttributeList() {
assertThrows(IllegalArgumentException.class, () ->
toTest.parseSingleExpression("strange_field:blabla",
List.of(EntityAttribute.builder()
.id("owner")
... |
@Override
public PageData<WidgetTypeInfo> findSystemWidgetTypes(WidgetTypeFilter widgetTypeFilter, PageLink pageLink) {
boolean deprecatedFilterEnabled = !DeprecatedFilter.ALL.equals(widgetTypeFilter.getDeprecatedFilter());
boolean deprecatedFilterBool = DeprecatedFilter.DEPRECATED.equals(widgetType... | @Test
public void testFindSystemWidgetTypes() {
PageData<WidgetTypeInfo> widgetTypes = widgetTypeDao.findSystemWidgetTypes(
WidgetTypeFilter.builder()
.tenantId(TenantId.SYS_TENANT_ID)
.fullSearch(true)
.deprecatedFilter... |
@Override
public synchronized void putAll(final List<KeyValue<Bytes, byte[]>> entries) {
physicalStore.putAll(entries.stream()
.map(kv -> new KeyValue<>(
prefixKeyFormatter.addPrefix(kv.key),
kv.value))
.collect(Collectors.toList()));
} | @Test
public void shouldPutAll() {
final List<KeyValue<Bytes, byte[]>> segment0Records = new ArrayList<>();
segment0Records.add(new KeyValue<>(
new Bytes(serializeBytes("shared")),
serializeBytes("v1")));
segment0Records.add(new KeyValue<>(
new Bytes(seria... |
@VisibleForTesting
MissingSegmentInfo findMissingSegments(Map<String, Map<String, String>> idealStateMap, Instant now) {
// create the maps
Map<Integer, LLCSegmentName> partitionGroupIdToLatestConsumingSegmentMap = new HashMap<>();
Map<Integer, LLCSegmentName> partitionGroupIdToLatestCompletedSegmentMap =... | @Test
public void noMissingConsumingSegmentsScenario3() {
// scenario 3: no missing segments and there's no exception in connecting to stream
// two partitions have reached end of life
Map<String, Map<String, String>> idealStateMap = new HashMap<>();
// partition 0
idealStateMap.put("tableA__0__0... |
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
while (it.hasNext()) ... | @Test
public void version() {
assertThat(CommandLineOptionsParser.parse(Arrays.asList("-v")).version()).isTrue();
} |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @Nullable <InputT> TransformEvaluator<InputT> forApplication(
AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) {
return createEvaluator((AppliedPTransform) application);
} | @Test
public void evaluatorReusesReaderAndClosesAtTheEnd() throws Exception {
int numElements = 1000;
ContiguousSet<Long> elems =
ContiguousSet.create(Range.openClosed(0L, (long) numElements), DiscreteDomain.longs());
TestUnboundedSource<Long> source =
new TestUnboundedSource<>(BigEndianLo... |
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CreateConnector that = (CreateConnector) o;
return Objects.equals(name, that.name)
&& Objects.equals(config, that.config)... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(
new CreateConnector(Optional.of(SOME_LOCATION), NAME, CONFIG, CreateConnector.Type.SOURCE, false),
new CreateConnector(Optional.of(OTHER_LOCATION), NAME, CONFIG, CreateConnector.Type.SOURCE, false),
... |
@Override public Message postProcessMessage(Message message) {
MessageProducerRequest request = new MessageProducerRequest(message);
TraceContext maybeParent = currentTraceContext.get();
// Unlike message consumers, we try current span before trying extraction. This is the proper
// order because the s... | @Test void should_prefer_current_span() {
// Will be either a bug, or a missing processor stage which can result in an old span in headers
Message message = MessageBuilder.withBody(new byte[0]).build();
message.getMessageProperties().setHeader("b3", B3SingleFormat.writeB3SingleFormat(grandparent));
Mes... |
public synchronized KsqlScalarFunction getFunction(final List<SqlArgument> argTypes) {
return udfIndex.getFunction(argTypes);
} | @Test
public void shouldThrowIfNoVariantFoundThatAcceptsSuppliedParamTypes() {
// When:
final Exception e = assertThrows(
KafkaException.class,
() -> factory.getFunction(of(SqlArgument.of(STRING), SqlArgument.of(BIGINT)))
);
// Then:
assertThat(e.getMessage(), containsString(
... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertEmptyObjectMessageToAmqpMessageWithDataBody() throws Exception {
ActiveMQObjectMessage outbound = createObjectMessage();
outbound.onSend();
outbound.storeContent();
JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer();
... |
public static Select select(String fieldName) { return new Select(fieldName);
} | @Test
void numeric_operations() {
String q = Q.select("*")
.from("sd1")
.where("f1").le(1)
.and("f2").lt(2)
.and("f3").ge(3)
.and("f4").gt(4)
.and("f5").eq(5)
.and("f6").inRange(6, 7)
... |
@Override
public void deleteUser(String username) {
String sql = "DELETE FROM users WHERE username=?";
try {
EmbeddedStorageContextHolder.addSqlContext(sql, username);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextHolder.cleanAllContext(... | @Test
void testDeleteUser() {
embeddedUserPersistService.deleteUser("username");
Mockito.verify(databaseOperate).blockUpdate();
} |
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) {
Objects.requireNonNull(metric);
if (batchMeasure == null) {
return Optional.empty();
}
Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder();
switch (metric.getType().getValueType()) {
... | @Test
public void toMeasure_maps_data_and_alert_properties_in_dto_for_Int_Metric() {
ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder()
.setIntValue(IntValue.newBuilder().setValue(10).setData(SOME_DATA))
.build();
Optional<Measure> measure = underTest.toMeasure(batchMeasure, ... |
public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length) {
checkNotNull(a, "a");
checkNotNull(b, "b");
// All indexes and lengths must be non-negative
checkPositiveOrZero(aStartIndex, "aStartIndex");
checkPositiveOrZero(bStartIndex, "bStart... | @Test
public void notEqualsBufferOverflow() {
byte[] b1 = new byte[8];
byte[] b2 = new byte[16];
Random rand = new Random();
rand.nextBytes(b1);
rand.nextBytes(b2);
final int iB1 = b1.length / 2;
final int iB2 = iB1 + b1.length;
final int length = b1.l... |
public RepositoryElementInterface dataNodeToElement( final DataNode rootNode ) throws KettleException {
JobMeta jobMeta = new JobMeta();
dataNodeToElement( rootNode, jobMeta );
return jobMeta;
} | @Test
public void testDataNodeToElement() throws KettleException {
DataNode dataNode = jobDelegate.elementToDataNode( mockJobMeta );
setIds( dataNode );
JobMeta jobMeta = new JobMeta();
jobDelegate.dataNodeToElement( dataNode, jobMeta );
assertThat( jobMeta.getJobCopies().size(), equalTo( 1 ) );
... |
public static <T> T runAs(String username, Callable<T> callable) {
final Subject subject = new Subject.Builder()
.principals(new SimplePrincipalCollection(username, "runAs-context"))
.authenticated(true)
.sessionCreationEnabled(false)
.buildSubject... | @Test
void runAs() {
// Simulate what we do in the DefaultSecurityManagerProvider
DefaultSecurityManager sm = new DefaultSecurityManager();
SecurityUtils.setSecurityManager(sm);
final DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
final DefaultSessionStorageEvaluator... |
@VisibleForTesting
static ConnectionConfig configureConnectionConfig(Map<String, String> properties) {
Long connectionTimeoutMillis =
PropertyUtil.propertyAsNullableLong(properties, REST_CONNECTION_TIMEOUT_MS);
Integer socketTimeoutMillis =
PropertyUtil.propertyAsNullableInt(properties, REST_S... | @Test
public void testSocketAndConnectionTimeoutSet() {
long connectionTimeoutMs = 10L;
int socketTimeoutMs = 10;
Map<String, String> properties =
ImmutableMap.of(
HTTPClient.REST_CONNECTION_TIMEOUT_MS, String.valueOf(connectionTimeoutMs),
HTTPClient.REST_SOCKET_TIMEOUT_MS,... |
@Override
public void publish(ScannerReportWriter writer) {
AbstractProjectOrModule rootProject = moduleHierarchy.root();
ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder()
.setAnalysisDate(projectInfo.getAnalysisDate().getTime())
// Here we want key without branch
... | @Test
public void write_branch_info() {
String branchName = "name";
String targetName = "target";
when(branches.branchName()).thenReturn(branchName);
when(branches.branchType()).thenReturn(BranchType.BRANCH);
when(branches.targetBranchName()).thenReturn(targetName);
underTest.publish(writer)... |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromSnapshotIdWithEmptyTable() {
ScanContext scanContextWithInvalidSnapshotId =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_ID)
.startSnapshotId(1L)
.build();
ContinuousSplitPlannerImpl... |
@VisibleForTesting
PlanNodeStatsEstimate calculateJoinComplementStats(
Optional<RowExpression> filter,
List<EquiJoinClause> criteria,
PlanNodeStatsEstimate leftStats,
PlanNodeStatsEstimate rightStats)
{
if (rightStats.getOutputRowCount() == 0) {
... | @Test
public void testLeftJoinComplementStatsWithMultipleClauses()
{
PlanNodeStatsEstimate expected = planNodeStats(
LEFT_ROWS_COUNT * (LEFT_JOIN_COLUMN_NULLS + LEFT_JOIN_COLUMN_NON_NULLS / 4),
variableStatistics(LEFT_JOIN_COLUMN, 0.0, 20.0, LEFT_JOIN_COLUMN_NULLS / (LEFT... |
@Override
protected Map<ApplicationId, String> applicationsNeedingMaintenance() {
if (deployer().bootstrapping()) return Map.of();
return nodesNeedingMaintenance().stream()
.map(node -> node.allocation().get().owner())
... | @Test(timeout = 60_000)
public void queues_all_eligible_applications_for_deployment() throws Exception {
fixture.activate();
// Exhaust initial wait period and set bootstrapping to be done
clock.advance(Duration.ofMinutes(30).plus(Duration.ofSeconds(1)));
fixture.setBootstrapping(fa... |
public double bearingTo(final IGeoPoint other) {
final double lat1 = Math.toRadians(this.mLatitude);
final double long1 = Math.toRadians(this.mLongitude);
final double lat2 = Math.toRadians(other.getLatitude());
final double long2 = Math.toRadians(other.getLongitude());
final dou... | @Test
public void test_bearingTo_east() {
final GeoPoint target = new GeoPoint(0.0, 0.0);
final GeoPoint other = new GeoPoint(0.0, 10.0);
assertEquals("directly east", 90, Math.round(target.bearingTo(other)));
} |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
if (isGrayImage(image))
{
return createFromGrayImage(image, document);
}
// We try to encode the image with predictor
if (USE_PREDICTOR_ENCODER... | @Test
void testCreateLosslessFromImageUSHORT_555_RGB() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));
// create an USHORT_555_RGB image
int w = image.getWidth();
int h = ima... |
@DeleteMapping("/rule")
public ShenyuAdminResult deleteRule(@RequestBody @Valid @NotNull final DataPermissionDTO dataPermissionDTO) {
return ShenyuAdminResult.success(ShenyuResultMessage.DELETE_SUCCESS, dataPermissionService.deleteRule(dataPermissionDTO));
} | @Test
public void deleteRule() throws Exception {
DataPermissionDTO dataPermissionDTO = new DataPermissionDTO();
dataPermissionDTO.setDataId("testDataId");
dataPermissionDTO.setUserId("testUserId");
given(this.dataPermissionService.deleteRule(dataPermissionDTO)).willReturn(1);
... |
@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 shouldThrowOnSerializingKeyError() {
// Given:
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
allAndPseudoColumnNames(SCHEMA),
ImmutableList.of(
new LongLiteral(1L),
new StringLiteral("str"),
new StringLiteral("str")... |
@Override
public long localCountForNode(String nodeId) {
final List<BasicDBObject> forThisNode = ImmutableList.of(new BasicDBObject(MessageInput.FIELD_NODE_ID, nodeId));
final List<BasicDBObject> query = ImmutableList.of(
new BasicDBObject(MessageInput.FIELD_GLOBAL, false),
... | @Test
@MongoDBFixtures("InputServiceImplTest.json")
public void localCountForNodeReturnsNumberOfLocalInputs() {
assertThat(inputService.localCountForNode("cd03ee44-b2a7-cafe-babe-0000deadbeef")).isEqualTo(2);
assertThat(inputService.localCountForNode("cd03ee44-b2a7-0000-0000-000000000000")).isEq... |
@Override
public Optional<OffsetExpirationCondition> offsetExpirationCondition() {
if (protocolType.isPresent()) {
if (isInState(EMPTY)) {
// No members exist in the group =>
// - If current state timestamp exists and retention period has passed since group became... | @Test
public void testOffsetExpirationCondition() {
long currentTimestamp = 30000L;
long commitTimestamp = 20000L;
long offsetsRetentionMs = 10000L;
OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(15000L, OptionalInt.empty(), "", commitTimestamp, OptionalLong.empty());
... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
public void testRequestVeryOldUpdateCompatibility() {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline.getOptions().as(StreamingOptions.class).setUpdateCompatibilityVersion("2.46.0");
pipeline.apply(Create.of(KV.of("arbitrary", "kv"))).apply(Reshuffle.of());
OldTransformSeeker seeker = ... |
public Set<String> getResourceNamesByCapacityType(
ResourceUnitCapacityType capacityType) {
return new HashSet<>(capacityTypePerResource.getOrDefault(capacityType,
Collections.emptySet()));
} | @Test
public void getResourceNamesByCapacityType() {
QueueCapacityVector capacityVector = QueueCapacityVector.newInstance();
capacityVector.setResource(MEMORY_URI, 10, ResourceUnitCapacityType.PERCENTAGE);
capacityVector.setResource(VCORES_URI, 6, ResourceUnitCapacityType.PERCENTAGE);
// custom is n... |
@Override
public String resolveExtensionVersion(String pluginId, String extensionType, final List<String> goSupportedExtensionVersions) {
List<String> pluginSupportedVersions = getRequiredExtensionVersionsByPlugin(pluginId, extensionType);
String resolvedExtensionVersion = "0";
for (String p... | @Test
void shouldThrowExceptionIfMatchingExtensionVersionNotFound() {
String pluginId = "plugin-id";
String extensionType = "sample-extension";
GoPlugin goPlugin = mock(GoPlugin.class);
GoPlugginOSGiFrameworkStub osGiFrameworkStub = new GoPlugginOSGiFrameworkStub(goPlugin);
o... |
public File dumpHeap()
throws MalformedObjectNameException, InstanceNotFoundException, ReflectionException,
MBeanException, IOException {
return dumpHeap(localDumpFolder);
} | @Test
public void heapDumpTwice() throws Exception {
File folder = tempFolder.newFolder();
File dump1 = MemoryMonitor.dumpHeap(folder);
assertNotNull(dump1);
assertTrue(dump1.exists());
assertThat(dump1.getParentFile(), Matchers.equalTo(folder));
File dump2 = MemoryMonitor.dumpHeap(folder);
... |
static Point projectPointAtNewTime(Point point, Instant newTime) {
//skip projection when data doesn't support it
if (point.speed() == null || point.course() == null) {
return new PointBuilder(point).time(newTime).build();
}
Duration timeDelta = Duration.between(point.time(... | @Test
public void testProjectPointAtNewTime_backwardInTime() {
//1 knot -- due east
Point testPoint = (new PointBuilder())
.time(Instant.EPOCH)
.latLong(0.0, 0.0)
.altitude(Distance.ofFeet(0.0))
.speedInKnots(1.0)
.courseInDegrees(90.0)
... |
@Override
public Object getValue() {
try {
return mBeanServerConn.getAttribute(getObjectName(), attributeName);
} catch (IOException e) {
return null;
} catch (JMException e) {
return null;
}
} | @Test
public void returnsNullIfMBeanNotFound() throws Exception {
ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean");
JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount");
assertThat(gauge.getValue()).isNull();
} |
public B token(String token) {
this.token = token;
return getThis();
} | @Test
void token() {
ServiceBuilder builder = new ServiceBuilder();
builder.token("token");
Assertions.assertEquals("token", builder.build().getToken());
} |
@Override
public void accept(final MeterEntity entity, final DataTable value) {
this.entityId = entity.id();
this.serviceId = entity.serviceId();
this.value.append(value);
} | @Test
public void testAccept() {
function.accept(
MeterEntity.newService("service-test", Layer.GENERAL),
HTTP_CODE_COUNT_1
);
function.accept(
MeterEntity.newService("service-test", Layer.GENERAL),
HTTP_CODE_COUNT_2
);
Assertio... |
static void valueMustBeValid(EvaluationContext ctx, Object value) {
if (!(value instanceof BigDecimal) && !(value instanceof LocalDate)) {
ctx.notifyEvt(() -> new ASTEventBase(FEELEvent.Severity.ERROR, Msg.createMessage(Msg.VALUE_X_NOT_A_VALID_ENDPOINT_FOR_RANGE_BECAUSE_NOT_A_NUMBER_NOT_A_DATE, valu... | @Test
void valueMustBeValidTrueTest() {
valueMustBeValid(ctx, BigDecimal.valueOf(1));
verify(listener, never()).onEvent(any(FEELEvent.class));
valueMustBeValid(ctx, LocalDate.of(2021, 1, 3));
verify(listener, never()).onEvent(any(FEELEvent.class));
} |
protected static void checkJavaVersion(final PrintStream logger, String javaCommand,
final BufferedReader r)
throws IOException {
String line;
Pattern p = Pattern.compile("(?i)(?:java|openjdk) version \"([0-9.]+).*\".*");
while (null != (line = r.r... | @Test public void jdk5() {
assertThrows(
IOException.class,
() ->
ComputerLauncher.checkJavaVersion(
new PrintStream(OutputStream.nullOutputStream()),
"-",
new BufferedReader(
new StringRe... |
@Override
public void scrubRegistrationProperties() {
if (!exist()) {
return;
}
try {
PropertiesConfiguration config = new PropertiesConfiguration();
config.setIOFactory(new FilteringOutputWriterFactory());
PropertiesConfigurationLayout layout ... | @Test
void shouldScrubTheAutoRegistrationProperties() throws Exception {
String originalContents = """
#
# file autogenerated by chef, any changes will be lost
#
# the registration key
agent.auto.register.key = some secret key
... |
@Override
public HttpResponseOutputStream<BaseB2Response> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
// Submit store call to background thread
final DelayedHttpEntityCallable<BaseB2Response> command = new DelayedHttpEntityCalla... | @Test
public void testWriteChecksumFailure() throws Exception {
final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
final TransferStatus status = new T... |
@VisibleForTesting
static OptionalDouble calculateAverageSizePerPartition(Collection<PartitionStatistics> statistics)
{
return statistics.stream()
.map(PartitionStatistics::getBasicStatistics)
.map(HiveBasicStatistics::getInMemoryDataSizeInBytes)
.filter(O... | @Test
public void testCalculateAverageSizePerPartition()
{
assertThat(calculateAverageSizePerPartition(ImmutableList.of())).isEmpty();
assertThat(calculateAverageSizePerPartition(ImmutableList.of(PartitionStatistics.empty()))).isEmpty();
assertThat(calculateAverageSizePerPartition(Immuta... |
@Override
public long getMax() {
if (values.length == 0) {
return 0;
}
return values[values.length - 1];
} | @Test
public void calculatesAMaxOfZeroForAnEmptySnapshot() throws Exception {
final Snapshot emptySnapshot = new WeightedSnapshot(
WeightedArray(new long[]{}, new double[]{}) );
assertThat(emptySnapshot.getMax())
.isZero();
} |
@Override
public StageBundleFactory forStage(ExecutableStage executableStage) {
return new SimpleStageBundleFactory(executableStage);
} | @Test
public void createsMultipleEnvironmentOfSingleType() throws Exception {
ServerFactory serverFactory = ServerFactory.createDefault();
Environment environmentA =
Environment.newBuilder()
.setUrn("env:urn:a")
.setPayload(ByteString.copyFrom(new byte[1]))
.build(... |
public static CharSequence commonPrefix(CharSequence str1, CharSequence str2) {
if (isEmpty(str1) || isEmpty(str2)) {
return EMPTY;
}
final int minLength = Math.min(str1.length(), str2.length());
int index = 0;
for (; index < minLength; index++) {
if (str1.charAt(index) != str2.charAt(index)) {
b... | @Test
public void commonPrefixTest() throws Exception{
// -------------------------- None match -----------------------
assertEquals("", CharSequenceUtil.commonPrefix("", "abc"));
assertEquals("", CharSequenceUtil.commonPrefix(null, "abc"));
assertEquals("", CharSequenceUtil.commonPrefix("abc", null));
ass... |
public static String removeIdentifierFromMetadataURL(String metadataURL) {
MetadataStoreProvider provider = findProvider(metadataURL);
if (metadataURL.startsWith(provider.urlScheme() + ":")) {
return metadataURL.substring(provider.urlScheme().length() + 1);
}
return metadataU... | @Test
public void testRemoveIdentifierFromMetadataURL() {
assertEquals(MetadataStoreFactoryImpl.removeIdentifierFromMetadataURL("zk:host:port"), "host:port");
assertEquals(MetadataStoreFactoryImpl.removeIdentifierFromMetadataURL("rocksdb:/data/dir"), "/data/dir");
assertEquals(MetadataStoreF... |
public static boolean isBasicInfoChanged(Member actual, Member expected) {
if (null == expected) {
return null != actual;
}
if (!expected.getIp().equals(actual.getIp())) {
return true;
}
if (expected.getPort() != actual.getPort()) {
return true... | @Test
void testIsBasicInfoChangedNoChangeWithExtendInfo() {
Member newMember = buildMember();
newMember.setExtendVal("test", "test");
assertFalse(MemberUtil.isBasicInfoChanged(newMember, originalMember));
} |
@SuppressWarnings("deprecation")
public static void setupDistributedCache(Configuration conf,
Map<String, LocalResource> localResources) throws IOException {
LocalResourceBuilder lrb = new LocalResourceBuilder();
lrb.setConf(conf);
// Cache archives
lrb.setType(LocalResourceType.ARCHIVE);
... | @SuppressWarnings("deprecation")
@Test
@Timeout(30000)
public void testSetupDistributedCache() throws Exception {
Configuration conf = new Configuration();
conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class);
URI mockUri = URI.create("mockfs://mock/");
FileSystem mockFs = ((Fi... |
protected void grantRoleToUser(List<String> parentRoleName, UserIdentity user) throws PrivilegeException {
userWriteLock();
try {
UserPrivilegeCollectionV2 userPrivilegeCollection = getUserPrivilegeCollectionUnlocked(user);
roleReadLock();
try {
for (... | @Test
public void testGrantRoleToUser() throws Exception {
CreateUserStmt createUserStmt = (CreateUserStmt) UtFrameUtils.parseStmtWithNewParser(
"create user test_role_user", ctx);
ctx.getGlobalStateMgr().getAuthenticationMgr().createUser(createUserStmt);
UserIdentity testUse... |
@Override
@TpsControl(pointName = "ConfigQuery")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException {
... | @Test
void testGetConfigNotExistAndConflict() throws Exception {
String dataId = "dataId" + System.currentTimeMillis();
String group = "group" + System.currentTimeMillis();
String tenant = "tenant" + System.currentTimeMillis();
//test config not exist
configCacheServ... |
public HttpRequest body(String body) {
return this.body(body, null);
} | @Test
@Disabled
public void bodyTest() {
final String ddddd1 = HttpRequest.get("https://baijiahao.baidu.com/s").body("id=1625528941695652600").execute().body();
Console.log(ddddd1);
} |
@Override
public void execute(Context context) {
editionProvider.get().ifPresent(edition -> {
if (!edition.equals(EditionProvider.Edition.COMMUNITY)) {
return;
}
Map<String, Integer> filesPerLanguage = reportReader.readMetadata().getNotAnalyzedFilesByLanguageMap()
.entrySet()
... | @Test
public void add_warning_and_measures_in_SQ_community_edition_if_there_are_c_or_cpp_files() {
when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY));
ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build();
Scann... |
public static byte[] nullToEmpty(final byte[] bytes) {
return bytes == null ? EMPTY_BYTES : bytes;
} | @Test
public void testNullToEmpty() {
Assert.assertArrayEquals(new byte[] {}, BytesUtil.nullToEmpty(null));
Assert.assertArrayEquals(new byte[] { 1, 2 }, BytesUtil.nullToEmpty(new byte[] { 1, 2 }));
} |
public List<InterpreterResultMessage> message() {
return msg;
} | @Test
void testComplexMagicType() {
InterpreterResult result = null;
result = new InterpreterResult(InterpreterResult.Code.SUCCESS,
"some text before %table col1\tcol2\naaa\t123\n");
assertEquals(InterpreterResult.Type.TEXT, result.message().get(0).getType(),
"some text before magic retur... |
@Udf
public int instr(final String str, final String substring) {
return instr(str, substring, 1);
} | @Test
public void shouldReturnZeroWhenSubstringNotFound() {
assertThat(udf.instr("CORPORATE FLOOR", "ABC"), is(0));
} |
@Override
public Set<Path> getPaths(ElementId src, ElementId dst) {
return super.getPaths(src, dst, (LinkWeigher) null);
} | @Test(expected = NullPointerException.class)
public void testGetPathsWithNullDest() {
VirtualNetwork vnet = setupVnet();
PathService pathService = manager.get(vnet.id(), PathService.class);
pathService.getPaths(DID1, null);
} |
public static int CCITT_Kermit(@NonNull final byte[] data, final int offset, final int length) {
return CRC(0x1021, 0x0000, data, offset, length, true, true, 0x0000);
} | @Test
public void CCITT_Kermit_empty() {
final byte[] data = new byte[0];
assertEquals(0x0000, CRC16.CCITT_Kermit(data, 0, 1));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.