focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public UserDefinedFunctionDescriptor(String name, String classpath) {
this.name = name;
this.classpath = classpath;
this.className = classpath.substring(classpath.lastIndexOf('.') + 1);
try {
Class<?> clazz = Class.forName(classpath);
isCdcPipelineUdf = isCdcPipel... | @Test
void testUserDefinedFunctionDescriptor() {
assertThat(new UserDefinedFunctionDescriptor("cdc_udf", CdcUdf.class.getName()))
.extracting("name", "className", "classpath", "returnTypeHint", "isCdcPipelineUdf")
.containsExactly(
"cdc_udf",
... |
@Override
public void configure(Map<String, ?> configs) {
super.configure(configs);
configureSamplingInterval(configs);
configurePrometheusAdapter(configs);
configureQueryMap(configs);
} | @Test(expected = ConfigException.class)
public void testGetSamplesWithCustomNegativeSamplingInterval() throws Exception {
Map<String, Object> config = new HashMap<>();
config.put(PROMETHEUS_SERVER_ENDPOINT_CONFIG, "http://kafka-cluster-1.org:9090");
config.put(PROMETHEUS_QUERY_RESOLUTION_STE... |
@Field
public void setExtractInlineImageMetadataOnly(boolean extractInlineImageMetadataOnly) {
defaultConfig.setExtractInlineImageMetadataOnly(extractInlineImageMetadataOnly);
} | @Test
public void testExtractInlineImageMetadata() throws Exception {
ParseContext context = new ParseContext();
PDFParserConfig config = new PDFParserConfig();
config.setExtractInlineImageMetadataOnly(true);
context.set(PDFParserConfig.class, config);
List<Metadata> metadata... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testGroupStuckInRebalanceTimeoutDueToNonjoinedStaticMember() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
int longSessionTimeoutMs = 10000;
int rebalanceTimeoutMs = 5000;
GroupMetada... |
public static Calendar getCalendar(Object date, Calendar defaultValue) {
Calendar cal = new GregorianCalendar();
if (date instanceof java.util.Date) {
cal.setTime((java.util.Date) date);
return cal;
} else if (date != null) {
Optional<Date> d = tryToParseDate(... | @Test
public void testGetCalendarObjectCalendarWithInvalidStringAndNullDefault() {
assertNull(Converter.getCalendar("invalid date", null));
} |
@Override
public void setAll(Properties properties) {
@SuppressWarnings("unchecked") Enumeration<String> names =
(Enumeration<String>) properties.propertyNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
Property property = Propert... | @Test
public void testSetAll() {
Properties props = new Properties();
props.put(TikaCoreProperties.FORMAT.getName(), "format");
props.put(TikaCoreProperties.SUBJECT.getName(), "keyword");
xmpMeta.setAll(props);
assertEquals("format", xmpMeta.get(TikaCoreProperties.FORMAT));... |
@Override
public boolean advanceBy(long amount, TimeUnit unit) {
return advanceTo(SystemClock.uptimeMillis() + unit.toMillis(amount));
} | @Test
public void advanceBy() {
Runnable runnable = mock(Runnable.class);
new Handler(getMainLooper()).postDelayed(runnable, 100);
verify(runnable, times(0)).run();
assertThat(scheduler.advanceBy(100, TimeUnit.MILLISECONDS)).isTrue();
verify(runnable, times(1)).run();
} |
@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 (windowedInnerClassSe... | @Test
public void shouldThrowConfigExceptionWhenInvalidWindowInnerClassSerialiserSupplied() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class");
assertThrows(ConfigException.class, () -> sessionWindowedSerializer.configure(props, false));
} |
@Override
public String getOperationName(Exchange exchange, Endpoint endpoint) {
// Based on HTTP component documentation:
return getHttpMethod(exchange, endpoint);
} | @Test
public void testGetOperationName() {
Exchange exchange = Mockito.mock(Exchange.class);
Message message = Mockito.mock(Message.class);
Mockito.when(exchange.getIn()).thenReturn(message);
Mockito.when(message.getHeader(Exchange.HTTP_METHOD)).thenReturn("PUT");
SpanDecor... |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfByteArrayNegativePrefixLengthIPv6() {
IpPrefix ipPrefix;
byte[] value;
value = new byte[] {0x11, 0x11, 0x22, 0x22,
0x33, 0x33, 0x44, 0x44,
0x55, 0x55, 0x66,... |
@VisibleForTesting
static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) {
final List<MemoryPoolMXBean> memoryPoolMXBeans =
ManagementFactory.getMemoryPoolMXBeans().stream()
.filter(bean -> "Metaspace".equals(bean.getName()))
... | @Test
void testMetaspaceMetricUsageNotStatic() throws Exception {
assertThat(hasMetaspaceMemoryPool())
.withFailMessage("Requires JVM with Metaspace memory pool")
.isTrue();
final InterceptingOperatorMetricGroup metaspaceMetrics =
new InterceptingOper... |
@Operation(summary = "queryAccessTokenList", description = "QUERY_ACCESS_TOKEN_LIST_NOTES")
@Parameters({
@Parameter(name = "searchVal", description = "SEARCH_VAL", schema = @Schema(implementation = String.class)),
@Parameter(name = "pageNo", description = "PAGE_NO", required = true, schema ... | @Test
public void testQueryAccessTokenList() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("pageNo", "1");
paramsMap.add("pageSize", "20");
paramsMap.add("searchVal", "");
MvcResult mvcResult = mockMvc.perform(get("/ac... |
@Override
public void startIt() {
if (semaphore.tryAcquire()) {
try {
executorService.execute(this::doDatabaseMigration);
} catch (RuntimeException e) {
semaphore.release();
throw e;
}
} else {
LOGGER.trace("{}: lock is already taken or process is already runnin... | @Test
public void status_is_FAILED_and_failure_stores_the_exception_when_trigger_throws_an_exception() {
mockMigrationThrowsError();
underTest.startIt();
assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.FAILED);
assertThat(migrationState.getError()).get().isSameAs(AN_ER... |
public boolean isCombo()
{
return getCOSObject().getFlag(COSName.FF, FLAG_COMBO);
} | @Test
void createListBox()
{
PDChoice choiceField = new PDListBox(acroForm);
assertEquals(choiceField.getFieldType(), choiceField.getCOSObject().getNameAsString(COSName.FT));
assertEquals("Ch", choiceField.getFieldType());
assertFalse(choiceField.isCombo());
} |
@Override
public String buildContext() {
final PluginDO after = (PluginDO) getAfter();
if (Objects.isNull(getBefore())) {
return String.format("the plugin [%s] is %s", after.getName(), StringUtils.lowerCase(getType().getType().toString()));
}
return String.format("the plu... | @Test
public void updatePluginBuildContextTest() {
String eventTypeStr = StringUtils.lowerCase(EventTypeEnum.PLUGIN_UPDATE.getType().toString());
PluginChangedEvent pluginUpdateEventWithoutChange = new PluginChangedEvent(pluginDO, pluginDO, EventTypeEnum.PLUGIN_UPDATE, "test-operator");
Stri... |
@Override
public Expression createExpression(Expression source, String expression, Object[] properties) {
return doCreateJsonPathExpression(source, expression, properties, false);
} | @Test
public void testUnpackJsonArray() {
Exchange exchange = new DefaultExchange(context);
exchange.getIn().setBody(new File("src/test/resources/expensive.json"));
JsonPathLanguage language = (JsonPathLanguage) context.resolveLanguage("jsonpath");
Expression expression = language.... |
@Override
public DescribeConsumerGroupsResult describeConsumerGroups(final Collection<String> groupIds,
final DescribeConsumerGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, ConsumerGroupDescription> future =
Descri... | @Test
public void testDescribeOldAndNewConsumerGroups() throws Exception {
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
env.kafkaClient().prepareResponse(new FindCoordinatorResponse... |
public boolean hasAnyMethodHandlerAnnotation() {
return !operationsWithHandlerAnnotation.isEmpty();
} | @Test
public void testHandlerOnDerived() {
BeanInfo info = new BeanInfo(context, MyDerivedClass.class);
assertFalse(info.hasAnyMethodHandlerAnnotation());
} |
public static void unmap(String resourceDescription, ByteBuffer buffer) throws IOException {
if (!buffer.isDirect())
throw new IllegalArgumentException("Unmapping only works with direct buffers");
if (UNMAP == null)
throw UNMAP_NOT_SUPPORTED_EXCEPTION;
try {
... | @Test
public void testUnmap() throws Exception {
File file = TestUtils.tempFile();
try (FileChannel channel = FileChannel.open(file.toPath())) {
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, 0);
ByteBufferUnmapper.unmap(file.getAbsolutePath(), map);
... |
public static <K> KTableHolder<K> build(
final KTableHolder<K> table,
final TableFilter<K> step,
final RuntimeBuildContext buildContext) {
return build(table, step, buildContext, SqlPredicate::new);
} | @Test
public void shouldBuildSqlPredicateCorrectly() {
// When:
step.build(planBuilder, planInfo);
// Then:
verify(predicateFactory).create(
filterExpression,
schema,
ksqlConfig,
functionRegistry
);
} |
@Override
public void recordStateMachineFinished(StateMachineInstance machineInstance, ProcessContext context) {
if (machineInstance != null) {
try {
// save to db
Map<String, Object> endParams = machineInstance.getEndParams();
if (endParams != nul... | @Test
public void testRecordStateMachineFinished() {
DbAndReportTcStateLogStore dbAndReportTcStateLogStore = new DbAndReportTcStateLogStore();
StateMachineInstanceImpl stateMachineInstance = new StateMachineInstanceImpl();
ProcessContextImpl context = new ProcessContextImpl();
contex... |
@Override
public void setIndex(int readerIndex, int writerIndex) {
if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) {
throw new IndexOutOfBoundsException();
}
this.readerIndex = readerIndex;
this.writerIndex = writerIndex;
} | @Test
void setIndexBoundaryCheck2() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.setIndex(CAPACITY / 2, CAPACITY / 4));
} |
@SuppressWarnings({"checkstyle:CyclomaticComplexity", "checkstyle:FinalParameters"})
protected static int send(
final String customerId, final byte[] bytes, final HttpPost httpPost, final HttpHost proxy,
CloseableHttpClient httpClient, final ResponseHandler responseHandler
) {
int statusCode = DEFAU... | @Test
public void testSubmitIgnoresEmptyInput() {
// Given
HttpPost p = mock(HttpPost.class);
byte[] emptyData = new byte[0];
// When
WebClient.send(customerId, emptyData, p, null);
// Then
verifyNoMoreInteractions(p);
} |
public static List<String> finalDestination(List<String> elements) {
if (isMagicPath(elements)) {
List<String> destDir = magicPathParents(elements);
List<String> children = magicPathChildren(elements);
checkArgument(!children.isEmpty(), "No path found under the prefix " +
MAGIC_PATH_PREF... | @Test
public void testFinalDestinationRootMagic2() {
assertEquals(l("3.txt"),
finalDestination(l(MAGIC_PATH_PREFIX, "2", "3.txt")));
} |
@Override
public void onElement(OnElementContext c) throws Exception {
getRepeated(c).invokeOnElement(c);
} | @Test
public void testOnElement() throws Exception {
setUp(FixedWindows.of(Duration.millis(10)));
tester.injectElements(37);
verify(mockTrigger).onElement(Mockito.any());
} |
public ShardingSphereSchema getSchema(final String schemaName) {
return schemas.get(schemaName);
} | @Test
void assertGetSchema() {
DatabaseType databaseType = mock(DatabaseType.class);
RuleMetaData ruleMetaData = mock(RuleMetaData.class);
ShardingSphereSchema schema = mock(ShardingSphereSchema.class);
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", databaseTy... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldThrowIfCsasKeyFormatDoesnotSupportInference() {
// Given:
givenFormatsAndProps("kafka", null,
ImmutableMap.of("KEY_SCHEMA_ID", new IntegerLiteral(42)));
givenDDLSchemaAndFormats(LOGICAL_SCHEMA, "kafka", "avro",
SerdeFeature.WRAP_SINGLES, SerdeFeature.UNWRAP_SINGLES)... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void unpinChatMessage() {
BaseResponse response = bot.execute(new UnpinChatMessage(groupId).messageId(3600));
assertTrue(response.isOk());
} |
public static String getGroupKey(ThreadPoolParameter parameter) {
return StringUtil.createBuilder()
.append(parameter.getTpId())
.append(Constants.GROUP_KEY_DELIMITER)
.append(parameter.getItemId())
.append(Constants.GROUP_KEY_DELIMITER)
... | @Test
public void assertGetGroupKey() {
String testText = "message-consume+dynamic-threadpool-example+prescription";
ThreadPoolParameterInfo parameter = ThreadPoolParameterInfo.builder()
.tenantId("prescription").itemId("dynamic-threadpool-example").tpId("message-consume").build();
... |
public static Level toLevel(String sArg) {
return toLevel(sArg, Level.DEBUG);
} | @Test
public void smoke() {
assertEquals(Level.TRACE, Level.toLevel("TRACE"));
assertEquals(Level.DEBUG, Level.toLevel("DEBUG"));
assertEquals(Level.INFO, Level.toLevel("INFO"));
assertEquals(Level.WARN, Level.toLevel("WARN"));
assertEquals(Level.ERROR, Level.toLevel("ERROR")... |
public ServiceBuilder<U> addMethods(List<? extends MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
} | @Test
void addMethods() {
MethodConfig method = new MethodConfig();
ServiceBuilder builder = new ServiceBuilder();
builder.addMethods(Collections.singletonList(method));
Assertions.assertTrue(builder.build().getMethods().contains(method));
Assertions.assertEquals(1, builder.b... |
@Description("Get the plan ids of given plan node")
@ScalarFunction("json_presto_query_plan_ids")
@SqlType("ARRAY<VARCHAR>")
@SqlNullable
public static Block jsonPlanIds(@TypeParameter("ARRAY<VARCHAR>") ArrayType arrayType,
@SqlType(StandardTypes.JSON) Slice jsonPlan)
{
List<Json... | @Test
public void testJsonPlanIds()
{
assertFunction("json_presto_query_plan_ids(null)", new ArrayType(VARCHAR), null);
assertFunction("json_presto_query_plan_ids(json '" +
TestJsonPrestoQueryPlanFunctionUtils.joinPlan.replaceAll("'", "''") + "')",
new Ar... |
public static Object remove(Object root, DataIterator it)
{
DataElement element;
// construct the list of Data objects to remove
// don't remove in place because iterator behavior with removals while iterating is undefined
ArrayList<ToRemove> removeList = new ArrayList<>();
while ((element = it.n... | @Test
public void testRemoveByPredicateWithPostOrder() throws Exception
{
SimpleTestData data = IteratorTestData.createSimpleTestData();
SimpleDataElement el = data.getDataElement();
Builder.create(el.getValue(), el.getSchema(), IterationOrder.POST_ORDER)
.filterBy(Predicates.pathMatchesPathSpe... |
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) {
if (msgs instanceof CodecOutputList) {
fireChannelRead(ctx, (CodecOutputList) msgs, numElements);
} else {
for (int i = 0; i < numElements; i++) {
ctx.fireChannelRead(msgs... | @Test
public void testDoesNotOverReadOnChannelReadComplete() {
ReadInterceptingHandler interceptor = new ReadInterceptingHandler();
EmbeddedChannel channel = new EmbeddedChannel(interceptor, new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ct... |
@Override
public void abortDm(MdId mdName, MaIdShort maName, MepId mepId)
throws CfmConfigException {
throw new UnsupportedOperationException("Not yet implemented");
} | @Test
public void testAbortOneDm() throws CfmConfigException {
//TODO: Implement underlying method
try {
soamManager.abortDm(MDNAME1, MANAME1, MEPID1, DMID101);
fail("Expecting UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void AcGroupAccessControlRight() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaimsGroup("stevehu", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("account.r", "account.w"), "admin frontOffice");
claims.setExpirationTimeMinutesInTheFuture(5256000);
... |
@Override
public boolean isInstalled(final Application application) {
synchronized(NSWorkspace.class) {
if(Application.notfound.equals(application)) {
return false;
}
return workspace.absolutePathForAppBundleWithIdentifier(
application.getI... | @Test
public void testInstalled() {
ApplicationFinder f = new LaunchServicesApplicationFinder();
assertTrue(f.isInstalled(new Application("com.apple.Preview", "Preview")));
assertFalse(f.isInstalled(new Application("com.apple.Preview_", "Preview")));
assertFalse(f.isInstalled(Applica... |
@Override
public void onRollbackFailure(GlobalTransaction tx, Throwable originalException) {
LOGGER.warn("Failed to rollback transaction[" + tx.getXid() + "]", originalException);
TIMER.newTimeout(new DefaultFailureHandlerImpl.CheckTimerTask(tx, GlobalStatus.Rollbacked),
SCHEDULE_INTERVA... | @Test
void onRollbackFailure() throws Exception {
RootContext.bind(DEFAULT_XID);
DefaultGlobalTransaction tx = (DefaultGlobalTransaction)GlobalTransactionContext.getCurrentOrCreate();
FailureHandler failureHandler = new DefaultFailureHandlerImpl();
failureHandler.onRollbackFailure... |
public static String format(LocalDateTime localDateTime, String format) {
return LocalDateTimeUtil.format(localDateTime, format);
} | @Test
public void formatSpeedTest(){
Date value = new Date();
//long t0 = System.currentTimeMillis();
//此处先加载FastDateFormat对象,保存到FastDateFormat.CACHE中
//解决后面两个for循环中保存到FastDateFormat对象创建未时差异的问题。
FastDateFormat.getInstance("YYYY-MM-dd HH:mm:ss.SSS");
long t1 = System.currentTimeMillis();
String strTime =... |
private void extractLinks(Page page, Selector urlRegionSelector, List<Pattern> urlPatterns) {
List<String> links;
if (urlRegionSelector == null) {
links = page.getHtml().links().all();
} else {
links = page.getHtml().selectList(urlRegionSelector).links().all();
}
... | @Test
public void testExtractLinks() throws Exception {
ModelPageProcessor modelPageProcessor = ModelPageProcessor.create(null, MockModel.class);
Page page = pageMocker.getMockPage();
modelPageProcessor.process(page);
assertThat(page.getTargetRequests()).containsExactly(new Request("... |
public String getUuid() {
return toString();
} | @Test
public void generatesValidType4UUID() {
// Given
Uuid uuid = new Uuid();
// When
String generatedUUID = uuid.getUuid();
// Then
assertTrue(generatedUUID.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"));
} |
@Override
public void onServerStart(Server server) {
List<CoreExtensionBridge> bridges = componentContainer.getComponentsByType(CoreExtensionBridge.class);
for (CoreExtensionBridge bridge : bridges) {
Profiler profiler = Profiler.create(LOGGER).startInfo(format("Bootstrapping %s", bridge.getPluginName()... | @Test
public void onServerStart_calls_startPlugin_if_Bridge_exists_in_container() {
componentContainer.add(bridge);
componentContainer.startComponents();
underTest.onServerStart(mock(Server.class));
verify(bridge).getPluginName();
verify(bridge).startPlugin(componentContainer);
verifyNoMoreI... |
public static Level toLevel(String sArg) {
return toLevel(sArg, Level.DEBUG);
} | @Test
public void smoke( ) {
assertEquals(Level.TRACE, Level.toLevel("TRACE"));
assertEquals(Level.DEBUG, Level.toLevel("DEBUG"));
assertEquals(Level.INFO, Level.toLevel("INFO"));
assertEquals(Level.WARN, Level.toLevel("WARN"));
assertEquals(Level.ERROR, Level.toLevel("ERROR"... |
@Override
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
return new JmsConsumer( stepMeta, stepDataInterface, copyNr, transMeta, trans );
} | @Test
public void withVariablesGetsNewObjectFromRegistry() throws KettleXMLException, KettleMissingPluginsException {
String path = getClass().getResource( "/jms-consumer.ktr" ).getPath();
TransMeta transMeta = new TransMeta( path, new Variables() );
StepMeta step = transMeta.getStep( 0 );
JmsConsumer... |
@Async
public void sendAfnemersBerichtAanDGL(AfnemersberichtAanDGL afnemersberichtAanDGL, Afnemersbericht afnemersbericht){
boolean success = digileveringClient.sendRequest(afnemersberichtAanDGL);
afnemersbericht.setStatus(success ? Afnemersbericht.Status.PENDING : Afnemersbericht.Status.SEND_FAILED... | @Test
public void testSendAfnemersBerichtAanDGL(){
AfnemersberichtAanDGL afnemersberichtAanDGL = new AfnemersberichtAanDGL();
Afnemersbericht afnemersbericht = new Afnemersbericht();
classUnderTest.sendAfnemersBerichtAanDGL(afnemersberichtAanDGL, afnemersbericht);
verify(digileveri... |
@SuppressWarnings("unchecked")
public <V> V run(String callableName, RetryOperation<V> operation)
{
int attempt = 1;
while (true) {
try {
return operation.run();
}
catch (Exception e) {
if (attempt >= maxAttempts || !retryPredic... | @Test(timeOut = 5000)
public void testBackoffTimeCapped()
{
RetryDriver retryDriver = new RetryDriver(
new RetryConfig()
.setMaxAttempts(5)
.setMinBackoffDelay(new Duration(10, MILLISECONDS))
.setMaxBackoffDelay(new ... |
static int maskChecksum(long checksum) {
return (int) ((checksum >> 15 | checksum << 17) + 0xa282ead8);
} | @Test
public void testMaskChecksum() {
ByteBuf input = Unpooled.wrappedBuffer(new byte[] {
0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00,
0x5f, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65,
0x61, 0x74, 0x5f,
});
assertEquals(0x44a4301f, calculateC... |
@Override
public boolean isContainer(final Path file) {
if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(host))) {
return super.isContainer(file);
}
return false;
} | @Test
public void testContainer() {
assertTrue("/", new S3PathContainerService(new Host(new S3Protocol(), "s3.amazonaws.com")).isContainer(new Path("/b", EnumSet.of(Path.Type.directory))));
assertEquals("b", new S3PathContainerService(new Host(new S3Protocol(), "s3.amazonaws.com")).getContainer(new ... |
public static SegmentGenerationJobSpec getSegmentGenerationJobSpec(String jobSpecFilePath, String propertyFilePath,
Map<String, Object> context, Map<String, String> environmentValues) {
Properties properties = new Properties();
if (propertyFilePath != null) {
try {
properties.load(FileUtils.... | @Test
public void testIngestionJobLauncherWithTemplate() {
Map<String, Object> context =
GroovyTemplateUtils.getTemplateContext(Arrays.asList("year=2020", "month=05", "day=06"));
SegmentGenerationJobSpec spec = IngestionJobLauncher.getSegmentGenerationJobSpec(
GroovyTemplateUtils.class.getClas... |
@Override
public boolean next() throws SQLException {
if (skipAll) {
return false;
}
if (!paginationContext.getActualRowCount().isPresent()) {
return getMergedResult().next();
}
return rowNumber++ <= paginationContext.getActualRowCount().get() && getMe... | @Test
void assertNextForSkipAll() throws SQLException {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(schema);
SQLServerSelectStatement sqlStatement = new SQLServerSelectStatement();
... |
public State currentState() {
return lastState.get().state;
} | @Test
public void currentStateIsNullWhenNotInitialized() {
assertNull(tracker.currentState());
} |
static void setHaConf(String nsId, Configuration conf) {
conf.set(DFSConfigKeys.DFS_NAMESERVICES, nsId);
final String haNNKey = DFS_HA_NAMENODES_KEY_PREFIX + "." + nsId;
conf.set(haNNKey, "nn0,nn1");
final String rpcKey = DFS_NAMENODE_RPC_ADDRESS_KEY + "." + nsId + ".";
conf.set(rpcKey + "nn0", "127... | @Test
public void testHaConf() {
final Configuration conf = new Configuration();
final String nsId = "cluster0";
FsImageValidation.setHaConf(nsId, conf);
Assert.assertTrue(HAUtil.isHAEnabled(conf, nsId));
} |
static void chDir(String workingDir) throws Exception {
CLibrary.chdir(workingDir);
System.setProperty("user.dir", workingDir);
// change current dir for the java.io.File class
Class<?> fileClass = Class.forName("java.io.File");
if (JavaVersion.getJavaSpec() >= 11.0) {
... | @Test
void testChdir() throws Exception {
File d = new File("target/tstDir").getAbsoluteFile();
d.mkdirs();
EnvHelper.chDir(d.toString());
assertEquals(new File(d, "test").getAbsolutePath(), new File("test").getAbsolutePath());
assertEquals(
d.toPath().resolve... |
public static ColumnName generateSyntheticJoinKey(final Stream<LogicalSchema> schemas) {
final AliasGenerator generator = buildAliasGenerators(schemas)
.getOrDefault(
SYNTHETIC_JOIN_KEY_COLUMN_PRIFIX,
new AliasGenerator(0, SYNTHETIC_JOIN_KEY_COLUMN_PRIFIX, ImmutableSet.of())
... | @Test
public void shouldDefaultToRowKeySyntheticJoinColumn() {
// When:
final ColumnName columnName = ColumnNames.generateSyntheticJoinKey(Stream.of());
// Then:
assertThat(columnName, is(ColumnName.of("ROWKEY")));
} |
public String getStatisticsForChannel(String subscribeChannel) {
return filterService.getFiltersForChannel(subscribeChannel).stream()
.map(PrioritizedFilter::statistics)
.map(PrioritizedFilterStatistics::toString)
.collect(Collectors.joining(",\n", "[", "]"));
... | @Test
void testGetStatisticsForChannel() {
String channel = "test";
service.getStatisticsForChannel(channel);
Mockito.verify(filterService, Mockito.times(1)).getFiltersForChannel(channel);
} |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null) {
return rule.getInverted();
}
final String value = msg.getField(rule.getField()).toString();
return rule.getInverted() ^ value.trim().equals(rule.getValue());
} | @Test
public void testNullFieldShouldNotMatch() {
final String fieldName = "nullfield";
final StreamRule rule = getSampleRule();
rule.setField(fieldName);
final Message msg = getSampleMessage();
msg.addField(fieldName, null);
final StreamRuleMatcher matcher = getMat... |
public Iterator<V> values() {
return new LongObjectCacheValuesIterator<>(this);
} | @Test
public void cacheIterator() {
LongObjectCache<String> cache = new LongObjectCache<>(4);
cache.put(0, "An IDE");
cache.put(1, "good IDEA");
cache.put(2, "better IDEA");
cache.put(3, "perfect IDEA");
cache.put(4, "IDEAL");
HashSet<String> values = new Hash... |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void group_nodes_are_not_marked_down_if_group_availability_sufficiently_high() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
.reportStorageNodeState(4... |
public void setNewConfiguration(@NonNull Configuration newConfiguration) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mAskAppContext = mAskAppContext.createConfigurationContext(newConfiguration);
}
mPackageContext.clear();
} | @Test
public void testSetNewConfiguration() {
var withLocal = new TestableAddOn("id1", "name111", 8);
Assert.assertSame(getApplicationContext(), withLocal.getPackageContext());
Assert.assertEquals(
1, withLocal.getPackageContext().getResources().getConfiguration().orientation);
var newConfig ... |
@UdafFactory(description = "sum double values in a list into a single double")
public static TableUdaf<List<Double>, Double, Double> sumDoubleList() {
return new TableUdaf<List<Double>, Double, Double>() {
@Override
public Double initialize() {
return 0.0;
}
@Override
publi... | @Test
public void shouldSumDoubleList() {
final TableUdaf<List<Double>, Double, Double> udaf = ListSumUdaf.sumDoubleList();
final Double[] values = new Double[] {1.0, 1.0, 1.0, 1.0, 1.0};
final List<Double> list = Arrays.asList(values);
final Double sum = udaf.aggregate(list, 0.0);
assertThat(5.... |
public void setIncludedCipherSuites(String cipherSuites) {
this.includedCipherSuites = cipherSuites;
} | @Test
public void testSetIncludedCipherSuites() throws Exception {
configurable.setSupportedCipherSuites(new String[] { "A", "B", "C", "D" });
configuration.setIncludedCipherSuites("A,B ,C, D");
configuration.configure(configurable);
assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" },
... |
public void check(List<String> words) throws MnemonicException {
toEntropy(words);
} | @Test(expected = MnemonicException.MnemonicLengthException.class)
public void testEmptyMnemonic() throws Exception {
List<String> words = new ArrayList<>();
mc.check(words);
} |
@Override
public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) {
refreshClassLoader(classLoader);
} | @Test
void testConfig1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "test.package1, test.packag... |
@Override
public void finish() throws IOException {
if (expression != null) {
expression.finish();
}
} | @Test
public void finish() throws IOException {
test.finish();
verify(expr).finish();
verifyNoMoreInteractions(expr);
} |
static void createCompactedTopic(String topicName, short partitions, short replicationFactor, Admin admin) {
NewTopic topicDescription = TopicAdmin.defineTopic(topicName).
compacted().
partitions(partitions).
replicationFactor(replicationFactor).
b... | @Test
public void testCreateCompactedTopicAssumeTopicAlreadyExistsWithUnsupportedVersionException() throws Exception {
Map<String, KafkaFuture<Void>> values = Collections.singletonMap(TOPIC, future);
when(future.get()).thenThrow(new ExecutionException(new UnsupportedVersionException("unsupported")))... |
public void removeSubscription(Topic topic) {
subscriptions.remove(new Subscription(data.clientId(), topic, MqttSubscriptionOption.onlyFromQos(MqttQoS.EXACTLY_ONCE)));
} | @Test
public void testRemoveSubscription() {
client.addSubscriptions(Arrays.asList(new Subscription(CLIENT_ID, new Topic("topic/one"), MqttSubscriptionOption.onlyFromQos(MqttQoS.AT_MOST_ONCE))));
Assertions.assertThat(client.getSubscriptions()).hasSize(1);
client.addSubscriptions(Arrays.asLi... |
@Override
public int getUnstableBars() {
return 0;
} | @Test
public void testUnstableBars() {
KalmanFilterIndicator kalmanIndicator = new KalmanFilterIndicator(closePrice);
Assert.assertEquals(0, kalmanIndicator.getUnstableBars());
} |
public static MetadataUpdate fromJson(String json) {
return JsonUtil.parse(json, MetadataUpdateParser::fromJson);
} | @Test
public void testMetadataUpdateWithoutActionCannotDeserialize() {
List<String> invalidJson =
ImmutableList.of("{\"action\":null,\"format-version\":2}", "{\"format-version\":2}");
for (String json : invalidJson) {
assertThatThrownBy(() -> MetadataUpdateParser.fromJson(json))
.isIn... |
@Override
public CompletableFuture<List<MessageExt>> queryMessage(String address, boolean uniqueKeyFlag, boolean decompressBody,
QueryMessageRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<List<MessageExt>> future = new CompletableFuture<>();
RemotingCommand request = Re... | @Test
public void assertQueryMessageWithNotFound() throws Exception {
when(response.getCode()).thenReturn(ResponseCode.QUERY_NOT_FOUND);
QueryMessageRequestHeader requestHeader = mock(QueryMessageRequestHeader.class);
CompletableFuture<List<MessageExt>> actual = mqClientAdminImpl.queryMessag... |
public static CsvReader getReader(CsvReadConfig config) {
return new CsvReader(config);
} | @Test
public void readTest() {
CsvReader reader = CsvUtil.getReader();
//从文件中读取CSV数据
CsvData data = reader.read(FileUtil.file("test.csv"));
List<CsvRow> rows = data.getRows();
final CsvRow row0 = rows.get(0);
assertEquals("sss,sss", row0.get(0));
assertEquals("姓名", row0.get(1));
assertEquals("性别", row0... |
private MergeSortedPages() {} | @Test
public void testSortingYields()
throws Exception
{
DriverYieldSignal yieldSignal = new DriverYieldSignal();
yieldSignal.forceYieldForTesting();
List<Type> types = ImmutableList.of(INTEGER);
WorkProcessor<Page> mergedPages = MergeSortedPages.mergeSortedPages(
... |
@Override
public TimestampedKeyValueStore<K, V> build() {
KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof TimestampedBytesStore)) {
if (store.persistent()) {
store = new KeyValueToTimestampedKeyValueByteStoreAdapter(store);
} e... | @Test
public void shouldHaveCachingAndChangeLoggingWhenBothEnabled() {
setUp();
final TimestampedKeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.withCachingEnabled()
.build();
final WrappedStateStore caching = (Wr... |
public UserGroupDto addMembership(String groupUuid, String userUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
UserDto userDto = findUserOrThrow(userUuid, dbSession);
GroupDto groupDto = findNonDefaultGroupOrThrow(groupUuid, dbSession);
UserGroupDto userGroupDto = new UserGroupDt... | @Test
public void addMembership_ifGroupNotFound_shouldThrow() {
mockUserDto();
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> groupMembershipService.addMembership(GROUP_A, USER_1))
.withMessage("Group 'group_a' not found");
} |
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception { // NOPMD
// cette méthode est appelée par le conteneur ejb grâce à l'annotation AroundInvoke
if (DISABLED || !EJB_COUNTER.isDisplayed()) {
return context.proceed();
}
// nom identifiant la requête
final String requestName ... | @Test
public void testMonitoringCdi() throws Exception {
final Counter ejbCounter = MonitoringProxy.getEjbCounter();
ejbCounter.clear();
final MonitoringCdiInterceptor interceptor = new MonitoringCdiInterceptor();
ejbCounter.setDisplayed(true);
interceptor.intercept(new InvokeContext(false));
assertSame("... |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
// 0. 初始化积分
MemberUserRespDTO user = memberUserApi.getUser(param.getUserId());
result.setTotalPoint(user.getPoint()).setUsePoint(0);
// 1.1 校验是否使用积分
if (!BooleanUtil.isTrue(pa... | @Test
public void testCalculate_PointStatusFalse() {
// 准备参数
TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
.setUserId(233L).setPointStatus(false) // 是否使用积分
.setItems(asList(
new TradePriceCalculateReqBO.Item().setSkuId(10L).se... |
public static String expandVars(String env) {
OrderedProperties ops = new OrderedProperties();
ops.addStringPairs(env);
Map<String, String> map = ops.asMap();
StringBuilder resultBuilder = new StringBuilder();
for (Map.Entry<String, String> entry: map.entrySet()) {
re... | @Test
public void testVarExpansion() {
String input = "log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\n" +
"log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\n" +
"log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %p %m (%c) [%t]%n\n" +
... |
protected static boolean assertFalse(String string) {
return string == null
|| StringUtils.EMPTY.equals(string)
|| StringUtils.FALSE.equalsIgnoreCase(string)
|| StringUtils.NULL.equals(string);
} | @Test
public void assertFalse() {
Assert.assertTrue(ConfigValueHelper.assertFalse(null));
Assert.assertTrue(ConfigValueHelper.assertFalse(""));
Assert.assertTrue(ConfigValueHelper.assertFalse("fALse"));
Assert.assertTrue(ConfigValueHelper.assertFalse("null"));
Assert.assertFa... |
public void fetchStringValues(String column, int[] inDocIds, int length, String[] outValues) {
_columnValueReaderMap.get(column).readStringValues(inDocIds, length, outValues);
} | @Test
public void testFetchStringValues() {
testFetchStringValues(INT_COLUMN);
testFetchStringValues(LONG_COLUMN);
testFetchStringValues(FLOAT_COLUMN);
testFetchStringValues(DOUBLE_COLUMN);
testFetchStringValues(BIG_DECIMAL_COLUMN);
testFetchStringValues(STRING_COLUMN);
testFetchStringValu... |
@Override
public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() {
return new UnbindChangeProcessor();
} | @Test
public void leftJoinShouldPropagateDeletionOfAPrimaryKey() {
final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>();
leftJoinProcessor.init(context);
context.setRecordMetadata("topic", 0, 0);
leftJoinProcess... |
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated t... | @Test
void getUnversionedProfileNoAuth() {
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier... |
@SuppressWarnings("unchecked")
@Override
protected Object createObject(ValueWrapper<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) {
// simple types
if (initialInstance.isValid() && !(initialInstance.getValue() instanceof Map)) {
... | @Test
public void createObject_directMappingSimpleType() {
Map<List<String>, Object> params = new HashMap<>();
String directMappingSimpleTypeValue = "TestName";
params.put(List.of(), directMappingSimpleTypeValue);
ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(p... |
@Override
public ConfigOperateResult insertOrUpdateBeta(final ConfigInfo configInfo, final String betaIps, final String srcIp,
final String srcUser) {
ConfigInfoStateWrapper configInfo4BetaState = this.findConfigInfo4BetaState(configInfo.getDataId(),
configInfo.getGroup(... | @Test
void testInsertOrUpdateBetaOfException() {
String dataId = "betaDataId113";
String group = "group113";
String tenant = "tenant113";
//mock exist beta
ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper();
mockedConfigInfoStateWrapper... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testImplicitCrossJoin()
{
// TODO: validate output
analyze("SELECT * FROM t1, t2");
} |
public static void cleanBuffer(final ByteBuffer buffer) {
if (null == buffer) {
return;
}
if (!buffer.isDirect()) {
return;
}
PlatformDependent.freeDirectBuffer(buffer);
} | @Test
public void testCleanBuffer() {
UtilAll.cleanBuffer(null);
UtilAll.cleanBuffer(ByteBuffer.allocateDirect(10));
UtilAll.cleanBuffer(ByteBuffer.allocateDirect(0));
UtilAll.cleanBuffer(ByteBuffer.allocate(10));
} |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void lifecycleCheckEndDisabled_shouldRouteThroughOnError() {
TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED);
testSource(resolveScopeFromLifecycle(lifecycle, false))
.assertError(LifecycleEndedException.class);
} |
@Override
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return join(otherStream, toValueJoinerWithKey(joiner), w... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullOtherStreamOnJoinWithStreamJoined() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(
null,
MockValueJoiner.TOSTRING_JOINER... |
public static MonthsWindows months(int number) {
return new MonthsWindows(number, 1, DEFAULT_START_DATE, DateTimeZone.UTC);
} | @Test
public void testMonths() throws Exception {
Map<IntervalWindow, Set<String>> expected = new HashMap<>();
final List<Long> timestamps =
Arrays.asList(
makeTimestamp(2014, 1, 1, 0, 0).getMillis(),
makeTimestamp(2014, 1, 31, 5, 5).getMillis(),
makeTimestamp(2014... |
public Map<String, String> confirm(RdaConfirmRequest params) {
AppSession appSession = appSessionService.getSession(params.getAppSessionId());
AppAuthenticator appAuthenticator = appAuthenticatorService.findByUserAppId(appSession.getUserAppId());
if(!checkSecret(params, appSession) || !checkAcc... | @Test
void checkForeignBsnError(){
appSession.setRdaSessionStatus("SCANNING_FOREIGN");
when(appSessionService.getSession(any())).thenReturn(appSession);
when(appAuthenticatorService.findByUserAppId(any())).thenReturn(appAuthenticator);
when(digidClient.checkBsn(any(),any())).thenRet... |
@Override
protected Source.Reader<T> createReader(@Nonnull FlinkSourceSplit<T> sourceSplit)
throws IOException {
Source<T> beamSource = sourceSplit.getBeamSplitSource();
return createUnboundedSourceReader(beamSource, sourceSplit.getSplitState());
} | @Test
public void testSnapshotStateAndRestore() throws Exception {
final int numSplits = 2;
final int numRecordsPerSplit = 10;
List<FlinkSourceSplit<KV<Integer, Integer>>> splits =
createSplits(numSplits, numRecordsPerSplit, 0);
RecordsValidatingOutput validatingOutput = new RecordsValidating... |
@Override
public PageData<User> findTenantAdmins(UUID tenantId, PageLink pageLink) {
return DaoUtil.toPageData(
userRepository
.findUsersByAuthority(
tenantId,
NULL_UUID,
p... | @Test
public void testFindTenantAdmins() {
PageLink pageLink = new PageLink(20);
PageData<User> tenantAdmins1 = userDao.findTenantAdmins(tenantId, pageLink);
assertEquals(20, tenantAdmins1.getData().size());
pageLink = pageLink.nextPageLink();
PageData<User> tenantAdmins2 = u... |
public static JavaToSqlTypeConverter javaToSqlConverter() {
return JAVA_TO_SQL_CONVERTER;
} | @Test
public void shouldConvertJavaLongToSqlBigInt() {
assertThat(javaToSqlConverter().toSqlType(Long.class), is(SqlBaseType.BIGINT));
} |
public TolerantFloatComparison isNotWithin(float tolerance) {
return new TolerantFloatComparison() {
@Override
public void of(float expected) {
Float actual = FloatSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, e... | @Test
public void isNotWithinOf() {
assertThatIsNotWithinFails(2.0f, 0.0f, 2.0f);
assertThatIsNotWithinFails(2.0f, 0.00001f, 2.0f);
assertThatIsNotWithinFails(2.0f, 1000.0f, 2.0f);
assertThatIsNotWithinFails(2.0f, 1.00001f, 3.0f);
assertThat(2.0f).isNotWithin(0.99999f).of(3.0f);
assertThat(2.0... |
public void restore(final List<Pair<byte[], byte[]>> backupCommands) {
// Delete the command topic
deleteCommandTopicIfExists();
// Create the command topic
KsqlInternalTopicUtils.ensureTopic(commandTopicName, serverConfig, topicClient);
// Restore the commands
restoreCommandTopic(backupComman... | @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT")
@Test
public void shouldThrowIfCannotDeleteTopic() {
// Given:
when(topicClient.isTopicExists(COMMAND_TOPIC_NAME)).thenReturn(true).thenReturn(true);
doThrow(new RuntimeException("denied")).when(topicClient)
.deleteTopics(Collections.... |
@Override
public void getChildren(final String path, final boolean watch, final AsyncCallback.ChildrenCallback cb, final Object ctx)
{
if (!SymlinkUtil.containsSymlink(path))
{
_zk.getChildren(path, watch, cb, ctx);
}
else
{
SymlinkChildrenCallback compositeCallback = new SymlinkChil... | @Test
public void testSymlinkWithChildrenWatcher2() throws ExecutionException, InterruptedException
{
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AsyncCallback.ChildrenCallback callback2 = new AsyncCallback.ChildrenCallback()
{
... |
public static Optional<OP_TYPE> getOpTypeFromTargets(Targets targets, String fieldName) {
if (targets != null && targets.getTargets() != null) {
return targets.getTargets().stream()
.filter(target -> Objects.equals(fieldName,target.getField()) && target.getOpType() != null)
... | @Test
void getOpTypeFromTargets() {
Optional<OP_TYPE> opType = org.kie.pmml.compiler.api.utils.ModelUtils.getOpTypeFromTargets(null, "vsd");
assertThat(opType).isNotNull();
assertThat(opType.isPresent()).isFalse();
final Targets targets = new Targets();
opType = org.kie.pmml.... |
public static String sanitizePath(String path) {
String sanitized = path;
if (path != null) {
sanitized = PATH_USERINFO_PASSWORD.matcher(sanitized).replaceFirst("$1xxxxxx$3");
}
return sanitized;
} | @Test
public void testSanitizePathWithUserInfoAndColonPassword() {
String path = "USERNAME:HARRISON:COLON@sftp.server.test";
String expected = "USERNAME:xxxxxx@sftp.server.test";
assertEquals(expected, URISupport.sanitizePath(path));
} |
@Override
public int hashCode() {
return Arrays.hashCode(components);
} | @Test
public void testEqualsAndHashCode() {
CompositeValue a = value("a", 'a');
assertThat(a).isNotNull();
assertThat(a).isEqualTo(a);
assertThat(value("a", 'a')).isEqualTo(value("a", 'a'));
assertThat(value("a", 'a').hashCode()).isEqualTo(value("a", 'a').hashCode());
... |
@Override
public boolean register(String name, ProcNodeInterface node) {
return false;
} | @Test
public void testRegister() {
Assert.assertFalse(optimizeProcDir.register(null, null));
} |
@Override
public List<OAuth2ApproveDO> getApproveList(Long userId, Integer userType, String clientId) {
List<OAuth2ApproveDO> approveDOs = oauth2ApproveMapper.selectListByUserIdAndUserTypeAndClientId(
userId, userType, clientId);
approveDOs.removeIf(o -> DateUtils.isExpired(o.getExpi... | @Test
public void testGetApproveList() {
// 准备参数
Long userId = 10L;
Integer userType = UserTypeEnum.ADMIN.getValue();
String clientId = randomString();
// mock 数据
OAuth2ApproveDO approve = randomPojo(OAuth2ApproveDO.class).setUserId(userId)
.setUserTyp... |
public static void write(ServiceInfo dom, String dir) {
try {
makeSureCacheDirExists(dir);
File file = new File(dir, dom.getKeyEncoded());
createFileIfAbsent(file, false);
StringBuilder keyContentBuffer = new StringBuilder();
... | @Test
void testWriteCacheWithErrorPath() {
File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded());
try {
file.mkdirs();
DiskCache.write(serviceInfo, CACHE_DIR);
assertTrue(file.isDirectory());
} finally {
file.delete();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.