focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
protected void write(final MySQLPacketPayload payload) {
for (Object each : data) {
if (null == each) {
payload.writeInt1(NULL);
continue;
}
writeDataIntoPayload(payload, each);
}
} | @Test
void assertLocalDateTime() {
String localDateTimeStr = "2021-08-23T17:30:30";
LocalDateTime dateTime = LocalDateTime.parse(localDateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
MySQLTextResultSetRowPacket actual = new MySQLTextResultSetRowPacket(Collections.singleton... |
public static UpdateRequirement fromJson(String json) {
return JsonUtil.parse(json, UpdateRequirementParser::fromJson);
} | @Test
public void testAssertTableDoesNotExistFromJson() {
String requirementType = UpdateRequirementParser.ASSERT_TABLE_DOES_NOT_EXIST;
String json = "{\"type\":\"assert-create\"}";
UpdateRequirement expected = new UpdateRequirement.AssertTableDoesNotExist();
assertEquals(requirementType, expected, Up... |
Subscription addSubscription(final String channel, final int streamId)
{
return addSubscription(channel, streamId, defaultAvailableImageHandler, defaultUnavailableImageHandler);
} | @Test
void addSubscriptionShouldNotifyMediaDriver()
{
whenReceiveBroadcastOnMessage(
ControlProtocolEvents.ON_SUBSCRIPTION_READY,
subscriptionReadyBuffer,
(buffer) ->
{
subscriptionReady.correlationId(CORRELATION_ID);
return... |
@Override
public CompletableFuture<RemovedTaskResult> remove(final TaskId taskId) {
final CompletableFuture<RemovedTaskResult> future = new CompletableFuture<>();
tasksAndActionsLock.lock();
try {
tasksAndActions.add(TaskAndAction.createRemoveTask(taskId, future));
ta... | @Test
public void shouldThrowIfRemovingUpdatingActiveTaskFailsWithStreamsException() throws Exception {
final StreamTask task = statefulTask(TASK_0_0, mkSet(TOPIC_PARTITION_A_0)).inState(State.RESTORING).build();
final StreamsException streamsException = new StreamsException("Something happened", ta... |
@Override
public T next() {
if (this.next != null || hasNext()) {
final T out = this.next;
this.next = null;
return out;
} else {
throw new NoSuchElementException();
}
} | @Test
void testNext() {
try {
// create the resettable Iterator
SpillingResettableIterator<IntValue> iterator =
new SpillingResettableIterator<IntValue>(
this.reader,
this.serializer,
... |
public byte[] encode(String val, String delimiters) {
return codecs[0].encode(val);
} | @Test
public void testEncodeChinesePersonNameUTF8() {
assertArrayEquals(CHINESE_PERSON_NAME_UTF8_BYTES,
utf8().encode(CHINESE_PERSON_NAME_UTF8, PN_DELIMS));
} |
public byte[] getBytes() {
return value.toByteArray();
} | @Test
public void testGetBytes() {
assertArrayEquals("[] equal after getBytes", new byte[] {}, ByteKey.EMPTY.getBytes());
assertArrayEquals("[00] equal after getBytes", new byte[] {0x00}, ByteKey.of(0x00).getBytes());
} |
public static String expandIP(String netAddress, int part) {
netAddress = netAddress.toUpperCase();
// expand netAddress
int separatorCount = StringUtils.countMatches(netAddress, ":");
int padCount = part - separatorCount;
if (padCount > 0) {
StringBuilder padStr = ne... | @Test
public void testExpandIP() {
Assert.assertEquals(AclUtils.expandIP("::", 8), "0000:0000:0000:0000:0000:0000:0000:0000");
Assert.assertEquals(AclUtils.expandIP("::1", 8), "0000:0000:0000:0000:0000:0000:0000:0001");
Assert.assertEquals(AclUtils.expandIP("3::", 8), "0003:0000:0000:0000:00... |
@Override
public Optional<Map<String, EncryptionInformation>> getReadEncryptionInformation(
ConnectorSession session,
Table table,
Optional<Set<HiveColumnHandle>> requestedColumns,
Map<String, Partition> partitions)
{
Optional<DwrfTableEncryptionProperties... | @Test
public void testGetReadEncryptionInformationForPartitionedTableWithColumnLevelEncryption()
{
Table table = createTable(DWRF, Optional.of(forPerColumn(fromHiveProperty("key1:col_string,col_struct.b.b2;key2:col_bigint,col_struct.a"), "algo", "provider")), true);
Optional<Map<String, Encrypti... |
@Override
public byte[] encode(ILoggingEvent event) {
var baos = new ByteArrayOutputStream();
try (var generator = jsonFactory.createGenerator(baos)) {
generator.writeStartObject();
// https://cloud.google.com/logging/docs/structured-logging#structured_logging_special_fields
// https://gith... | @Test
void encode_mdc() {
var e = mockEvent();
when(e.getLevel()).thenReturn(Level.DEBUG);
when(e.getFormattedMessage()).thenReturn("oha, sup?");
when(e.getMDCPropertyMap())
.thenReturn(
Map.of(
"traceId", "k398cidkekk",
"spanId", "499910"));
... |
@Override
public void deleteDataSourceConfig(Long id) {
// 校验存在
validateDataSourceConfigExists(id);
// 删除
dataSourceConfigMapper.deleteById(id);
} | @Test
public void testDeleteDataSourceConfig_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> dataSourceConfigService.deleteDataSourceConfig(id), DATA_SOURCE_CONFIG_NOT_EXISTS);
} |
public <T> List<CompletableFuture<T>> scheduleWriteAllOperation(
String name,
Duration timeout,
CoordinatorWriteOperation<S, T, U> op
) {
throwIfNotRunning();
log.debug("Scheduled execution of write all operation {}.", name);
return coordinators
.keySet()
... | @Test
public void testScheduleWriteAllOperation() throws ExecutionException, InterruptedException, TimeoutException {
MockTimer timer = new MockTimer();
MockPartitionWriter writer = new MockPartitionWriter();
CoordinatorRuntime<MockCoordinatorShard, String> runtime =
new Coordin... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertDecimal() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("numeric(38,2)")
.dataType("numeric")
.precision(38L)
... |
public static String getAppName() {
String appName;
appName = getAppNameByProjectName();
if (appName != null) {
return appName;
}
appName = getAppNameByServerHome();
if (appName != null) {
return appName;
}
... | @Test
void testGetAppNameByServerTypeForJetty() {
System.setProperty("jetty.home", "/home/admin/testAppName/");
String appName = AppNameUtils.getAppName();
assertEquals("testAppName", appName);
} |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
final Stacker contextStacker = buildContext.buildNodeContext(getId().toString());
return schemaKStreamFactory.create(
buildContext,
dataSource,
contextStacker.push(SOURCE_OP_NAME)
);
} | @Test
public void shouldBuildSourceNode() {
// When:
realStream = buildStream(node);
// Then:
final TopologyDescription.Source node = (TopologyDescription.Source) getNodeByName(realBuilder.build(), PlanTestUtil.SOURCE_NODE);
final List<String> successors = node.successors().stream().map(TopologyD... |
public static long timeUnitToMill(String timeStrWithUnit) {
// If `timeStrWithUnit` doesn't include time unit,
// `Duration.parse` would fail to parse and throw Exception.
if (timeStrWithUnit.endsWith("ms")) {
return Long.parseLong(timeStrWithUnit.substring(0, timeStrWithUnit.length() - 2));
}
... | @Test
void testTimeUnitToMill_WithoutUnit_1() {
assertThrows(DateTimeParseException.class, () -> {
ZeppelinConfiguration.timeUnitToMill("60000");
});
} |
public void execute() throws Exception {
forward();
LOG.info("forwarding to master get result max journal id: {}", result.maxJournalId);
ctx.getGlobalStateMgr().getJournalObservable().waitOn(result.maxJournalId, waitTimeoutMs);
if (result.state != null) {
MysqlStateType stat... | @Test
public void testResourceGroupNameInAuditLog() throws Exception {
String createGroup = "create resource group rg1\n" +
"to\n" +
" (db='d1')\n" +
"with (\n" +
" 'cpu_core_limit' = '1',\n" +
" 'mem_limit' = '50%',\n... |
public void fetch(DownloadAction downloadAction, URLService urlService) throws Exception {
downloadChecksumFile(downloadAction, urlService.baseRemoteURL());
downloadArtifact(downloadAction, urlService.baseRemoteURL());
} | @Test
public void shouldMakeTheFetchHandlerUseTheArtifactMd5Checksum() throws Exception {
ArtifactMd5Checksums artifactMd5Checksums = mock(ArtifactMd5Checksums.class);
when(urlService.baseRemoteURL()).thenReturn("http://10.10.1.1/go/files");
when(checksumFileHandler.url("http://10.10.1.1/go... |
public ModuleBuilder addRegistries(List<? extends RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
} | @Test
void addRegistries() {
RegistryConfig registry = new RegistryConfig();
ModuleBuilder builder = ModuleBuilder.newBuilder();
builder.addRegistries(Collections.singletonList(registry));
Assertions.assertTrue(builder.build().getRegistries().contains(registry));
Assertions.a... |
Configuration get() {
return this.hadoopConfig;
} | @Test
void customPropertiesSurviveSerializationDeserialization()
throws IOException, ClassNotFoundException {
final SerializableHadoopConfiguration serializableConfigUnderTest =
new SerializableHadoopConfiguration(configuration);
final byte[] serializedConfigUnderTest = s... |
public JobMetaDataParameterObject processJobMultipart(JobMultiPartParameterObject parameterObject)
throws IOException, NoSuchAlgorithmException {
// Change the timestamp in the beginning to avoid expiration
changeLastUpdatedTime();
validateReceivedParameters(parameterObject);
... | @Test
public void testZeroPartSize() {
byte[] partData = new byte[]{1};
JobMultiPartParameterObject jobMultiPartParameterObject = new JobMultiPartParameterObject();
jobMultiPartParameterObject.setSessionId(null);
jobMultiPartParameterObject.setCurrentPartNumber(1);
jobMultiP... |
public static ThreadFactory createThreadFactory(final String pattern,
final boolean daemon) {
return new ThreadFactory() {
private final AtomicLong threadEpoch = new AtomicLong(0);
@Override
public Thread newThread(Runnable... | @Test
public void testThreadNameWithNumberNoDemon() {
ThreadFactory localThreadFactory = ThreadUtils.createThreadFactory(THREAD_NAME_WITH_NUMBER, false);
assertEquals(THREAD_NAME + "1", localThreadFactory.newThread(EMPTY_RUNNABLE).getName());
assertEquals(THREAD_NAME + "2", localThreadFactor... |
public StrBuilder reset() {
this.position = 0;
return this;
} | @Test
public void resetTest() {
StrBuilder builder = StrBuilder.create(1);
builder.append("aaa").append("你好").append('r');
builder.insert(3, "数据插入");
builder.reset();
assertEquals("", builder.toString());
} |
@Override
public double rank(Corpus corpus, TextTerms doc, String term, int tf, int n) {
if (tf <= 0) return 0.0;
int N = corpus.ndoc();
int docSize = doc.size();
int avgDocSize = corpus.avgDocSize();
return score(tf, docSize, avgDocSize, N, n);
} | @Test
public void testRank() {
System.out.println("rank");
int freq = 3;
int docSize = 100;
int avgDocSize = 150;
int N = 10000000;
int n = 1000;
BM25 instance = new BM25(2.0, 0.75, 0.0);
double expResult = 18.419681;
double result = instance.s... |
@Override
public void showUpWebView(WebView webView, boolean isSupportJellyBean) {
} | @Test
public void testShowUpWebView2() {
WebView webView = new WebView(mApplication);
mSensorsAPI.showUpWebView(webView, false);
} |
public static OffchainLookup build(byte[] bytes) {
List<Type> resultList =
FunctionReturnDecoder.decode(Numeric.toHexString(bytes), outputParameters);
return new OffchainLookup(
(Address) resultList.get(0),
(DynamicArray<Utf8String>) resultList.get(1),
... | @Test
void build() {
OffchainLookup offchainLookup =
OffchainLookup.build(Numeric.hexStringToByteArray(LOOKUP_HEX.substring(10)));
assertNotNull(offchainLookup);
assertEquals("0xc1735677a60884abbcf72295e88d47764beda282", offchainLookup.getSender());
assertNotNull(off... |
public static Optional<SingleMetaDataValidator> newInstance(final SQLStatement sqlStatement) {
if (sqlStatement instanceof DropSchemaStatement) {
return Optional.of(new SingleDropSchemaMetaDataValidator());
}
if (sqlStatement instanceof DropTableStatement) {
return Option... | @Test
void assertNewInstanceForDropSchemaStatement() {
assertTrue(SingleMetaDataValidatorFactory.newInstance(mock(DropSchemaStatement.class)).isPresent());
} |
public static <T> PTransform<PCollection<T>, PCollection<T>> exceptDistinct(
PCollection<T> rightCollection) {
checkNotNull(rightCollection, "rightCollection argument is null");
return new SetImpl<>(rightCollection, exceptDistinct());
} | @Test
@Category(NeedsRunner.class)
public void testExceptCollectionList() {
PCollection<String> third = p.apply("third", Create.of(Arrays.asList("a", "b", "b", "g", "g")));
PCollection<Row> thirdRows = p.apply("thirdRows", Create.of(toRows("a", "b", "b", "g", "g")));
PAssert.that(
PCollecti... |
@Override
public void register(final TopicPartition partition, final ProcessorStateManager stateManager) {
final StateStoreMetadata storeMetadata = stateManager.storeMetadata(partition);
if (storeMetadata == null) {
throw new IllegalStateException("Cannot find the corresponding state sto... | @Test
public void shouldNotRegisterStoreWithoutMetadata() {
assertThrows(IllegalStateException.class,
() -> changelogReader.register(new TopicPartition("ChangelogWithoutStoreMetadata", 0), stateManager));
} |
public static LocalDateTime parse(String dateTime, DateTimeFormatter dateTimeFormatter) {
TemporalAccessor parsedTimestamp = dateTimeFormatter.parse(dateTime);
LocalTime localTime = parsedTimestamp.query(TemporalQueries.localTime());
LocalDate localDate = parsedTimestamp.query(TemporalQueries.lo... | @Test
public void testParseTimestamp() {
// 2023-12-22 12:55:20
final long timestamp = 1703220920013L;
LocalDateTime parse = DateTimeUtils.parse(timestamp, ZoneId.of("Asia/Shanghai"));
Assertions.assertEquals(55, parse.getMinute());
Assertions.assertEquals(12, parse.getHour(... |
public static void validatePermission(@Nullable String tableName, AccessType accessType,
@Nullable HttpHeaders httpHeaders, String endpointUrl, AccessControl accessControl) {
String userMessage = getUserMessage(tableName, accessType, endpointUrl);
String rawTableName = TableNameBuilder.extractRawTableName... | @Test
public void testValidatePermissionAllowed() {
AccessControl ac = Mockito.mock(AccessControl.class);
HttpHeaders mockHttpHeaders = Mockito.mock(HttpHeaders.class);
Mockito.when(ac.hasAccess(_table, AccessType.READ, mockHttpHeaders, _endpoint)).thenReturn(true);
AccessControlUtils.validatePermis... |
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, Dimension... dimensions) ... | @Test
void testDouble() {
testGeneric(Flags.defineDoubleFlag("double-id", 3.142, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 2.718);
} |
public static String[] parseKey(String groupKey) {
StringBuilder sb = new StringBuilder();
String dataId = null;
String group = null;
String tenant = null;
for (int i = 0; i < groupKey.length(); ++i) {
char c = groupKey.charAt(i);
if (PLUS == c) {... | @Test
void testParseKeyIllegalArgumentException2() {
assertThrows(IllegalArgumentException.class, () -> {
GroupKey.parseKey("f%oo");
});
} |
public static void checkProxyPortProperty() throws NumberFormatException {
checkNumericSystemProperty("http.proxyPort", Range.closed(0, 65535));
checkNumericSystemProperty("https.proxyPort", Range.closed(0, 65535));
} | @Test
public void testCheckHttpProxyPortProperty_undefined() throws NumberFormatException {
System.clearProperty("http.proxyPort");
System.clearProperty("https.proxyPort");
JibSystemProperties.checkProxyPortProperty();
} |
public static Map<String, String> getKiePMMLRegressionModelSourcesMap(final RegressionCompilationDTO compilationDTO) throws IOException {
logger.trace("getKiePMMLRegressionModelSourcesMap {} {} {}", compilationDTO.getFields(),
compilationDTO.getModel(),
compilationDTO.g... | @Test
void getKiePMMLRegressionModelSourcesMap() throws IOException {
final CommonCompilationDTO<RegressionModel> compilationDTO =
CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmml,
... |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = MinionConstants.UpsertCompactionTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
if (!validate(tableConfig)) {
LO... | @Test
public void testGenerateTasksWithNewlyCompletedSegment() {
when(_mockClusterInfoAccessor.getSegmentsZKMetadata(REALTIME_TABLE_NAME)).thenReturn(
Lists.newArrayList(_completedSegment));
when(_mockClusterInfoAccessor.getIdealState(REALTIME_TABLE_NAME)).thenReturn(
getIdealState(REALTIME_TA... |
@Override
public void setProperties(final Properties properties) {
} | @Test
public void setPropertiesTest() {
final PostgreSQLPrepareInterceptor postgreSQLPrepareInterceptor = new PostgreSQLPrepareInterceptor();
Assertions.assertDoesNotThrow(() -> postgreSQLPrepareInterceptor.setProperties(mock(Properties.class)));
} |
public String getName() {
if ( transMeta == null ) {
return null;
}
return transMeta.getName();
} | @Test
public void testFindDatabaseWithEncodedConnectionName() {
DatabaseMeta dbMeta1 =
new DatabaseMeta( "encoded_DBConnection", "Oracle", "localhost", "access", "test", "111", "test", "test" );
dbMeta1.setDisplayName( "encoded.DBConnection" );
meta.addDatabase( dbMeta1 );
DatabaseMeta dbMeta2 ... |
public String selectProtocol() {
if (members.isEmpty()) {
throw new IllegalStateException("Cannot select protocol for empty group");
}
// select the protocol for this group which is supported by all members
Set<String> candidates = candidateProtocols();
// let each ... | @Test
public void testSelectProtocolRaisesIfNoMembers() {
assertThrows(IllegalStateException.class, () -> group.selectProtocol());
} |
@Override
public void flush(final ByteBuffer buffer, final Consumer<Map<String, Object>> eventConsumer) {
decodeMetricIn.increment();
decodeMetricTime.time(() -> codec.flush(buffer, (event) -> {
decodeMetricOut.increment();
eventConsumer.accept(event);
}));
} | @Test
public void flushIncrementsEventCount() {
codec = new AbstractCodec() {
@Override
public void flush(final ByteBuffer buffer, final Consumer<Map<String, Object>> eventConsumer) {
eventConsumer.accept(ImmutableMap.of("message", "abcdef"));
eventCon... |
Object getCellValue(Cell cell, Schema.FieldType type) {
ByteString cellValue = cell.getValue();
int valueSize = cellValue.size();
switch (type.getTypeName()) {
case BOOLEAN:
checkArgument(valueSize == 1, message("Boolean", 1));
return cellValue.toByteArray()[0] != 0;
case BYTE:
... | @Test
public void shouldParseInt32Type() {
byte[] value = new byte[] {0, 2, 0, 0};
assertEquals(131072, PARSER.getCellValue(cell(value), INT32));
} |
@Override
public Map<V, String> hash(V... members) {
return get(hashAsync(members));
} | @Test
public void testHash() {
RGeo<String> geo = redisson.getGeo("test");
geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"), new GeoEntry(15.087269, 37.502669, "Catania"));
Map<String, String> expected = new LinkedHashMap<>();
expected.put("Palermo", "sqc8b49rny0");
... |
public void report(String message) {
if (monochrome) {
message = message.replaceAll("\u001B\\[[;\\d]*m", "");
}
out.print(message);
} | @Test
void printsTheCorrespondingReportsCucumberIoUrl() throws UnsupportedEncodingException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
UrlReporter urlReporter = new UrlReporter(new PrintStream(bytes, false, StandardCharsets.UTF_8.name()));
urlReporter.report(message);
... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testInvalidSpdyRstStreamFrameLength() throws Exception {
short type = 3;
byte flags = 0;
int length = 12; // invalid length
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(... |
static void dissectFrame(
final DriverEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
builder.append(": address=");
enc... | @Test
void dissectFrameTypeRtt()
{
internalEncodeLogHeader(buffer, 0, 3, 3, () -> 3_000_000_000L);
final int socketAddressOffset = encodeSocketAddress(
buffer, LOG_HEADER_LENGTH, new InetSocketAddress("localhost", 8888));
final RttMeasurementFlyweight flyweight = new RttMeasu... |
public static MessageType convertToParquetMessageType(String name, RowType rowType) {
Type[] types = new Type[rowType.getFieldCount()];
for (int i = 0; i < rowType.getFieldCount(); i++) {
String fieldName = rowType.getFieldNames().get(i);
LogicalType fieldType = rowType.getTypeAt(i);
types[i] ... | @Test
void testConvertComplexTypes() {
DataType dataType = DataTypes.ROW(
DataTypes.FIELD("f_array",
DataTypes.ARRAY(DataTypes.CHAR(10))),
DataTypes.FIELD("f_map",
DataTypes.MAP(DataTypes.INT(), DataTypes.VARCHAR(20))),
DataTypes.FIELD("f_row",
DataTypes... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testThreeMoreThanFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
history.add(3);
history.add(4);
history.add(5);
history.add(6);
int[] expectedHistorySnapshot = {4, 5, 6};
testHistory(history, expectedHistory... |
@Override
public List<Bar> aggregate(List<Bar> bars) {
final List<Bar> aggregated = new ArrayList<>();
if (bars.isEmpty()) {
return aggregated;
}
final Bar firstBar = bars.get(0);
// get the actual time period
final Duration actualDur = firstBar.getTimePer... | @Test
public void upscaledTo5DayBars() {
final DurationBarAggregator barAggregator = new DurationBarAggregator(Duration.ofDays(5), true);
final List<Bar> bars = barAggregator.aggregate(getOneDayBars());
// must be 3 bars
assertEquals(3, bars.size());
// bar 1 must have ohl... |
@Injection( name = "TRUNCATE_TABLE" )
public void metaSetTruncateTable( String value ) {
setTruncateTable( "Y".equalsIgnoreCase( value ) );
} | @Test
public void metaSetTruncateTable() {
TableOutputMeta tableOutputMeta = new TableOutputMeta();
tableOutputMeta.metaSetTableNameDefinedInField( "Y" );
assertTrue( tableOutputMeta.isTableNameInField() );
tableOutputMeta.metaSetTableNameDefinedInField( "N" );
assertFalse( tableOutputMeta.isTable... |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldFailDropStreamWhenAnotherStreamIsReadingTheTable() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create stream bar as select * from test1;"
+ "create stream foo as select * from ba... |
@PUT
@Path("{noteId}/rename")
@ZeppelinApi
public Response renameNote(@PathParam("noteId") String noteId,
String message) throws IOException {
LOGGER.info("Rename note by JSON {}", message);
RenameNoteRequest request = GSON.fromJson(message, RenameNoteRequest.class);
Stri... | @Test
void testRenameNote() throws IOException {
LOG.info("Running testRenameNote");
String noteId = null;
try {
String oldName = "old_name";
noteId = notebook.createNote(oldName, anonymous);
assertEquals(oldName, notebook.processNote(noteId, Note::getName));
final String newName ... |
@Override
public Object toKsqlRow(final Schema connectSchema, final Object connectData) {
if (connectData == null) {
return null;
}
return toKsqlValue(schema, connectSchema, connectData, "");
} | @Test
public void shouldTranslateMapWithStructValues() {
// Given:
final Schema innerSchema = SchemaBuilder
.struct()
.field("FIELD", Schema.OPTIONAL_INT32_SCHEMA)
.build();
final Schema rowSchema = SchemaBuilder
.struct()
.field("MAP", SchemaBuilder
... |
public static <T> IntermediateCompatibilityResult<T> constructIntermediateCompatibilityResult(
TypeSerializerSnapshot<?>[] newNestedSerializerSnapshots,
TypeSerializerSnapshot<?>[] oldNestedSerializerSnapshots) {
Preconditions.checkArgument(
newNestedSerializerSnapshots.... | @Test
void testCompatibleAsIsIntermediateCompatibilityResult() {
final TypeSerializerSnapshot<?>[] previousSerializerSnapshots =
new TypeSerializerSnapshot<?>[] {
new SchemaCompatibilityTestingSerializer("first serializer")
.snapshotConfigurati... |
public List<ScimGroupDto> findScimGroups(DbSession dbSession, ScimGroupQuery query, Pagineable pagination) {
return mapper(dbSession).findScimGroups(query, pagination);
} | @Test
void findScimGroups_whenFilteringByDisplayName_shouldReturnTheExpectedScimGroups() {
insertGroupAndScimGroup("group1");
insertGroupAndScimGroup("group2");
ScimGroupQuery query = ScimGroupQuery.fromScimFilter(DISPLAY_NAME_FILTER);
List<ScimGroupDto> scimGroups = scimGroupDao.findScimGroups(db.ge... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
return new DropboxAttributesFinderFeature(session).find(file, listener) != PathAttributes.EMPTY;
}
... | @Test
public void testFindNotFound() throws Exception {
assertFalse(new DropboxFindFeature(session).find(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file))));
} |
@Override
public int getIntLE(int index) {
checkIndex(index, 4);
return _getIntLE(index);
} | @Test
public void testGetIntLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().getIntLE(0);
}
});
} |
@Override
public void writeDouble(final double v) throws IOException {
ensureAvailable(DOUBLE_SIZE_IN_BYTES);
MEM.putDouble(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v);
pos += DOUBLE_SIZE_IN_BYTES;
} | @Test
public void testWriteDoubleV() throws Exception {
double expected = 1.1d;
out.writeDouble(expected);
long theLong = Bits.readLong(out.buffer, 0, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
double actual = Double.longBitsToDouble(theLong);
assertEquals(expected, a... |
@Override
public int size() {
if (entries == null) {
return 0;
}
return entries.size();
} | @Test
public void testSize_whenEmpty() {
List<Map.Entry> emptyList = Collections.emptyList();
ResultSet resultSet = new ResultSet(emptyList, IterationType.KEY);
assertEquals(0, resultSet.size());
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM
&& event.getType() != ChatMessageType.GAMEMESSAGE
&& event.getType() != ChatMessageType.MESBOX)
{
return;
}
final var msg = event.getMessage();
if (WOOD_CUT_PATTERN.matcher(msg).matches())
{
... | @Test
public void testArcticLogs()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", "You get an arctic log.", "", 0);
woodcuttingPlugin.onChatMessage(chatMessage);
assertNotNull(woodcuttingPlugin.getSession());
} |
public static void trackNotificationOpenedEvent(String sfData,
String title,
String content,
String appPushServiceName,
... | @Test
public void trackNotificationOpenedEvent() {
try {
trackJPushOpenActivity();
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
@Nullable
public Integer getIntValue(@IntFormat final int formatType,
@IntRange(from = 0) final int offset) {
if ((offset + getTypeLen(formatType)) > size()) return null;
return switch (formatType) {
case FORMAT_UINT8 -> unsignedByteToInt(mValue[offset]);
case FORMAT_UINT16_LE -> unsignedBytesToIn... | @Test
public void getValue_UINT8() {
final Data data = new Data(new byte[] {(byte) 0xC8 });
final int value = data.getIntValue(Data.FORMAT_UINT8, 0);
assertEquals(200, value);
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeRoundingEven() {
FunctionTestUtil.assertResult(roundHalfDownFunction.invoke(BigDecimal.valueOf(10.25)), BigDecimal.valueOf(10));
FunctionTestUtil.assertResult(roundHalfDownFunction.invoke(BigDecimal.valueOf(10.25), BigDecimal.ONE),
BigDecimal.va... |
@ExceptionHandler(UnauthorizedException.class)
protected ShenyuAdminResult handleUnauthorizedException(final UnauthorizedException exception) {
LOG.error("unauthorized exception", exception);
return ShenyuAdminResult.error(CommonErrorCode.TOKEN_NO_PERMISSION, ShenyuResultMessage.TOKEN_HAS_NO_PERMISS... | @Test
public void testShiroExceptionHandler() {
UnauthorizedException unauthorizedException = new UnauthorizedException("Test unauthorizedException");
ShenyuAdminResult result = exceptionHandlersUnderTest.handleUnauthorizedException(unauthorizedException);
Assertions.assertEquals(result.getC... |
@Override
public List<ActionParameter> getParameters() {
return List.of(
ActionParameter.from("filename", "Relative path of the file to write in the agent workspace"),
ActionParameter.from("body", "Text content to write to the file. Binary is not supported.")
);
} | @Test
void testGetParameters() {
List<ActionParameter> parameters = writeFileAction.getParameters();
assertEquals(2, parameters.size());
assertEquals("filename", parameters.get(0).getName());
assertEquals("Relative path of the file to write in the agent workspace", parameters.get(0).... |
public static void verifyIncrementPubContent(String content) {
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("publish/delete content can not be null");
}
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);... | @Test
void testVerifyIncrementPubContentFail4() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
String content = "aa" + WORD_SEPARATOR + "bbb";
ContentUtils.verifyIncrementPubContent(content);
});
assertTrue(exception.getMessage().contains... |
@Deprecated
public static void unJarAndSave(InputStream inputStream, File toDir,
String name, Pattern unpackRegex)
throws IOException{
File file = new File(toDir, name);
ensureDirectory(toDir);
try (OutputStream jar = Files.newOutputStream(file.toPath());
TeeInput... | @SuppressWarnings("deprecation")
@Test
public void testBigJar() throws Exception {
Random r = new Random(System.currentTimeMillis());
File dir = new File(TEST_ROOT_DIR, Long.toHexString(r.nextLong()));
Assert.assertTrue(dir.mkdirs());
File input = generateBigJar(dir);
File output = new File(dir,... |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Payload other = (Payload) o;
return this.compressionInfo.equals(other.compressionInfo) && this.data.equals(other.data);
} | @Test
public void testEquals() {
final String foo1 = "foo 1";
final String foo2 = "foo 2";
Payload a = Payload.from(foo1);
Payload b = Payload.from(foo1);
assertEquals(a, b);
Payload c = Payload.from(foo2);
assertNotEquals(a, c);
Slime slime = new S... |
public static Catalog loadCatalog(
String impl, String catalogName, Map<String, String> properties, Object hadoopConf) {
Preconditions.checkNotNull(impl, "Cannot initialize custom Catalog, impl class name is null");
DynConstructors.Ctor<Catalog> ctor;
try {
ctor = DynConstructors.builder(Catalog... | @Test
public void loadCustomCatalog_BadCatalogNameCatalog() {
Map<String, String> options = Maps.newHashMap();
options.put("key", "val");
Configuration hadoopConf = new Configuration();
String name = "custom";
String impl = "CatalogDoesNotExist";
assertThatThrownBy(() -> CatalogUtil.loadCatalo... |
@Override
public Cost plus(RelOptCost other) {
Cost other0 = (Cost) other;
if (isInfinite() || other.isInfinite()) {
return INFINITY;
}
return new Cost(rows + other0.rows, cpu + other0.cpu, network + other0.network);
} | @Test
public void testPlus() {
CostFactory factory = CostFactory.INSTANCE;
Cost firstCost = factory.makeCost(1.0d, 2.0d, 3.0d);
Cost secondCost = factory.makeCost(4.0d, 5.0d, 6.0d);
Cost infiniteCost = factory.makeInfiniteCost();
assertEquals(factory.makeCost(5.0d, 7.0d, 9.... |
@VisibleForTesting
static int parseRgb(Slice color)
{
if (color.length() != 4 || color.getByte(0) != '#') {
return -1;
}
int red = Character.digit((char) color.getByte(1), 16);
int green = Character.digit((char) color.getByte(2), 16);
int blue = Character.dig... | @Test
public void testParseRgb()
{
assertEquals(parseRgb(toSlice("#000")), 0x00_00_00);
assertEquals(parseRgb(toSlice("#FFF")), 0xFF_FF_FF);
assertEquals(parseRgb(toSlice("#F00")), 0xFF_00_00);
assertEquals(parseRgb(toSlice("#0F0")), 0x00_FF_00);
assertEquals(parseRgb(toS... |
public CompletableFuture<Acknowledge> triggerSavepoint(
AsynchronousJobOperationKey operationKey,
String targetDirectory,
SavepointFormatType formatType,
TriggerSavepointMode savepointMode,
Time timeout) {
return registerOperationIdempotently(
... | @Test
public void throwsIfCacheIsShuttingDown() {
savepointTriggerCache.closeAsync();
assertThrows(
IllegalStateException.class,
() ->
handler.triggerSavepoint(
operationKey,
targe... |
@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
throw new ReadOnlyBufferException();
} | @Test
public void shouldRejectSetBytes2() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() throws IOException {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ScatteringByteChannel) null, 0);
}
}... |
@Override
public String convertDestination(ProtocolConverter converter, Destination d) {
if (d == null) {
return null;
}
ActiveMQDestination activeMQDestination = (ActiveMQDestination)d;
String physicalName = activeMQDestination.getPhysicalName();
String rc = con... | @Test(timeout = 10000)
public void testConvertCompositeMixture() throws Exception {
String destinationA = "destinationA";
String destinationB = "destinationB";
String destinationC = "destinationC";
String destinationD = "destinationD";
String composite = "/queue/" + destinat... |
@VisibleForTesting
Optional<Xpp3Dom> getSpringBootRepackageConfiguration() {
Plugin springBootPlugin =
project.getPlugin("org.springframework.boot:spring-boot-maven-plugin");
if (springBootPlugin != null) {
for (PluginExecution execution : springBootPlugin.getExecutions()) {
if (executio... | @Test
public void testGetSpringBootRepackageConfiguration_noRepackageGoal() {
when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin"))
.thenReturn(mockPlugin);
when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution));
when(mockPluginExecution.get... |
@Override
public void deleteFile(Long id) throws Exception {
// 校验存在
FileDO file = validateFileExists(id);
// 从文件存储器中删除
FileClient client = fileConfigService.getFileClient(file.getConfigId());
Assert.notNull(client, "客户端({}) 不能为空", file.getConfigId());
client.delete(... | @Test
public void testDeleteFile_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> fileService.deleteFile(id), FILE_NOT_EXISTS);
} |
@Override
public void onDeserializationFailure(
final String source,
final String changelog,
final byte[] data
) {
// NOTE: this only happens for values, we should never auto-register key schemas
final String sourceSubject = KsqlConstants.getSRSubject(source, false);
final String chang... | @Test
public void shouldRegisterIdFromData() throws IOException, RestClientException {
// Given:
when(srClient.getSchemaBySubjectAndId(KsqlConstants.getSRSubject(SOURCE, false), ID)).thenReturn(schema);
final RegisterSchemaCallback call = new RegisterSchemaCallback(srClient);
// When:
call.onDese... |
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) {
return mRxSharedPreferences.getBoolean(
mResources.getString(prefKey), mResources.getBoolean(defaultValue));
} | @Test
public void testSetupFallbackDictionaryToFalseIfWasNotSetBefore() {
SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 11);
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Assert.assertFalse(preferences.contains("sett... |
@Override
@Transactional
public boolean updateAfterApproval(Long userId, Integer userType, String clientId, Map<String, Boolean> requestedScopes) {
// 如果 requestedScopes 为空,说明没有要求,则返回 true 通过
if (CollUtil.isEmpty(requestedScopes)) {
return true;
}
// 更新批准的信息
... | @Test
public void testUpdateAfterApproval_approved() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
Map<String, Boolean> requestedScopes = new LinkedHashMap<>(); // 有序,方便判断
requ... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (applicationName != null && !applicationName.isEmpty()) {
invocation.setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, applicationName);
}
return invoker.invoke(invocation);
... | @Test
public void testInvokeApplicationKey() {
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(Invocation.class);
URL url = URL.valueOf("test://test:111/test?application=serviceA");
when(invoker.getUrl()).thenReturn(url);
ApplicationModel applicationModel... |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test
public void testMergeDifferentProducerConfig() {
FunctionConfig functionConfig = createFunctionConfig();
ProducerConfig producerConfig = new ProducerConfig();
producerConfig.setMaxPendingMessages(100);
producerConfig.setMaxPendingMessagesAcrossPartitions(1000);
produce... |
@Override
public void initialize(URI uri, Configuration conf)
throws IOException
{
requireNonNull(uri, "uri is null");
requireNonNull(conf, "conf is null");
super.initialize(uri, conf);
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAut... | @Test
public void testStaticCredentials()
throws Exception
{
Configuration config = new Configuration();
config.set(S3_ACCESS_KEY, "test_secret_access_key");
config.set(S3_SECRET_KEY, "test_access_key_id");
// the static credentials should be preferred
try (P... |
public int generate(Class<? extends CustomResource> crdClass, Writer out) throws IOException {
ObjectNode node = nf.objectNode();
Crd crd = crdClass.getAnnotation(Crd.class);
if (crd == null) {
err(crdClass + " is not annotated with @Crd");
} else {
node.put("apiV... | @Test
void simpleTestWithoutDescriptions() throws IOException {
CrdGenerator crdGenerator = new CrdGenerator(KubeVersion.V1_16_PLUS, ApiVersion.V1, CrdGenerator.YAML_MAPPER,
emptyMap(), crdGeneratorReporter, emptyList(), null, null,
new CrdGenerator.NoneConversionStrategy(), ... |
@Override
public Map<String, JWK> getAllPublicKeys() {
Map<String, JWK> pubKeys = new HashMap<>();
// pull out all public keys
for (String keyId : keys.keySet()) {
JWK key = keys.get(keyId);
JWK pub = key.toPublicJWK();
if (pub != null) {
pubKeys.put(keyId, pub);
}
}
return pubKeys;
} | @Test
public void getAllPubKeys() throws ParseException {
Map<String,JWK> keys2check = service_2.getAllPublicKeys();
assertEquals(
JSONObjectUtils.getString(RSAjwk.toPublicJWK().toJSONObject(), "e"),
JSONObjectUtils.getString(keys2check.get(RSAkid).toJSONObject(), "e")
);
assertEquals(
JSONObjec... |
@Override
public Serde.Deserializer deserializer(String topic, Serde.Target type) {
return new Serde.Deserializer() {
@SneakyThrows
@Override
public DeserializeResult deserialize(RecordHeaders headers, byte[] data) {
try {
UnknownFieldSet unknownFields = UnknownFi... | @Test
void deserializeSimpleMessage() {
var deserialized = serde.deserializer(DUMMY_TOPIC, Serde.Target.VALUE)
.deserialize(null, getProtobufMessage());
assertThat(deserialized.getResult()).isEqualTo("1: 5\n");
} |
public CommandLine getCommandLine() {
return commandLine;
} | @SuppressWarnings("static-access")
@Test
public void testCreateWithOptions() throws Exception {
// Create new option newOpt
Option opt = Option.builder("newOpt").argName("int")
.hasArg()
.desc("A new option")
.build();
Options opts = new Options();
opts.addOption(opt);
... |
@Override
public org.apache.kafka.streams.kstream.Transformer<KIn, VIn, Iterable<KeyValue<KOut, VOut>>> get() {
return new org.apache.kafka.streams.kstream.Transformer<KIn, VIn, Iterable<KeyValue<KOut, VOut>>>() {
private final org.apache.kafka.streams.kstream.Transformer<KIn, VIn, KeyValue<KOu... | @Test
public void shouldAlwaysGetNewAdapterTransformer() {
@SuppressWarnings("unchecked")
final org.apache.kafka.streams.kstream.Transformer<String, String, KeyValue<Integer, Integer>> transformer1 =
mock(org.apache.kafka.streams.kstream.Transformer.class);
@SuppressWarnings("unc... |
@Override
public DataType getType() {
return DataType.URI;
} | @Test
public void testGetType() {
assertEquals(DataType.URI, uriRegisterExecutorSubscriber.getType());
} |
@Override
public String getParamDesc() {
return paramDesc;
} | @Test
void getParamDesc() {
Assertions.assertEquals(ReflectUtils.getDesc(String.class), method.getParamDesc());
} |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test
public void testValueOfAddressIPv4() {
Ip4Address ipAddress;
Ip4Prefix ipPrefix;
ipAddress = Ip4Address.valueOf("1.2.3.4");
ipPrefix = Ip4Prefix.valueOf(ipAddress, 24);
assertThat(ipPrefix.toString(), is("1.2.3.0/24"));
ipPrefix = Ip4Prefix.valueOf(ipAddress, ... |
public static Correspondence<Number, Number> tolerance(double tolerance) {
return new TolerantNumericEquality(tolerance);
} | @Test
public void testTolerance_viaIterableSubjectContains_success() {
assertThat(ImmutableList.of(1.02, 2.04, 3.08))
.comparingElementsUsing(tolerance(0.05))
.contains(2.0);
} |
public static int[] rowMin(int[][] matrix) {
int[] x = new int[matrix.length];
for (int i = 0; i < x.length; i++) {
x[i] = min(matrix[i]);
}
return x;
} | @Test
public void testRowMin() {
System.out.println("rowMin");
double[][] A = {
{0.7220180, 0.07121225, 0.6881997},
{-0.2648886, -0.89044952, 0.3700456},
{-0.6391588, 0.44947578, 0.6240573}
};
double[] r = {0.07121225, -0.89044952, -0.6391588};
... |
public void write(MemoryBuffer buffer, Locale l) {
fury.writeJavaString(buffer, l.getLanguage());
fury.writeJavaString(buffer, l.getCountry());
fury.writeJavaString(buffer, l.getVariant());
} | @Test(dataProvider = "furyCopyConfig")
public void testWrite(Fury fury) {
copyCheckWithoutSame(fury, Locale.US);
copyCheckWithoutSame(fury, Locale.CHINESE);
copyCheckWithoutSame(fury, Locale.ENGLISH);
copyCheckWithoutSame(fury, Locale.TRADITIONAL_CHINESE);
copyCheckWithoutSame(fury, Locale.CHINA);... |
public static String createGPX(InstructionList instructions, String trackName, long startTimeMillis, boolean includeElevation, boolean withRoute, boolean withTrack, boolean withWayPoints, String version, Translation tr) {
DateFormat formatter = Helper.createFormatter();
DecimalFormat decimalFormat = ne... | @Test
public void testInstructionsWithTimeAndPlace() {
BaseGraph g = new BaseGraph.Builder(carManager).create();
// n-4-5 (n: pillar node)
// |
// 7-3-2-6
// |
// 1
NodeAccess na = g.getNodeAccess();
na.setNode(1, 15.0, 10);
na.se... |
public void errorFromOrigin(final Throwable ex) {
try {
// Flag that there was an origin server related error for the loadbalancer to choose
// whether to circuit-trip this server.
if (originConn != null) {
// NOTE: if originConn is null, then these stats will... | @Test
public void onErrorFromOriginNoRetryAdjustment() {
doReturn(OutboundErrorType.RESET_CONNECTION).when(attemptFactory).mapNettyToOutboundErrorType(any());
proxyEndpoint.errorFromOrigin(new RuntimeException());
verify(nettyOrigin).adjustRetryPolicyIfNeeded(request);
verify(nettyO... |
public void setSelector(String selector) {
this.selector = selector;
} | @Test
void testSerialize() throws JsonProcessingException {
ServiceListRequest request = new ServiceListRequest(NAMESPACE, GROUP, 1, 10);
request.setSelector("label");
String json = mapper.writeValueAsString(request);
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
... |
@Override
public RestLiResponseData<CreateResponseEnvelope> buildRestLiResponseData(Request request,
RoutingResult routingResult,
Object result,
Map<String, Strin... | @Test
public void testCreateResponseException() throws URISyntaxException
{
CreateResponse createResponse = new CreateResponse(new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST));
RestRequest restRequest = new RestRequestBuilder(new URI("/foo")).build();
RestLiResponseData<?> envelope = new Create... |
public static String pretreatStatement(Executor executor, String statement) {
statement = SqlUtil.removeNote(statement);
if (executor.isUseSqlFragment()) {
statement = executor.getVariableManager().parseVariable(statement);
}
return statement.trim();
} | @Test
public void replaceFragmentTest() {
String statement = "nullif1:=NULLIF(1, 0) as val;\n"
+ "nullif2:=NULLIF(0, 0) as val$null;\n"
+ "select ${nullif1},${nullif2}";
String pretreatStatement = FlinkInterceptor.pretreatStatement(ExecutorFactory.getDefaultExecutor()... |
public CompletableFuture<Void> compensate(URL lra, Exchange exchange) {
HttpRequest request = prepareRequest(URI.create(lra.toString() + COORDINATOR_PATH_CANCEL), exchange)
.setHeader(CONTENT_TYPE, TEXT_PLAIN_CONTENT)
.PUT(HttpRequest.BodyPublishers.ofString(""))
... | @DisplayName("Tests whether LRAClient is calling prepareRequest with exchange from compensate()")
@Test
void testCallsPrepareRequestWithExchangeInCompensate() throws MalformedURLException {
LRASagaService sagaService = new LRASagaService();
applyMockProperties(sagaService);
LRAClient cli... |
public void cacheSelectData(final SelectorData selectorData) {
Optional.ofNullable(selectorData).ifPresent(this::selectorAccept);
} | @Test
public void testCacheSelectData() throws NoSuchFieldException, IllegalAccessException {
SelectorData firstCachedSelectorData = SelectorData.builder().id("1").pluginName(mockPluginName1).sort(1).build();
BaseDataCache.getInstance().cacheSelectData(firstCachedSelectorData);
ConcurrentHas... |
public void loadAccessData() {
getControls();
pushCache();
Object key = connectionBox.getSelectedItem();
// Nothing selected yet...
if ( key == null ) {
key = connectionMap.firstKey();
connectionBox.setSelectedItem( key );
return;
}
DatabaseInterface database = connect... | @Test
public void testLoadAccessData() throws Exception {
when( accessBox.getSelectedItem() ).thenReturn( "Native" );
DatabaseInterface dbInterface = mock( DatabaseInterface.class );
when( dbInterface.getDefaultDatabasePort() ).thenReturn( 5309 );
DataHandler.connectionMap.put( "myDb", dbInterface );... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.