focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public String convert(ParsedSchema schema) throws IOException {
ProtobufSchema protobufSchema = (ProtobufSchema) schema;
return ProtoConversionUtil.getAvroSchemaForMessageDescriptor(protobufSchema.toDescriptor(), schemaConfig).toString();
} | @Test
void testConvert() throws Exception {
TypedProperties properties = new TypedProperties();
properties.setProperty(ProtoClassBasedSchemaProviderConfig.PROTO_SCHEMA_CLASS_NAME.key(), Parent.class.getName());
Schema.Parser parser = new Schema.Parser();
ProtobufSchema protobufSchema = new ProtobufSch... |
@JsonCreator
@SuppressWarnings("unused")
public static LookupCacheKey createFromJSON(@JsonProperty("prefix") String prefix, @JsonProperty("key") @Nullable Object key) {
return new AutoValue_LookupCacheKey(prefix, key);
} | @Test
public void serialize() {
final LookupCacheKey cacheKey = LookupCacheKey.createFromJSON("prefix", "key");
final JsonNode node = objectMapper.convertValue(cacheKey, JsonNode.class);
assertThat(node.isObject()).isTrue();
assertThat(node.fieldNames()).toIterable().containsExactlyI... |
public static <T> Pair<T, Map<String, Object>> stringToObjectAndUnrecognizedProperties(String jsonString,
Class<T> valueType)
throws IOException {
T instance = DEFAULT_READER.forType(valueType).readValue(jsonString);
Map<String, Object> inputJsonMap = flatten(DEFAULT_MAPPER.readValue(jsonString, MAP... | @Test
public void testUnrecognizedJsonProperties()
throws Exception {
String inputJsonMissingProp = "{\"primitiveIntegerField\": 123, \"missingProp\": 567,"
+ " \"missingObjectProp\": {\"somestuff\": \"data\", \"somemorestuff\":\"moredata\"},"
+ " \"classField\": {\"internalIntField\": 12, ... |
public void logFrameOut(final ByteBuffer buffer, final InetSocketAddress dstAddress)
{
final int length = buffer.remaining() + socketAddressLength(dstAddress);
final int captureLength = captureLength(length);
final int encodedLength = encodedLength(captureLength);
final ManyToOneRin... | @Test
void logFrameOut()
{
final int recordOffset = 24;
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, recordOffset);
final ByteBuffer byteBuffer = buffer.byteBuffer();
byteBuffer.position(8);
final byte[] bytes = new byte[32];
fill(bytes, (byte)-1);
b... |
@GetMapping(
path = "/api/{namespace}/{extension}",
produces = MediaType.APPLICATION_JSON_VALUE
)
@CrossOrigin
@Operation(summary = "Provides metadata of the latest version of an extension")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description =... | @Test
public void testLatestExtensionVersionNonDefaultTarget() throws Exception {
var extVersion = mockExtension("alpine-arm64");
extVersion.setDisplayName("Foo Bar (alpine arm64)");
Mockito.when(repositories.findExtensionVersion("foo", "bar", null, VersionAlias.LATEST)).thenReturn(extVersio... |
public static <K, V> MultiVersionedKeyQuery<K, V> withKey(final K key) {
Objects.requireNonNull(key, "key cannot be null.");
return new MultiVersionedKeyQuery<>(key, Optional.empty(), Optional.empty(), ResultOrder.ANY);
} | @Test
public void shouldThrowNPEWithNullKey() {
final Exception exception = assertThrows(NullPointerException.class, () -> MultiVersionedKeyQuery.withKey(null));
assertEquals("key cannot be null.", exception.getMessage());
} |
public static Builder custom() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void zeroSlowCallRateThresholdShouldFail() {
custom().slowCallRateThreshold(0).build();
} |
static @NonNull CloudStringReader of(final @NonNull CommandInput commandInput) {
return new CloudStringReader(commandInput);
} | @Test
void testPartialWorldRead() throws CommandSyntaxException {
// Arrange
final CommandInput commandInput = CommandInput.of("hi minecraft:pig");
final StringReader stringReader = CloudStringReader.of(commandInput);
// Act
final String readString1 = stringReader.readString... |
static Document replacePlaceholders(Document doc, ExpressionEvalContext evalContext, JetSqlRow inputRow,
String[] externalNames, boolean forRow) {
Object[] values = inputRow.getValues();
return replacePlaceholders(doc, evalContext, values, externalNames, forRow);
... | @Test
public void replaces_mixed() {
// given
Document embedded = new Document("<!InputRef(1)!>", "<!DynamicParameter(0)!>");
Document doc = new Document("<!InputRef(0)!>", embedded);
// when
List<Object> arguments = singletonList("dwa");
Object[] inputs = {"jeden", ... |
public static String propertiesToString(Properties props) throws IOException {
String result = "";
if (props != null) {
DataByteArrayOutputStream dataOut = new DataByteArrayOutputStream();
props.store(dataOut, "");
result = new String(dataOut.getData(), 0, dataOut.siz... | @Test
public void testPropertiesToString() throws Exception {
Properties props = new Properties();
for (int i = 0; i < 10; i++) {
String key = "key" + i;
String value = "value" + i;
props.put(key, value);
}
String str = MarshallingSupport.propertie... |
@Override
public KeyValueIterator<K, V> range(final K from,
final K to) {
final byte[] serFrom = from == null ? null : serdes.rawKey(from);
final byte[] serTo = to == null ? null : serdes.rawKey(to);
return new MeteredKeyValueIterator(
wrap... | @Test
public void shouldThrowNullPointerOnRangeIfToIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> metered.range("from", null));
} |
public static Iterator<String> lineIterator(String input) {
return new LineIterator(input);
} | @Test
public void terminalLine() {
Iterator<String> it = Newlines.lineIterator("foo\nbar\n");
it.next();
it.next();
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
it = Newlines.lineIterator("foo\nbar");
it.next();
it.next();
try {... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertBinary() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("binary(1)")
.dataType("binary")
.length(1L)
... |
public static HudiTableType fromInputFormat(String inputFormat) {
switch (inputFormat) {
case COW_INPUT_FORMAT:
case COW_INPUT_FORMAT_LEGACY:
return HudiTableType.COW;
case MOR_RT_INPUT_FORMAT:
case MOR_RT_INPUT_FORMAT_LEGACY:
retur... | @Test
public void testInputFormat() {
Assert.assertEquals(HudiTable.HudiTableType.COW,
HudiTable.fromInputFormat("org.apache.hudi.hadoop.HoodieParquetInputFormat"));
Assert.assertEquals(HudiTable.HudiTableType.COW,
HudiTable.fromInputFormat("com.uber.hoodie.hadoop.Hoo... |
@Override
public final Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) {
// TODO implement with calendar
Object result = currentResultSetRow.getCell(columnIndex);
wasNull = null == result;
return result;
} | @Test
void assertGetCalendarValue() {
when(memoryResultSetRow.getCell(1)).thenReturn(new Date(0L));
assertThat(memoryMergedResult.getCalendarValue(1, Object.class, Calendar.getInstance()), is(new Date(0L)));
} |
@Override
public void decorateRouteContext(final RouteContext routeContext, final QueryContext queryContext, final ShardingSphereDatabase database,
final SingleRule rule, final ConfigurationProperties props, final ConnectionContext connectionContext) {
SQLStatementContex... | @Test
void assertDecorateRouteContextWithMultiDataSource() throws SQLException {
SingleRule rule = new SingleRule(new SingleRuleConfiguration(), DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), createMultiDataSourceMap(), Collections.emptyList());
RouteContext routeContext = new RouteContext();
... |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_multipleEntriesEscaped() {
assertThat(resolve("^${FOO}:^${BAR}"), equalTo("${FOO}:${BAR}"));
} |
public long betweenMonth(boolean isReset) {
final Calendar beginCal = DateUtil.calendar(begin);
final Calendar endCal = DateUtil.calendar(end);
final int betweenYear = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR);
final int betweenMonthOfYear = endCal.get(Calendar.MONTH) - beginCal.get(Calendar.MONT... | @Test
public void betweenMonthTest() {
Date start = DateUtil.parse("2017-02-01 12:23:46");
Date end = DateUtil.parse("2018-02-01 12:23:46");
long betweenMonth = new DateBetween(start, end).betweenMonth(false);
assertEquals(12, betweenMonth);
Date start1 = DateUtil.parse("2017-02-01 12:23:46");
Date end1 =... |
public void writeStatus(Session.Status sessionStatus) {
try {
createWriteStatusTransaction(sessionStatus).commit();
} catch (Exception e) {
throw new RuntimeException("Unable to write session status", e);
}
} | @Test
public void require_that_status_is_written_to_zk() {
int sessionId = 2;
SessionZooKeeperClient zkc = createSessionZKClient(sessionId);
zkc.writeStatus(Session.Status.NEW);
Path path = sessionPath(sessionId).append(SESSIONSTATE_ZK_SUBPATH);
assertTrue(curator.exists(path... |
@Override
public boolean isOutput() {
return true;
} | @Test
public void testIsOutput() throws Exception {
assertTrue( analyzer.isOutput() );
} |
@Override
protected void doStop() throws Exception {
super.doStop();
int openRequestsAtStop = openRequests.get();
log.debug("Stopping with {} open requests", openRequestsAtStop);
if (openRequestsAtStop > 0) {
log.warn("There are still {} open requests", openRequestsAtStop... | @Test
public void doStopOpenRequest() throws Exception {
sut.openRequests.incrementAndGet();
sut.doStop();
} |
public static Configuration resolve(Configuration conf) {
Configuration resolved = new Configuration(false);
for (Map.Entry<String, String> entry : conf) {
resolved.set(entry.getKey(), conf.get(entry.getKey()));
}
return resolved;
} | @Test
public void resolve() {
Configuration conf = new Configuration(false);
conf.set("a", "A");
conf.set("b", "${a}");
assertEquals(conf.getRaw("a"), "A");
assertEquals(conf.getRaw("b"), "${a}");
conf = ConfigurationUtils.resolve(conf);
assertEquals(conf.getRaw("a"), "A");
assertEqual... |
@PostMapping(
path = "/user/token/create",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<AccessTokenJson> createAccessToken(@RequestParam(required = false) String description) {
if (description != null && description.length() > TOKEN_DESCRIPTION_SIZE) {
... | @Test
public void testCreateAccessToken() throws Exception {
mockUserData();
Mockito.doReturn("foobar").when(users).generateTokenValue();
mockMvc.perform(post("/user/token/create?description={description}", "This is my token")
.with(user("test_user"))
.with(cs... |
public Map<String, Object> convertValue(final Object entity, final Class<?> entityClass) {
if (entityClass.equals(String.class)) {
return Collections.singletonMap("data", objectMapper.convertValue(entity, String.class));
} else if (!entityClass.equals(Void.class) && !entityClass.equals(void.... | @Test
public void convertsListOfEntities() {
final SimpleEntity firstObject = new SimpleEntity("foo", 1);
final SimpleEntity secondObject = new SimpleEntity("bar", 42);
final Map<String, Object> result = toTest.convertValue(Arrays.asList(firstObject, secondObject), SimpleEntity.class);
... |
@Override
public ByteBuf setBytes(int index, byte[] src) {
setBytes(index, src, 0, src.length);
return this;
} | @Test
public void testSetBytesAfterRelease5() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().setBytes(0, new byte[8], 0, 1);
}
});
} |
public static byte[] swapLongs(byte b[], int off, int len) {
checkLength(len, 8);
for (int i = off, n = off + len; i < n; i += 8) {
swap(b, i, i+7);
swap(b, i+1, i+6);
swap(b, i+2, i+5);
swap(b, i+3, i+4);
}
return b;
} | @Test
public void testSwapLongs() {
assertArrayEquals(DOUBLE_PI_LE ,
ByteUtils.swapLongs(DOUBLE_PI_BE.clone(), 0,
DOUBLE_PI_BE.length));
} |
public static void i(String tag, String message, Object... args) {
sLogger.i(tag, message, args);
} | @Test
public void infoWithThrowable() {
String tag = "TestTag";
String message = "Test message";
Throwable t = new Throwable();
LogManager.i(t, tag, message);
verify(logger).i(t, tag, message);
} |
public String parse(Function<String, String> propertyMapping) {
init();
boolean inPrepare = false;
char[] expression = new char[128];
int expressionPos = 0;
while (next()) {
if (isPrepare()) {
inPrepare = true;
} else if (inPrepare && isP... | @Test
public void testLargeExpr() {
String expr = "";
for (int i = 0; i < 1000; i++) {
expr += "expr_" + i;
}
String result = TemplateParser.parse("${"+expr+"}", Function.identity());
assertEquals(expr,result);
} |
int preferredLocalParallelism() {
if (options.containsKey(SqlConnector.OPTION_PREFERRED_LOCAL_PARALLELISM)) {
return Integer.parseInt(options.get(SqlConnector.OPTION_PREFERRED_LOCAL_PARALLELISM));
}
return StreamKafkaP.PREFERRED_LOCAL_PARALLELISM;
} | @Test
public void when_preferredLocalParallelism_isNotDefined_then_useDefault() {
KafkaTable table = new KafkaTable(
null, null, null, null, null, null, null,
emptyMap(),
null, null, null, null, null
);
assertThat(table.preferredLocalParalleli... |
@Override
public boolean add(Integer integer) {
throw new UnsupportedOperationException("RangeSet is immutable");
} | @Test
public void equals2() throws Exception {
IntSet rs = new RangeSet(4);
Set<Integer> hashSet = new HashSet<>();
hashSet.add(0);
hashSet.add(1);
hashSet.add(2);
// Verify equals both ways
assertNotEquals(rs, hashSet);
assertNotEquals(hashSet, rs);
hashSet.a... |
@Override
public WebSocketClientExtension handshakeExtension(WebSocketExtensionData extensionData) {
if (!PERMESSAGE_DEFLATE_EXTENSION.equals(extensionData.name())) {
return null;
}
boolean succeed = true;
int clientWindowSize = MAX_WINDOW_SIZE;
int serverWindowS... | @Test
public void testNormalHandshake() {
PerMessageDeflateClientExtensionHandshaker handshaker =
new PerMessageDeflateClientExtensionHandshaker();
WebSocketClientExtension extension = handshaker.handshakeExtension(
new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTEN... |
@Override
public int compareTo(SegmentPointer other) {
if (idPage == other.idPage) {
return Long.compare(offset, other.offset);
} else {
return Integer.compare(idPage, other.idPage);
}
} | @Test
public void testCompareInDifferentSegments() {
final SegmentPointer minor = new SegmentPointer(1, 10);
final SegmentPointer otherMinor = new SegmentPointer(1, 10);
final SegmentPointer major = new SegmentPointer(2, 4);
assertEquals(-1, minor.compareTo(major), "minor is less th... |
public String ensureVideosFolder() throws IOException, InvalidTokenException {
String rootFolder = ensureRootFolder();
if (!videosEnsured) {
ensureFolder(rootFolder, VIDEOS_NAME);
videosEnsured = true;
}
return rootFolder + "/" + VIDEOS_NAME;
} | @Test
public void testEnsureVideosFolder() throws Exception {
server.enqueue(new MockResponse().setResponseCode(200));
client.ensureRootFolder();
assertEquals(1, server.getRequestCount());
server.takeRequest();
server.enqueue(new MockResponse().setResponseCode(200));
client.ensureVideosFolde... |
public static Configuration adjustForLocalExecution(Configuration config) {
UNUSED_CONFIG_OPTIONS.forEach(
option -> warnAndRemoveOptionHasNoEffectIfSet(config, option));
setConfigOptionToPassedMaxIfNotSet(
config, TaskManagerOptions.CPU_CORES, LOCAL_EXECUTION_CPU_CORES)... | @Test
public void testNetworkMaxAdjustForLocalExecutionIfMinSet() {
MemorySize networkMemorySize = MemorySize.ofMebiBytes(1);
Configuration configuration = new Configuration();
configuration.set(TaskManagerOptions.NETWORK_MEMORY_MIN, networkMemorySize);
TaskExecutorResourceUtils.adju... |
public static boolean dumpTag(String dataId, String group, String tenant, String tag, String content,
long lastModifiedTs, String encryptedDataKey4Tag) {
final String groupKey = GroupKey2.getKey(dataId, group, tenant);
makeSure(groupKey, null);
final int lockResult = tryWrit... | @Test
void testDumpTag() throws Exception {
String dataId = "dataIdtestDumpTag133323";
String group = "group11";
String tenant = "tenant112";
String content = "mockContnet11";
String tag = "tag12345";
String groupKey = GroupKey2.getKey(dataId, group, tenant);
... |
@Override
public SocialUserDO getSocialUser(Long id) {
return socialUserMapper.selectById(id);
} | @Test
public void testGetSocialUser() {
// 准备参数
Integer userType = UserTypeEnum.ADMIN.getValue();
Integer type = SocialTypeEnum.GITEE.getType();
String code = "tudou";
String state = "yuanma";
// mock 社交用户
SocialUserDO socialUserDO = randomPojo(SocialUserDO.cl... |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
MetaData.Builder metaData = new MetaData.Builder(sanit... | @Test
public void sanitizesMetricName() throws Exception {
Counter counter = registry.counter("dash-illegal.slash/illegal");
counter.inc();
reporter.report();
ValueList values = receiver.next();
assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_illegal");
} |
public static Set<String> findKeywordsFromCrashReport(String crashReport) {
Matcher matcher = CRASH_REPORT_STACK_TRACE_PATTERN.matcher(crashReport);
Set<String> result = new HashSet<>();
if (matcher.find()) {
for (String line : matcher.group("stacktrace").split("\\n")) {
... | @Test
public void twilightforest() throws IOException {
assertEquals(
Collections.singleton("twilightforest"),
CrashReportAnalyzer.findKeywordsFromCrashReport(loadLog("/crash-report/mod/twilightforest.txt")));
} |
public static IdGenerator incrementingLongs() {
AtomicLong longs = new AtomicLong();
return () -> Long.toString(longs.incrementAndGet());
} | @Test
public void incrementingIndependent() {
IdGenerator gen = IdGenerators.incrementingLongs();
IdGenerator otherGen = IdGenerators.incrementingLongs();
assertThat(gen.getId(), equalTo("1"));
assertThat(gen.getId(), equalTo("2"));
assertThat(otherGen.getId(), equalTo("1"));
} |
public void setProperty(String name, String value) {
if (value == null) {
return;
}
Method setter = aggregationAssessor.findSetterMethod(name);
if (setter == null) {
addWarn("No setter for property [" + name + "] in " + objClass.getName() + ".");
} else {
... | @Test
public void testSetCamelProperty() {
setter.setProperty("camelCase", "trot");
assertEquals("trot", house.getCamelCase());
setter.setProperty("camelCase", "gh");
assertEquals("gh", house.getCamelCase());
} |
@Override
public long getSequence() {
return sequence.get();
} | @Test
public void testGetSequence() {
assertEquals(0, sequencer.getSequence());
} |
@Override
public boolean supportsCatalogsInDataManipulation() {
return false;
} | @Test
void assertSupportsCatalogsInDataManipulation() {
assertFalse(metaData.supportsCatalogsInDataManipulation());
} |
@Override
public void execute(Context context) {
editionProvider.get().ifPresent(edition -> {
if (!edition.equals(EditionProvider.Edition.COMMUNITY)) {
return;
}
Map<String, Integer> filesPerLanguage = reportReader.readMetadata().getNotAnalyzedFilesByLanguageMap()
.entrySet()
... | @Test
public void adds_warning_in_SQ_community_edition_if_there_are_cpp_files() {
when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY));
reportReader.setMetadata(ScannerReport.Metadata.newBuilder()
.putNotAnalyzedFilesByLanguage("C++", 1)
.build());
underTest.... |
public void command(String primaryCommand, SecureConfig config, String... allArguments) {
terminal.writeLine("");
final Optional<CommandLine> commandParseResult;
try {
commandParseResult = Command.parse(primaryCommand, allArguments);
} catch (InvalidCommandException e) {
... | @Test
public void testRemoveWithNoIdentifiers() {
final String expectedMessage = "ERROR: You must supply a value to remove.";
createKeyStore();
String[] nullArguments = null;
cli.command("remove", newStoreConfig.clone(), nullArguments);
assertThat(terminal.out).containsIgno... |
@Override
public QualityGate.Condition apply(Condition input) {
String metricKey = input.getMetric().getKey();
ConditionStatus conditionStatus = statusPerConditions.get(input);
checkState(conditionStatus != null, "Missing ConditionStatus for condition on metric key %s", metricKey);
return builder
... | @Test
public void apply_converts_key_from_metric() {
ConditionToCondition underTest = new ConditionToCondition(of(SOME_CONDITION, SOME_CONDITION_STATUS));
assertThat(underTest.apply(SOME_CONDITION).getMetricKey()).isEqualTo(METRIC_KEY);
} |
public static KafkaUserModel fromCrd(KafkaUser kafkaUser,
String secretPrefix,
boolean aclsAdminApiSupported) {
KafkaUserModel result = new KafkaUserModel(kafkaUser.getMetadata().getNamespace(),
kafkaUser.getMetada... | @Test
public void testFromCrdTlsUserWith64CharTlsUsernameValid() {
// 64 characters => Should be still OK
KafkaUser notTooLong = new KafkaUserBuilder(tlsUser)
.editMetadata()
.withName("User123456789012345678901234567890123456789012345678901234567890")
... |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_density_any() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("anydpi", config);
assertThat(config.density).isEqualTo(DENSITY_ANY);
} |
@Override
public KvMetadata resolveMetadata(
boolean isKey,
List<MappingField> resolvedFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void test_resolveMetadataWithExistingClassDefinition(boolean key, String prefix) {
InternalSerializationService ss = new DefaultSerializationServiceBuilder().build();
ClassDefinition classDefinition =
... |
static BuildResult fromImage(Image image, Class<? extends BuildableManifestTemplate> targetFormat)
throws IOException {
ImageToJsonTranslator imageToJsonTranslator = new ImageToJsonTranslator(image);
BlobDescriptor containerConfigurationBlobDescriptor =
Digests.computeDigest(imageToJsonTranslator.... | @Test
public void testFromImage() throws IOException {
Image image1 = Image.builder(V22ManifestTemplate.class).setUser("user").build();
Image image2 = Image.builder(V22ManifestTemplate.class).setUser("user").build();
Image image3 = Image.builder(V22ManifestTemplate.class).setUser("anotherUser").build();
... |
@Override
public GETATTR3Response getattr(XDR xdr, RpcInfo info) {
return getattr(xdr, getSecurityHandler(info), info.remoteAddress());
} | @Test(timeout = 60000)
public void testGetattr() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
... |
@Override
public ResultSet getTables(Connection connection, String dbName) throws SQLException {
String tableTypes = properties.get("table_types");
if (null != tableTypes) {
String[] tableTypesArray = tableTypes.split(",");
if (tableTypesArray.length == 0) {
t... | @Test
public void testListTableNames() throws SQLException {
new Expectations() {
{
dataSource.getConnection();
result = connection;
minTimes = 0;
connection.getCatalog();
result = "t1";
minTimes = 0... |
@Override
@TpsControl(pointName = "ConfigPublish")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigPublishResponse handle(ConfigPublishRequest request, RequestMeta meta) throws NacosException {
... | @Test
void testTagPublishCas() throws NacosException, InterruptedException {
String dataId = "testTagPublishCas";
String group = "group";
ConfigPublishRequest configPublishRequest = new ConfigPublishRequest();
configPublishRequest.setDataId(dataId);
configPublishRequest.setGr... |
@Override
public void trace(String msg) {
logger.trace(msg);
} | @Test
public void testTraceWithException() {
Log mockLog = mock(Log.class);
InternalLogger logger = new CommonsLogger(mockLog, "foo");
logger.trace("a", e);
verify(mockLog).trace("a", e);
} |
@SuppressWarnings({"rawtypes", "unchecked"})
public <T extends Gauge> T gauge(String name) {
return (T) getOrAdd(name, MetricBuilder.GAUGES);
} | @Test
public void accessingASettableGaugeRegistersAndReusesIt() {
final SettableGauge<String> gauge1 = registry.gauge("thing");
gauge1.setValue("Test");
final Gauge<String> gauge2 = registry.gauge("thing");
assertThat(gauge1).isSameAs(gauge2);
assertThat(gauge2.getValue()).i... |
public void inputWatermark(Watermark watermark, int channelIndex, DataOutput<?> output)
throws Exception {
final SubpartitionStatus subpartitionStatus;
if (watermark instanceof InternalWatermark) {
int subpartitionStatusIndex = ((InternalWatermark) watermark).getSubpartitionIndex... | @Test
void testSingleInputIncreasingWatermarks() throws Exception {
StatusWatermarkOutput valveOutput = new StatusWatermarkOutput();
StatusWatermarkValve valve = new StatusWatermarkValve(1);
valve.inputWatermark(new Watermark(0), 0, valveOutput);
assertThat(valveOutput.popLastSeenOu... |
private static byte[] getDateSigningKey(String secret, String date, String signMethod) {
try {
Mac mac = Mac.getInstance(signMethod);
mac.init(new SecretKeySpec((PREFIX + secret).getBytes(StandardCharsets.UTF_8), signMethod));
return mac.doFinal(date.getBytes(StandardCharsets... | @Test
public void testGetDateSigningKey() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String secret = "mySecret";
String date = "20220101";
String signMethod = "HmacSHA256";
byte[] expectArray = new byte[]{-96, 108, 42, 75, -59, 121, -63, 108, -3... |
@Override
public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId,
final ProcessorContext context,
final long streamTime) {
final TimestampedSegment segment = super.getOrCreateSegmentIfLiv... | @Test
public void shouldCloseAllOpenSegments() {
final TimestampedSegment first = segments.getOrCreateSegmentIfLive(0, context, -1L);
final TimestampedSegment second = segments.getOrCreateSegmentIfLive(1, context, -1L);
final TimestampedSegment third = segments.getOrCreateSegmentIfLive(2, co... |
public void removeRuleData(final String pluginName) {
RULE_DATA_MAP.remove(pluginName);
} | @Test
public void testRemoveRuleData() throws NoSuchFieldException, IllegalAccessException {
RuleData cacheRuleData = RuleData.builder().id("1").pluginName(mockPluginName1).sort(1).build();
MatchDataCache.getInstance().cacheRuleData(path1, cacheRuleData, 100, 100);
MatchDataCache.getInstance... |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
} |
@Override
public long getLong(PropertyKey key) {
// Low-precision types int can be implicitly converted to high-precision types long
// without loss of precision
checkArgument(key.getType() == PropertyKey.PropertyType.LONG
|| key.getType() == PropertyKey.PropertyType.INTEGER);
return ((Number)... | @Test
public void getLong() {
// bigger than MAX_INT
mConfiguration.set(PropertyKey.JOB_MASTER_JOB_CAPACITY, 12345678910L);
assertEquals(12345678910L,
mConfiguration.getLong(PropertyKey.JOB_MASTER_JOB_CAPACITY));
} |
@Override
public BackgroundException map(final IOException e) {
if(ExceptionUtils.getRootCause(e) != e && ExceptionUtils.getRootCause(e) instanceof SSHException) {
return this.map((SSHException) ExceptionUtils.getRootCause(e));
}
final StringBuilder buffer = new StringBuilder();
... | @Test
public void testSocketTimeout() {
assertEquals(ConnectionTimeoutException.class, new SFTPExceptionMappingService()
.map(new SocketTimeoutException()).getClass());
assertEquals(ConnectionTimeoutException.class, new SFTPExceptionMappingService()
.map("message", new Socket... |
public static TimestampExtractionPolicy create(
final KsqlConfig ksqlConfig,
final LogicalSchema schema,
final Optional<TimestampColumn> timestampColumn
) {
if (!timestampColumn.isPresent()) {
return new MetadataTimestampExtractionPolicy(getDefaultTimestampExtractor(ksqlConfig));
}
... | @Test
public void shouldFailIfStringTimestampTypeAndFormatNotSupplied() {
// Given:
final String field = "my_string_field";
final LogicalSchema schema = schemaBuilder2
.valueColumn(ColumnName.of(field.toUpperCase()), SqlTypes.STRING)
.build();
// When:
assertThrows(
KsqlEx... |
@PublicAPI(usage = ACCESS)
public static Transformer matching(String packageIdentifier) {
PackageMatchingSliceIdentifier sliceIdentifier = new PackageMatchingSliceIdentifier(packageIdentifier);
String description = "slices matching " + sliceIdentifier.getDescription();
return new Transformer... | @Test
public void default_naming_slices() {
JavaClasses classes = importClassesWithContext(Object.class, String.class, Pattern.class);
DescribedIterable<Slice> slices = Slices.matching("java.(*)..").transform(classes);
assertThat(slices).extractingResultOf("getDescription").containsOnly("Sl... |
public IndexingResults bulkIndex(final List<MessageWithIndex> messageList) {
return bulkIndex(messageList, false, null);
} | @Test
public void bulkIndexingShouldAccountMessageSizesForSystemTrafficSeparately() throws IOException {
final IndexSet indexSet = mock(IndexSet.class);
final List<MessageWithIndex> messageList = List.of(
new MessageWithIndex(wrap(messageWithSize(17)), indexSet),
new ... |
@Override
public void removeSubscriber(Subscriber subscriber) {
subscribers.remove(subscriber);
} | @Test
void testRemoveSubscriber() {
publisher.addSubscriber(subscriber);
assertEquals(1, publisher.getSubscribers().size());
publisher.removeSubscriber(subscriber);
assertEquals(0, publisher.getSubscribers().size());
} |
@Override
public short getTypeCode() {
return MessageType.TYPE_REG_RM_RESULT;
} | @Test
public void getTypeCode() {
RegisterRMResponse registerRMResponse = new RegisterRMResponse();
Assertions.assertEquals(MessageType.TYPE_REG_RM_RESULT, registerRMResponse.getTypeCode());
} |
@Override
public Map<String, Object> batchInsertOrUpdate(List<ConfigAllInfo> configInfoList, String srcUser, String srcIp,
Map<String, Object> configAdvanceInfo, SameConfigPolicy policy) throws NacosException {
int succCount = 0;
int skipCount = 0;
List<Map<String, String>> failD... | @Test
void testBatchInsertOrUpdateOverwrite() throws NacosException {
List<ConfigAllInfo> configInfoList = new ArrayList<>();
//insert direct
configInfoList.add(createMockConfigAllInfo(0));
//exist config and overwrite
configInfoList.add(createMockConfigAllInfo(1));
/... |
@Override
public OSGeneratedQueryContext generate(Query query, Set<SearchError> validationErrors, DateTimeZone timezone) {
final BackendQuery backendQuery = query.query();
final Set<SearchType> searchTypes = query.searchTypes();
final QueryBuilder normalizedRootQuery = translateQueryString... | @Test
public void generatedContextHasQueryThatIncludesSearchFilters() {
final ImmutableList<UsedSearchFilter> usedSearchFilters = ImmutableList.of(
InlineQueryStringSearchFilter.builder().title("").description("").queryString("method:GET").build(),
ReferencedQueryStringSearch... |
public void mergeMetric(String name, RuntimeMetric metric)
{
metrics.computeIfAbsent(name, k -> new RuntimeMetric(name, metric.getUnit())).mergeWith(metric);
} | @Test
public void testMergeMetric()
{
RuntimeStats stats1 = new RuntimeStats();
stats1.addMetricValue(TEST_METRIC_NAME_1, NONE, 2);
stats1.addMetricValue(TEST_METRIC_NAME_1, NONE, 3);
stats1.addMetricValue(TEST_METRIC_NAME_NANO_1, NANO, 3);
RuntimeStats stats2 = new Runt... |
@Override
public void removeSelector(final SelectorData selectorData) {
if (Objects.isNull(selectorData.getId())) {
return;
}
ApplicationConfigCache.getInstance().invalidate(selectorData.getId());
} | @Test
public void testRemoveSelector() {
when(selectorData.getId()).thenReturn(null);
grpcPluginDataHandler.removeSelector(selectorData);
when(selectorData.getId()).thenReturn("selectorId");
grpcPluginDataHandler.removeSelector(selectorData);
final List<ShenyuServiceInstance>... |
@GetMapping("")
public ShenyuAdminResult queryPlugins(final String name, final Integer enabled,
@NotNull final Integer currentPage,
@NotNull final Integer pageSize) {
CommonPager<PluginVO> commonPager = pluginService.listByP... | @Test
public void testQueryPlugins() throws Exception {
final PageParameter pageParameter = new PageParameter();
List<PluginVO> pluginVOS = new ArrayList<>();
pluginVOS.add(pluginVO);
final CommonPager<PluginVO> commonPager = new CommonPager<>();
commonPager.setPage(pageParam... |
public static Schema schemaFor(Table table, long snapshotId) {
Snapshot snapshot = table.snapshot(snapshotId);
Preconditions.checkArgument(snapshot != null, "Cannot find snapshot with ID %s", snapshotId);
Integer schemaId = snapshot.schemaId();
// schemaId could be null, if snapshot was created before ... | @Test
public void schemaForRef() {
Schema initialSchema =
new Schema(
required(1, "id", Types.IntegerType.get()),
required(2, "data", Types.StringType.get()));
assertThat(table.schema().asStruct()).isEqualTo(initialSchema.asStruct());
assertThat(SnapshotUtil.schemaFor(tabl... |
public static BufferDebloatConfiguration fromConfiguration(ReadableConfig config) {
Duration targetTotalBufferSize = config.get(BUFFER_DEBLOAT_TARGET);
int maxBufferSize =
Math.toIntExact(config.get(TaskManagerOptions.MEMORY_SEGMENT_SIZE).getBytes());
int minBufferSize =
... | @Test
public void testMinGreaterThanMaxBufferSize() {
final Configuration config = new Configuration();
config.set(TaskManagerOptions.MIN_MEMORY_SEGMENT_SIZE, new MemorySize(50));
config.set(TaskManagerOptions.MEMORY_SEGMENT_SIZE, new MemorySize(49));
assertThrows(
Il... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP);
if (args.isEmpty()) {
terminal.println(restClient.getServerAddress());
return;
} else {
final String serverAddress = args.get(0);
restClient.setS... | @Test
public void shouldResetCliForNewServer() {
// When:
command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal);
// Then:
verify(resetCliForNewServer).fire();
} |
public static <InputT, AccumT, OutputT>
CombineFnWithContext<InputT, AccumT, OutputT> toFnWithContext(
GlobalCombineFn<InputT, AccumT, OutputT> globalCombineFn) {
if (globalCombineFn instanceof CombineFnWithContext) {
@SuppressWarnings("unchecked")
CombineFnWithContext<InputT, AccumT, Ou... | @Test
public void testToFnWithContextIdempotent() throws Exception {
CombineFnWithContext<Integer, int[], Integer> fnWithContext =
CombineFnUtil.toFnWithContext(Sum.ofIntegers());
assertTrue(fnWithContext == CombineFnUtil.toFnWithContext(fnWithContext));
} |
public Exception getException() {
if (exception != null) return exception;
try {
final Class<? extends Exception> exceptionClass = ReflectionUtils.toClass(getExceptionType());
if (getExceptionCauseType() != null) {
final Class<? extends Exception> exceptionCauseCl... | @Test
void getExceptionForJobMethodNotFoundException() {
final FailedState failedState = new FailedState("JobRunr message", new JobMethodNotFoundException(jobDetails().build()));
setInternalState(failedState, "exception", null);
assertThat(failedState.getException())
.isIns... |
@Override
public int solve(ArrayList<Character> elements) throws Exception {
return 0;
} | @Test
public void testSolve() throws Exception {
Controlador controlador = new Controlador();
ArrayList<Character> elements = new ArrayList<>();
elements.add('1');
elements.add('2');
elements.add('+');
elements.add('4');
elements.add('*');
elements.add... |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test(dataProvider = "validateQueryParameter")
public void testQueryParameterValidation(String paramKey, Class<?> dataType,
Object paramValue,
boolean isValid,
String errorMessage)
{
... |
@Nullable public String getValue(@Nullable TraceContext context) {
if (context == null) return null;
return this.context.getValue(this, context);
} | @Test void getValue_extracted_invalid() {
assertThatThrownBy(() -> REQUEST_ID.getValue((TraceContextOrSamplingFlags) null))
.isInstanceOf(NullPointerException.class);
} |
public BigMatrix aat() {
BigMatrix C = new BigMatrix(m, m);
C.mm(NO_TRANSPOSE, this, TRANSPOSE, this);
C.uplo(LOWER);
return C;
} | @Test
public void testAAT() {
System.out.println("AAT");
BigMatrix c = matrix.aat();
assertEquals(c.nrow(), 3);
assertEquals(c.ncol(), 3);
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < C[i].length; j++) {
assertEquals(C[i][j], c.get(i, j... |
@ThriftField(1)
public boolean isAll()
{
return all;
} | @Test
public void testFromValueSetNone()
{
PrestoThriftValueSet thriftValueSet = fromValueSet(ValueSet.none(HYPER_LOG_LOG));
assertNotNull(thriftValueSet.getAllOrNoneValueSet());
assertFalse(thriftValueSet.getAllOrNoneValueSet().isAll());
} |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldLoadConfigWithConfigRepoAndPluginName() throws Exception {
CruiseConfig cruiseConfig = xmlLoader.loadConfigHolder(configWithConfigRepos(
"""
<config-repos>
<config-repo pluginId="myplugin" id="repo-id">
... |
@Override
public QueryCacheScheduler getQueryCacheScheduler() {
return queryCacheScheduler;
} | @Test
public void testGetQueryCacheScheduler() {
QueryCacheScheduler scheduler = context.getQueryCacheScheduler();
assertNotNull(scheduler);
final QuerySchedulerTask task = new QuerySchedulerTask();
scheduler.execute(task);
final QuerySchedulerRepetitionTask repetitionTask ... |
@Override
public List<T> getValue() {
// Static arrays cannot be modified
return Collections.unmodifiableList(value);
} | @Test
public void canBeInstantiatedWithLessThan32Elements() {
final StaticArray<Uint> array = new StaticArray32<>(arrayOfUints(32));
assertEquals(array.getValue().size(), (32));
} |
public static <T> T[] replaceFirst(T[] src, T oldValue, T[] newValues) {
int index = indexOf(src, oldValue);
if (index == -1) {
return src;
}
T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length - 1 + newValues.length);
// copy the first p... | @Test
public void replace_whenInBeginning() {
Integer[] result = replaceFirst(new Integer[]{6, 3, 4}, 6, new Integer[]{1, 2});
System.out.println(Arrays.toString(result));
assertArrayEquals(new Integer[]{1, 2, 3, 4}, result);
} |
@Override
public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
// 1. 执行请求
// 参考链接 https://api.aliyun.com/document/Dysmsapi/2017-05-25/QuerySmsTemplate
TreeMap<String, Object> queryParam = new TreeMap<>();
queryParam.put("TemplateCode", apiTemplateId);
... | @Test
public void testGetSmsTemplate() throws Throwable {
try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) {
// 准备参数
String apiTemplateId = randomString();
// mock 方法
httpUtilsMockedStatic.when(() -> HttpUtils.post(anyString(),... |
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception {
return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM);
} | @Test
public void testSupplier() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
ConnectException e = assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, null, Duration.ofMillis(100), 10, moc... |
public static BigDecimal generateMaximumNumberWithPrecision(int precision) {
return (new BigDecimal("10")).pow(precision).subtract(new BigDecimal("1"));
} | @Test
public void testGenerateMaximumNumberWithPrecision() {
int[] testCases = { 1, 3, 10, 38, 128 };
for (int precision : testCases) {
BigDecimal bd = BigDecimalUtils.generateMaximumNumberWithPrecision(precision);
assertEquals(bd.precision(), precision);
assertEquals(bd.add(new BigDecimal("... |
synchronized void evict() {
if (tail == null) {
return;
}
final LRUNode eldest = tail;
currentSizeBytes -= eldest.size();
remove(eldest);
cache.remove(eldest.key);
if (eldest.entry.isDirty()) {
flush(eldest);
}
totalCacheSiz... | @Test
public void shouldNotThrowNullPointerWhenCacheIsEmptyAndEvictionCalled() {
cache.evict();
} |
@Override
public BroadcastRule build(final BroadcastRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType,
final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceC... | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void assertBuild() {
BroadcastRuleConfiguration ruleConfig = mock(BroadcastRuleConfiguration.class);
DatabaseRuleBuilder builder = OrderedSPILoader.getServices(DatabaseRuleBuilder.class, Collections.singleton(ruleConfig)).get(ruleConfig);
... |
@Override
public Object[] getRowFromCache( RowMetaInterface lookupMeta, Object[] lookupRow ) throws KettleException {
if ( stepData.hasDBCondition ) {
// actually, there was no sense in executing SELECT from db in this case,
// should be reported as improvement
return null;
}
SearchingC... | @Test
public void lookup_Finds_WithBetweenOperator() throws Exception {
RowMeta meta = keysMeta.clone();
meta.setValueMeta( 3, new ValueMetaDate() );
meta.addValueMeta( new ValueMetaInteger() );
ReadAllCache cache = buildCache( "<>,IS NOT NULL,BETWEEN,IS NULL" );
Object[] found = cache.getRowFrom... |
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors(
ReconnaissanceReport reconnaissanceReport) {
return tsunamiPlugins.entrySet().stream()
.filter(entry -> isVulnDetector(entry.getKey()))
.map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc... | @Test
public void getVulnDetectors_whenNoVulnDetectorsInstalled_returnsEmptyList() {
NetworkService fakeNetworkService1 =
NetworkService.newBuilder()
.setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80))
.setTransportProtocol(TransportProtocol.TCP)
.setS... |
public static List<FieldValueSetter> getSetters(
TypeDescriptor<?> typeDescriptor,
Schema schema,
FieldValueTypeSupplier fieldValueTypeSupplier,
TypeConversionsFactory typeConversionsFactory) {
// Return the setters, ordered by their position in the schema.
return CACHED_SETTERS.computeI... | @Test
public void testGeneratedByteBufferSetters() {
POJOWithByteArray pojo = new POJOWithByteArray();
List<FieldValueSetter> setters =
POJOUtils.getSetters(
new TypeDescriptor<POJOWithByteArray>() {},
POJO_WITH_BYTE_ARRAY_SCHEMA,
JavaFieldTypeSupplier.INSTANCE,
... |
@Override
public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) {
if (!shouldHandle(instances)) {
return instances;
}
List<Object> result = getTargetInstancesByRules(targetName, instances);
return super.handle(targetName, result, ... | @Test
public void testGetTargetInstancesByTagRulesWithPolicySceneThree() {
RuleInitializationUtils.initAZTagMatchTriggerThresholdMinAllInstancesPolicyRule();
List<Object> instances = new ArrayList<>();
ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.... |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesString() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "string");
JType result = rule.apply("fooBar", objectNode, null, jpack... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.precision(column.getColumnLength())
.length(column.getColumn... | @Test
public void testReconvertFloat() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.FLOAT_TYPE).build();
BasicTypeDefine typeDefine = IrisTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName());
... |
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
try {
return new SchemaAndValue(Schema.OPTIONAL_STRING_SCHEMA, deserializer.deserialize(topic, value));
} catch (SerializationException e) {
throw new DataException("Failed to deserialize string: ", e... | @Test
public void testBytesNullToString() {
SchemaAndValue data = converter.toConnectData(TOPIC, null);
assertEquals(Schema.OPTIONAL_STRING_SCHEMA, data.schema());
assertNull(data.value());
} |
@Override
protected String buildHandle(final List<URIRegisterDTO> uriList, final SelectorDO selectorDO) {
String handleAdd;
List<WebSocketUpstream> addList = buildWebSocketUpstreamList(uriList);
List<WebSocketUpstream> canAddList = new CopyOnWriteArrayList<>();
List<WebSocketUpstream... | @Test
public void testBuildHandle() {
URIRegisterDTO dto = new URIRegisterDTO();
dto.setPort(8080);
dto.setHost("host");
dto.setProtocol("http");
List<URIRegisterDTO> uriList = Collections.singletonList(dto);
SelectorDO selectorDO = mock(SelectorDO.class);
whe... |
@Override
public void upgrade() {
if (hasBeenRunSuccessfully()) {
LOG.debug("Migration already completed.");
return;
}
final Map<String, String> savedSearchToViewsMap = new HashMap<>();
final Map<View, Search> newViews = this.savedSearchService.streamAll()
... | @Test
public void runsIfNoSavedSearchesArePresent() {
this.migration.upgrade();
} |
static Object parseCell(String cell, Schema.Field field) {
Schema.FieldType fieldType = field.getType();
try {
switch (fieldType.getTypeName()) {
case STRING:
return cell;
case INT16:
return Short.parseShort(cell);
case INT32:
return Integer.parseInt(c... | @Test
public void givenIntegerWithSurroundingSpaces_throws() {
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" 12 ", 12);
Schema schema = Schema.builder().addInt32Field("an_integer").addStringField("a_string").build();
IllegalArgumentException e =
assertThrows(
IllegalA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.