focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void useSmsCode(SmsCodeUseReqDTO reqDTO) {
// 检测验证码是否有效
SmsCodeDO lastSmsCode = validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene());
// 使用验证码
smsCodeMapper.updateById(SmsCodeDO.builder().id(lastSmsCode.getId())
.used(true).usedTi... | @Test
public void testUseSmsCode_success() {
// 准备参数
SmsCodeUseReqDTO reqDTO = randomPojo(SmsCodeUseReqDTO.class, o -> {
o.setMobile("15601691300");
o.setScene(randomEle(SmsSceneEnum.values()).getScene());
});
// mock 数据
SqlConstants.init(DbType.MYSQL)... |
static ArgumentParser argParser() {
ArgumentParser parser = ArgumentParsers
.newArgumentParser("producer-performance")
.defaultHelp(true)
.description("This tool is used to verify the producer performance. To enable transactions, " +
"you c... | @Test
public void testFractionalThroughput() {
String[] args = new String[] {
"--topic", "Hello-Kafka",
"--num-records", "5",
"--throughput", "1.25",
"--record-size", "100",
"--producer-props", "bootstrap.servers=localhost:9000"};
ArgumentP... |
public Page getRegion(int positionOffset, int length)
{
if (positionOffset < 0 || length < 0 || positionOffset + length > positionCount) {
throw new IndexOutOfBoundsException(format("Invalid position %s and length %s in page with %s positions", positionOffset, length, positionCount));
}
... | @Test(expectedExceptions = IndexOutOfBoundsException.class, expectedExceptionsMessageRegExp = "Invalid position 1 and length 1 in page with 0 positions")
public void testGetRegionExceptions()
{
new Page(0).getRegion(1, 1);
} |
@Override
@MethodNotAvailable
public void removeAll() {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testRemoveAllWithKeys() {
adapter.removeAll(singleton(42));
} |
public static AclOperation getDeniedOperation(final String errorMessage) {
final Matcher matcher = DENIED_OPERATION_STRING_PATTERN.matcher(errorMessage);
if (matcher.matches()) {
return AclOperation.fromString(matcher.group(1));
} else {
return AclOperation.UNKNOWN;
}
} | @Test
public void shouldReturnUnknownDeniedOperationFromNoValidAuthorizationMessage() {
// When:
final AclOperation operation = SchemaRegistryUtil.getDeniedOperation(
"INVALID is denied operation Write on Subject: t2-value; error code: 40301");
// Then:
assertThat(operation, is(AclOperation.U... |
@Override
public void close() throws IOException {
if(close.get()) {
log.warn(String.format("Skip double close of stream %s", this));
return;
}
try {
if(buffer.size() > 0) {
proxy.write(buffer.toByteArray());
}
// Re... | @Test
public void testCopy2() throws Exception {
final ByteArrayOutputStream proxy = new ByteArrayOutputStream(40500);
final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768);
final byte[] content = RandomUtils.nextBytes(40500);
out.write(content, 0,... |
@Udf(description = "Splits a string into an array of substrings based on a delimiter.")
public List<String> split(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The delimiter to spli... | @Test
public void shouldSplitBytesByGivenMultipleBytesDelimiter() {
assertThat(
splitUdf.split(
ByteBuffer.wrap(new byte[]{'a', '-', '-', 'b'}),
ByteBuffer.wrap(new byte[]{'-', '-'})),
contains(
ByteBuffer.wrap(new byte[]{'a'}),
ByteBuffer.wrap(new b... |
@Override
@Deprecated
@SuppressWarnings("unchecked")
public <T extends Number> Counter<T> counter(String name, Class<T> type, Unit unit) {
if (Integer.class.equals(type)) {
return (Counter<T>) new DefaultCounter(unit).asIntCounter();
}
if (Long.class.equals(type)) {
return (Counter<T>) ne... | @Test
public void intCounterNullCheck() {
assertThatThrownBy(() -> new DefaultMetricsContext().counter("name", Integer.class, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid count unit: null");
} |
public synchronized Topology addSink(final String name,
final String topic,
final String... parentNames) {
internalTopologyBuilder.addSink(name, topic, null, null, null, parentNames);
return this;
} | @Test
public void shouldNotAllowNullNameWhenAddingSink() {
assertThrows(NullPointerException.class, () -> topology.addSink(null, "topic"));
} |
public void stop() {
registry.removeListener(listener);
listener.unregisterAll();
} | @Test
public void cleansUpAfterItselfWhenStopped() throws Exception {
reporter.stop();
try {
getAttributes("gauges", "gauge", "Value", "Number");
failBecauseExceptionWasNotThrown(InstanceNotFoundException.class);
} catch (InstanceNotFoundException e) {
}
... |
@Override
public int remainingCapacity() {
int sum = 0;
for (BlockingQueue<E> q : this.queues) {
sum += q.remainingCapacity();
}
return sum;
} | @Test
public void testInitialRemainingCapacity() {
assertEquals(10, fcq.remainingCapacity());
} |
@Override
public Optional<DiscreteResource> lookup(DiscreteResourceId id) {
return Optional.empty();
} | @Test
public void testLookup() {
assertThat(sut.lookup(Resources.discrete(DeviceId.deviceId("a")).id()), is(Optional.empty()));
} |
public static <IN1, IN2, OUT> TwoInputTransformation<IN1, IN2, OUT> getTwoInputTransformation(
String operatorName,
AbstractDataStream<IN1> inputStream1,
AbstractDataStream<IN2> inputStream2,
TypeInformation<OUT> outTypeInformation,
TwoInputStreamOperator<IN1,... | @Test
void testGetTwoInputTransformation() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
TwoInputNonBroadcastProcessOperator<Integer, Long, Long> operator =
new TwoInputNonBroadcastProcessOperator<>(
new StreamTestUtils.NoOpTwoInp... |
@Override
public void execute(Context context) {
try (StreamWriter<ProjectDump.Plugin> writer = dumpWriter.newStreamWriter(DumpElement.PLUGINS)) {
Collection<PluginInfo> plugins = pluginRepository.getPluginInfos();
for (PluginInfo plugin : plugins) {
ProjectDump.Plugin.Builder builder = Proje... | @Test
public void test_nullable_exported_fields() {
when(pluginRepository.getPluginInfos()).thenReturn(singletonList(
new PluginInfo("java")));
underTest.execute(new TestComputationStepContext());
ProjectDump.Plugin exportedPlugin = dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS).get(0);
... |
@Override
public Long createDiyPage(DiyPageCreateReqVO createReqVO) {
// 校验名称唯一
validateNameUnique(null, createReqVO.getTemplateId(), createReqVO.getName());
// 插入
DiyPageDO diyPage = DiyPageConvert.INSTANCE.convert(createReqVO);
diyPage.setProperty("{}");
diyPageMapp... | @Test
public void testCreateDiyPage_success() {
// 准备参数
DiyPageCreateReqVO reqVO = randomPojo(DiyPageCreateReqVO.class);
// 调用
Long diyPageId = diyPageService.createDiyPage(reqVO);
// 断言
assertNotNull(diyPageId);
// 校验记录的属性是否正确
DiyPageDO diyPage = diy... |
@Udf
public Integer abs(@UdfParameter final Integer val) {
return (val == null) ? null : Math.abs(val);
} | @Test
public void shouldHandlePositive() {
assertThat(udf.abs(1), is(1));
assertThat(udf.abs(1L), is(1L));
assertThat(udf.abs(1.0), is(1.0));
assertThat(udf.abs(new BigDecimal(1)), is(new BigDecimal(1).abs()));
} |
public static Date parseDate(final String str) {
try {
return new Date(TimeUnit.DAYS.toMillis(
LocalDate.parse(PartialStringToTimestampParser.completeDate(str))
.toEpochDay()));
} catch (DateTimeParseException e) {
throw new KsqlException("Failed to parse date '" + str
... | @Test
public void shouldParseDate() {
assertThat(SqlTimeTypes.parseDate("1990"), is(new Date(631152000000L)));
assertThat(SqlTimeTypes.parseDate("1990-01"), is(new Date(631152000000L)));
assertThat(SqlTimeTypes.parseDate("1990-01-01"), is(new Date(631152000000L)));
} |
@Override
public void deleteCategory(Long id) {
// 校验分类是否存在
validateProductCategoryExists(id);
// 校验是否还有子分类
if (productCategoryMapper.selectCountByParentId(id) > 0) {
throw exception(CATEGORY_EXISTS_CHILDREN);
}
// 校验分类是否绑定了 SPU
Long spuCount = pro... | @Test
public void testDeleteCategory_success() {
// mock 数据
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class);
productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbCategory.getId();
// 调用
productCategoryService.de... |
@Override
public int configInfoTagCount() {
ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_TAG);
String sql = configInfoTagMapper.count(null);
Integer result = jt.queryForObject(sql, Integer.... | @Test
void testConfigInfoTagCount() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//mock count
Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(308);
//execute & verify
int count = externalConfigInfoTagPersistS... |
private synchronized boolean validateClientAcknowledgement(long h) {
if (h < 0) {
throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h);
}
if (h > MASK) {
throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa... | @Test
public void testValidateClientAcknowledgement_rollover_edgecase_unsent() throws Exception
{
// Setup test fixture.
final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1;
final long h = MAX;
final long oldH = MAX - 1;
final Long lastUnackedX = null;
... |
@Override
public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets,
ListOffsetsOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future =
ListOffsetsHandler.newFuture(topicParti... | @Test
public void testListOffsetsLatestTierSpecSpecMinVersion() throws Exception {
Node node = new Node(0, "localhost", 8120);
List<Node> nodes = Collections.singletonList(node);
List<PartitionInfo> pInfos = new ArrayList<>();
pInfos.add(new PartitionInfo("foo", 0, node, new Node[]{n... |
public List<String> mergePartitions(
MergingStrategy mergingStrategy,
List<String> sourcePartitions,
List<String> derivedPartitions) {
if (!derivedPartitions.isEmpty()
&& !sourcePartitions.isEmpty()
&& mergingStrategy != MergingStrategy.EXCLUD... | @Test
void mergePartitionsFromBaseTable() {
List<String> sourcePartitions = Arrays.asList("col1", "col2");
List<String> mergePartitions =
util.mergePartitions(
getDefaultMergingStrategies().get(FeatureOption.PARTITIONS),
sourcePartition... |
@UdafFactory(description = "Compute sample standard deviation of column with type Double.",
aggregateSchema = "STRUCT<SUM double, COUNT bigint, M2 double>")
public static TableUdaf<Double, Struct, Double> stdDevDouble() {
return getStdDevImplementation(
0.0,
STRUCT_DOUBLE,
(agg, newV... | @Test
public void shouldCalculateStdDevDoubles() {
final TableUdaf<Double, Struct, Double> udaf = stdDevDouble();
Struct agg = udaf.initialize();
final Double[] values = new Double[] {10.2, 13.4, 14.5, 17.8};
for (final Double thisValue : values) {
agg = udaf.aggregate(thisValue, agg);
}
... |
protected String messageToString(Message message) {
switch (message.getMessageType()) {
case SYSTEM:
return message.getContent();
case USER:
return humanPrompt + message.getContent();
case ASSISTANT:
return assistantPrompt + mes... | @Test
public void testSystemMessageType() {
Message systemMessage = new SystemMessage("System message");
String expected = "System message";
Assert.assertEquals(expected, converter.messageToString(systemMessage));
} |
@Override
public Deserializer getDeserializer(String type) throws HessianProtocolException {
// 如果类型在过滤列表, 说明是jdk自带类, 直接委托父类处理
if (StringUtils.isEmpty(type) || ClassFilter.filterExcludeClass(type)) {
return super.getDeserializer(type);
}
// 如果是数组类型, 且在name过滤列表, 说明jdk类, ... | @Test
public void getDeserializer() throws Exception {
Assert.assertEquals(GenericClassDeserializer.class,
factory.getDeserializer(Class.class.getCanonicalName()).getClass());
Assert.assertEquals(GenericDeserializer.class,
factory.getDeserializer(GenericObject.class.getCanoni... |
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Merger<? super K, V> sessionMerger) {
return aggregate(initializer, sessionMerger, Materialized.with(null, null));
} | @Test
public void shouldNotHaveNullNamed2OnAggregate() {
assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, sessionMerger, (Named) null));
} |
public void addIndexes(int maxIndex, int[] dictionaryIndexes, int indexCount)
{
if (indexCount == 0 && indexRetainedBytes > 0) {
// Ignore empty segment, since there are other segments present.
return;
}
checkState(maxIndex >= lastMaxIndex, "LastMax is greater than the... | @Test
public void testEmptyDictionary()
{
DictionaryRowGroupBuilder rowGroupBuilder = new DictionaryRowGroupBuilder();
rowGroupBuilder.addIndexes(-1, new int[0], 0);
byte[] byteIndexes = getByteIndexes(rowGroupBuilder);
assertEquals(0, byteIndexes.length);
} |
@Udf
public <T> List<T> concat(
@UdfParameter(description = "First array of values") final List<T> left,
@UdfParameter(description = "Second array of values") final List<T> right) {
if (left == null && right == null) {
return null;
}
final int leftSize = left != null ? left.size() : 0;
... | @Test
public void shouldConcatArraysBothContainingNulls() {
final List<String> input1 = Arrays.asList(null, "foo", "bar");
final List<String> input2 = Arrays.asList("foo", null);
final List<String> result = udf.concat(input1, input2);
assertThat(result, is(Arrays.asList(null, "foo", "bar", "foo", null... |
public static Map<String, AdvertisedListener> validateAndAnalysisAdvertisedListener(ServiceConfiguration config) {
if (StringUtils.isBlank(config.getAdvertisedListeners())) {
return Collections.emptyMap();
}
Optional<String> firstListenerName = Optional.empty();
Map<String, L... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testWithoutListenerNameInAdvertisedListeners() {
ServiceConfiguration config = new ServiceConfiguration();
config.setAdvertisedListeners(" internal:pulsar://127.0.0.1:6660, internal:pulsar+ssl://127.0.0.1:6651");
config.s... |
@Override
public String requestMessageForLatestRevisionsSince(SCMPropertyConfiguration scmConfiguration, Map<String, String> materialData, String flyweightFolder, SCMRevision previousRevision) {
Map configuredValues = new LinkedHashMap();
configuredValues.put("scm-configuration", jsonResultMessageHa... | @Test
public void shouldBuildRequestBodyForLatestRevisionsSinceRequest() throws Exception {
Date timestamp = new SimpleDateFormat(DATE_FORMAT).parse("2011-07-13T19:43:37.100Z");
Map data = new LinkedHashMap();
data.put("dataKeyOne", "data-value-one");
data.put("dataKeyTwo", "data-val... |
@Override
@NonNull
public String getId() {
return ID;
} | @Test
public void shouldNotProvideIdForMissingCredentials() throws Exception {
User user = login();
String scmPath = "/organizations/" + getOrgName() + "/scm/git/";
String repoPath = scmPath + "?repositoryUrl=" + HTTPS_GITHUB_PUBLIC;
Map resp = new RequestBuilder(baseUrl)
... |
@Override
public boolean shouldCareAbout(Object entity) {
return securityConfigClasses.stream().anyMatch(aClass -> aClass.isAssignableFrom(entity.getClass()));
} | @Test
public void shouldCareAboutAdminsConfigChange() {
SecurityConfigChangeListener securityConfigChangeListener = new SecurityConfigChangeListener() {
@Override
public void onEntityConfigChange(Object entity) {
}
};
assertThat(securityConfigChangeListen... |
public static UExpressionStatement create(UExpression expression) {
return new AutoValue_UExpressionStatement(expression);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(UExpressionStatement.create(UFreeIdent.create("foo")))
.addEqualityGroup(
UExpressionStatement.create(
UBinary.create(Kind.PLUS, ULiteral.intLit(5), ULiteral.intLit(2))))
.testEquals();
} |
@Override
public TimeSlot apply(TimeSlot timeSlot, SegmentInMinutes segmentInMinutes) {
int segmentInMinutesDuration = segmentInMinutes.value();
Instant segmentStart = normalizeStart(timeSlot.from(), segmentInMinutesDuration);
Instant segmentEnd = normalizeEnd(timeSlot.to(), segmentInMinute... | @Test
void noNormalizationWhenSlotStartsAtSegmentStart() {
//given
Instant start = Instant.parse("2023-09-09T00:15:00Z");
Instant end = Instant.parse("2023-09-09T00:30:00Z");
TimeSlot timeSlot = new TimeSlot(start, end);
Instant start2 = Instant.parse("2023-09-09T00:30:00Z");... |
@Override
public Consumer createConsumer(Processor aProcessor) throws Exception {
// validate that all of the endpoint is configured properly
if (getMonitorType() != null) {
if (!isPlatformServer()) {
throw new IllegalArgumentException(ERR_PLATFORM_SERVER);
}... | @Test
public void noNotifyHighOrNotifyLow() throws Exception {
JMXEndpoint ep = context.getEndpoint(
"jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=gauge&observedAttribute=foo",
JMXEndpoint.class);
try {
ep.createConsumer(null);
... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testReturnCommittedTransactions() {
buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
ByteBuffer buffer = ByteBuffer.allocate(1024);
int currentOffset = 0;
... |
@Override
public void onMetaDataChanged(final List<MetaData> changed, final DataEventTypeEnum eventType) {
if (CollectionUtils.isEmpty(changed)) {
return;
}
this.updateMetaDataCache();
this.afterMetaDataChanged(changed, eventType);
} | @Test
public void testOnMetaDataChanged() {
List<MetaData> empty = Lists.newArrayList();
DataEventTypeEnum eventType = mock(DataEventTypeEnum.class);
listener.onMetaDataChanged(empty, eventType);
assertFalse(listener.getCache().containsKey(ConfigGroupEnum.META_DATA.name()));
... |
public CompletableFuture<NotifyClientTerminationResponse> notifyClientTermination(ProxyContext ctx,
NotifyClientTerminationRequest request) {
CompletableFuture<NotifyClientTerminationResponse> future = new CompletableFuture<>();
try {
String clientId = ctx.getClientID();
... | @Test
public void testConsumerNotifyClientTermination() throws Throwable {
ProxyContext context = createContext();
when(this.grpcClientSettingsManager.removeAndGetClientSettings(any())).thenReturn(Settings.newBuilder()
.setClientType(ClientType.PUSH_CONSUMER)
.build());
... |
public void setDisplayNameOrNull(String displayName) throws IOException {
setDisplayName(displayName);
} | @Test
public void testSetDisplayNameOrNull() throws Exception {
final String projectName = "projectName";
final String displayName = "displayName";
StubAbstractItem i = new StubAbstractItem();
i.doSetName(projectName);
assertNull(i.getDisplayNameOrNull());
i.setDispl... |
@Override
public PipelinedSubpartitionView createReadView(
BufferAvailabilityListener availabilityListener) {
synchronized (buffers) {
checkState(!isReleased);
checkState(
readView == null,
"Subpartition %s of is being (or already h... | @TestTemplate
void testIllegalReadViewRequest() throws Exception {
final PipelinedSubpartition subpartition = createSubpartition();
// Successful request
assertThat(subpartition.createReadView(new NoOpBufferAvailablityListener())).isNotNull();
assertThatThrownBy(() -> subpartition.... |
public Optional<ShardingTable> findShardingTableByActualTable(final String actualTableName) {
for (ShardingTable each : shardingTables.values()) {
if (each.isExisted(actualTableName)) {
return Optional.of(each);
}
}
return Optional.empty();
} | @Test
void assertFindTableRuleByActualTable() {
assertTrue(createMaximumShardingRule().findShardingTableByActualTable("table_0").isPresent());
} |
@CheckForNull
public View getView(final String name) {
ViewGroup group = Jenkins.get();
View view = null;
final StringTokenizer tok = new StringTokenizer(name, "/");
while (tok.hasMoreTokens()) {
String viewName = tok.nextToken();
view = group.getView(view... | @Test public void reportViewSpaceNameRequestAsIAE() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
final IllegalArgumentException e = assertThrows("No exception thrown. Expected IllegalArgume... |
@Override
public Integer doCall() throws Exception {
List<Row> rows = new ArrayList<>();
JsonObject plugins = loadConfig().getMap("plugins");
plugins.forEach((key, value) -> {
JsonObject details = (JsonObject) value;
String name = details.getStringOrDefault("name", ... | @Test
public void shouldGetDefaultPlugins() throws Exception {
PluginGet command = new PluginGet(new CamelJBangMain().withPrinter(printer));
command.all = true;
command.doCall();
List<String> output = printer.getLines();
Assertions.assertEquals(6, output.size());
Ass... |
@PublicEvolving
public static CongestionControlRateLimitingStrategyBuilder builder() {
return new CongestionControlRateLimitingStrategyBuilder();
} | @Test
void testInvalidMaxInFlightMessages() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(
() ->
CongestionControlRateLimitingStrategy.builder()
.setMaxInFlightRequests(1... |
public Path getLocalPathForWrite(String pathStr,
Configuration conf) throws IOException {
return getLocalPathForWrite(pathStr, SIZE_UNKNOWN, conf);
} | @Test(timeout = 30000)
public void testGetLocalPathForWriteForInvalidPaths() throws Exception {
conf.set(CONTEXT, " ");
try {
dirAllocator.getLocalPathForWrite("/test", conf);
fail("not throwing the exception");
} catch (IOException e) {
assertEquals("Incorrect exception message",
... |
public static void main(String[] args) throws IOException {
System.setProperty("hazelcast.tracking.server", "true");
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
printMemberPort(hz);
} | @Test
public void testMain() throws Exception {
System.setProperty("print.port", child.getName());
HazelcastMemberStarter.main(new String[]{});
assertEquals(1, Hazelcast.getAllHazelcastInstances().size());
assertTrue(child.exists());
} |
@VisibleForTesting
ClientConfiguration createBkClientConfiguration(MetadataStoreExtended store, ServiceConfiguration conf) {
ClientConfiguration bkConf = new ClientConfiguration();
if (conf.getBookkeeperClientAuthenticationPlugin() != null
&& conf.getBookkeeperClientAuthenticationPlu... | @Test
public void testSetMetadataServiceUriBookkeeperMetadataServiceUri() {
BookKeeperClientFactoryImpl factory = new BookKeeperClientFactoryImpl();
ServiceConfiguration conf = new ServiceConfiguration();
try {
{
String uri = "metadata-store:localhost:2181";
... |
public static String toAbsolute(String baseURL, String relativeURL) {
String relURL = relativeURL;
// Relative to protocol
if (relURL.startsWith("//")) {
return StringUtils.substringBefore(baseURL, "//") + "//"
+ StringUtils.substringAfter(relURL, "//");
}... | @Test
public void testToAbsoluteRelativeToProtocol() {
s = "//www.relative.com/e/f.html";
t = "https://www.relative.com/e/f.html";
assertEquals(t, HttpURL.toAbsolute(absURL, s));
} |
public String transform() throws ScanException {
StringBuilder stringBuilder = new StringBuilder();
compileNode(node, stringBuilder, new Stack<Node>());
return stringBuilder.toString();
} | @Test
public void literal() throws ScanException {
String input = "abv";
Node node = makeNode(input);
NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0);
assertEquals(input, nodeToStringTransformer.transform());
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) {
if ( n == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null"));
}
if ( scale == null ) {
return FEEL... | @Test
void invokeLargerScale() {
FunctionTestUtil.assertResult(decimalFunction.invoke(BigDecimal.valueOf(10.123456789), BigDecimal.valueOf(6))
, BigDecimal.valueOf(10.123457));
} |
public JSONObject set(String key, Object value) throws JSONException {
return set(key, value, null, false);
} | @Test
public void toBeanNullStrTest() {
final JSONObject json = JSONUtil.createObj(JSONConfig.create().setIgnoreError(true))//
.set("strValue", "null")//
.set("intValue", 123)//
// 子对象对应"null"字符串,如果忽略错误,跳过,否则抛出转换异常
.set("beanValue", "null")//
.set("list", JSONUtil.createArray().set("a").set("b"));
... |
public Set<ReplicatedRecord> getRecords() {
return new HashSet<>(storageRef.get().values());
} | @Test
public void testGetRecords() {
assertTrue(recordStore.getRecords().isEmpty());
recordStore.put("key1", "value1");
recordStore.put("key2", "value2");
assertEquals(2, recordStore.getRecords().size());
} |
@Override
public boolean sendHeartbeatMessage(int leaderId) {
var leaderInstance = instanceMap.get(leaderId);
return leaderInstance.isAlive();
} | @Test
void testSendHeartbeatMessage() {
var instance1 = new RingInstance(null, 1, 1);
Map<Integer, Instance> instanceMap = Map.of(1, instance1);
var messageManager = new RingMessageManager(instanceMap);
assertTrue(messageManager.sendHeartbeatMessage(1));
} |
@Override
public ClusterHealth checkCluster() {
checkState(!nodeInformation.isStandalone(), "Clustering is not enabled");
checkState(sharedHealthState != null, "HealthState instance can't be null when clustering is enabled");
Set<NodeHealth> nodeHealths = sharedHealthState.readAll();
Health health = ... | @Test
public void checkCluster_returns_causes_of_all_ClusterHealthChecks_whichever_their_status() {
when(nodeInformation.isStandalone()).thenReturn(false);
List<String[]> causesGroups = IntStream.range(0, 1 + random.nextInt(20))
.mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAl... |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testSimpleGroupOffsetCommit() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> result = context.commitOffset(
new OffsetCommitRequestData()
... |
@Override
public ParsedLine parse(final String line, final int cursor, final ParseContext context) {
final String trimmed = line.trim();
final int adjCursor = adjustCursor(line, trimmed, cursor);
return delegate.parse(trimmed, adjCursor, context);
} | @Test
public void shouldAdjustCursorIfInRightWhiteSpace() {
expect(delegate.parse(anyString(), eq(4), anyObject()))
.andReturn(parsedLine).anyTimes();
replay(delegate);
parser.parse(" line ", 6, UNSPECIFIED);
parser.parse(" line ", 7, UNSPECIFIED);
parser.parse(" line ", 8, UNSPECIF... |
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newNewIssuesNotification_DetailsSupplier_getUserNameByUuid_always_returns_empty_if_map_argument_is_empty() {
NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap());
DetailsSupplier detailsSupplier = readDetailsSupplier(underTest);
assertThat(detailsSupplie... |
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
} | @Test
public void reportFailures_notification_is_enable_at_global_level() {
NotificationDispatcherMetadata metadata = ReportAnalysisFailureNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("true");
} |
@Override
public void onWorkflowFinalized(Workflow workflow) {
WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput());
WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow);
String reason = workflow.getReasonForIncompletion();
LOG.inf... | @Test
public void testWorkflowFinalizedTerminatedForKilled() {
when(workflow.getStatus()).thenReturn(Workflow.WorkflowStatus.TERMINATED);
when(instanceDao.getWorkflowInstanceStatus(eq("test-workflow-id"), anyLong(), anyLong()))
.thenReturn(WorkflowInstance.Status.IN_PROGRESS);
when(workflow.getRea... |
@Override
public void v(String tag, String message, Object... args) { } | @Test
public void verboseWithThrowableNotLogged() {
Throwable t = new Throwable("Test Throwable");
logger.v(t, tag, "Hello %s", "World");
assertNotLogged();
} |
@VisibleForTesting
public String validateMobile(String mobile) {
if (StrUtil.isEmpty(mobile)) {
throw exception(SMS_SEND_MOBILE_NOT_EXISTS);
}
return mobile;
} | @Test
public void testCheckMobile_notExists() {
// 准备参数
// mock 方法
// 调用,并断言异常
assertServiceException(() -> smsSendService.validateMobile(null),
SMS_SEND_MOBILE_NOT_EXISTS);
} |
public static boolean isValidEnsName(String input) {
return isValidEnsName(input, Keys.ADDRESS_LENGTH_IN_HEX);
} | @Test
public void testIsEnsName() {
assertTrue(isValidEnsName("eth"));
assertTrue(isValidEnsName("web3.eth"));
assertTrue(isValidEnsName("0x19e03255f667bdfd50a32722df860b1eeaf4d635.eth"));
assertFalse(isValidEnsName("0x19e03255f667bdfd50a32722df860b1eeaf4d635"));
assertFalse... |
@Override
public Object intercept(final Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
Executor executor = (Executor) invocation.getTarget();
for (Class<?> superClass ... | @Test
public void interceptTest() throws SQLException {
final PostgreSqlUpdateInterceptor postgreSqlUpdateInterceptor = new PostgreSqlUpdateInterceptor();
final Invocation invocation = mock(Invocation.class);
Object[] args = new Object[2];
args[0] = mock(MappedStatement.class);
... |
public void finishTransactionBatch(TransactionStateBatch stateBatch, Set<Long> errorReplicaIds) {
Database db = globalStateMgr.getDb(stateBatch.getDbId());
if (db == null) {
stateBatch.writeLock();
try {
writeLock();
try {
state... | @Test
public void testFinishTransactionBatch() throws UserException {
FakeGlobalStateMgr.setGlobalStateMgr(masterGlobalStateMgr);
DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(GlobalStateMgrTestUtil.testDbId1);
long txnId6 = lableToTxnId.get(GlobalStateMg... |
@Override
public String execute(CommandContext commandContext, String[] args) {
return QosConstants.CLOSE;
} | @Test
void testExecute() throws Exception {
Quit quit = new Quit();
String output = quit.execute(Mockito.mock(CommandContext.class), null);
assertThat(output, equalTo(QosConstants.CLOSE));
} |
@Override
public PluginDescriptor find(Path pluginPath) {
Manifest manifest = readManifest(pluginPath);
return createPluginDescriptor(manifest);
} | @Test
public void testFindNotFound() {
PluginDescriptorFinder descriptorFinder = new ManifestPluginDescriptorFinder();
assertThrows(PluginRuntimeException.class, () -> descriptorFinder.find(pluginsPath.resolve("test-plugin-3")));
} |
public static Driver load(String className) throws DriverLoadException {
final ClassLoader loader = DriverLoader.class.getClassLoader();
return load(className, loader);
} | @Test(expected = DriverLoadException.class)
public void testLoad_String_String_badPath() throws Exception {
String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
//File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.ja... |
@Override
public CompletableFuture<JobManagerRunnerResult> getResultFuture() {
return resultFuture;
} | @Test
void testInitializationFailureSetsExceptionHistoryProperly()
throws ExecutionException, InterruptedException {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestIns... |
public synchronized long nextId() {
long timestamp = genTime();
if (timestamp < this.lastTimestamp) {
if (this.lastTimestamp - timestamp < timeOffset) {
// 容忍指定的回拨,避免NTP校时造成的异常
timestamp = lastTimestamp;
} else {
// 如果服务器时间有问题(时钟后退) 报错。
throw new IllegalStateException(StrUtil.format("Clock mov... | @Test
public void getSnowflakeLengthTest(){
for (int i = 0; i < 1000; i++) {
final long l = IdUtil.getSnowflake(0, 0).nextId();
assertEquals(19, StrUtil.toString(l).length());
}
} |
public static <InputT> ValueByReduceByBuilder<InputT, InputT> of(PCollection<InputT> input) {
return named(null).of(input);
} | @Test
public void testWindow_applyIf() {
final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings());
final PCollection<Long> output =
ReduceWindow.of(dataset)
.reduceBy(e -> 1L)
.withSortedValues(String::compareTo)
.applyIf(
... |
@Deprecated
public static <T> T defaultIfEmpty(String str, Supplier<? extends T> handle, final T defaultValue) {
if (StrUtil.isNotEmpty(str)) {
return handle.get();
}
return defaultValue;
} | @Test
public void defaultIfEmptyTest() {
final String emptyValue = "";
final String dateStr = "2020-10-23 15:12:30";
Instant result1 = ObjectUtil.defaultIfEmpty(emptyValue,
(source) -> DateUtil.parse(source, DatePattern.NORM_DATETIME_PATTERN).toInstant(), Instant.now());
assertNotNull(result1);
Instant r... |
public static synchronized Class<?> getClass(String name, Configuration conf
) throws IOException {
Class<?> writableClass = NAME_TO_CLASS.get(name);
if (writableClass != null)
return writableClass;
try {
return conf.getClassByName(name);
} catch (... | @Test
public void testBadName() throws Exception {
Configuration conf = new Configuration();
try {
WritableName.getClass("unknown_junk",conf);
assertTrue(false);
} catch(IOException e) {
assertTrue(e.getMessage().matches(".*unknown_junk.*"));
}
} |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final long beginTimeMills = this.brokerController.getMessageStore().now();
request.addExtFieldIfNotExist(BORN_TIME, String.valueOf(System.currentTimeMil... | @Test
public void testGetInitOffset_normalTopic() throws RemotingCommandException {
long maxOffset = 999L;
when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig());
when(messageStore.getMaxOffsetInQueue(topic, 0)).thenReturn(maxOffset);
String newGroup = group ... |
public static CreateSourceAsProperties from(final Map<String, Literal> literals) {
try {
return new CreateSourceAsProperties(literals, false);
} catch (final ConfigException e) {
final String message = e.getMessage().replace(
"configuration",
"property"
);
throw new ... | @Test
public void shouldThrowIfValueFormatAndFormatProvided() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> CreateSourceAsProperties.from(
ImmutableMap.<String, Literal>builder()
.put(VALUE_FORMAT_PROPERTY, new StringLiteral("JSON"))
... |
public FuryBuilder withMetaCompressor(MetaCompressor metaCompressor) {
this.metaCompressor = MetaCompressor.checkMetaCompressor(metaCompressor);
return this;
} | @Test
public void testWithMetaCompressor() {
MetaCompressor metaCompressor =
new FuryBuilder()
.withMetaCompressor(
new MetaCompressor() {
@Override
public byte[] compress(byte[] data, int offset, int size) {
return new by... |
@Override
public void handle(HttpExchange httpExchange) {
try {
String requestUri = httpExchange.getRequestURI().toString();
requestUri = sanitizeRequestUri(requestUri);
final String toServe = requestUri.substring((contextPath + "/").length());
final URL reso... | @Test
void servesIndexHtmlIfNoFileRequested() throws IOException {
when(httpExchange.getRequestURI()).thenReturn(URI.create("/dashboard"));
staticFileHttpHandler.handle(httpExchange);
verify(httpExchange).sendResponseHeaders(200, 0);
} |
@CanIgnoreReturnValue
public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
ListMultimap<?, ?> extra = difference(actual, expectedMult... | @Test
public void containsExactlyEntriesIn_homogeneousMultimap_failsWithSameToString()
throws Exception {
expectFailureWhenTestingThat(ImmutableMultimap.of(1, "a", 1, "b", 2, "c"))
.containsExactlyEntriesIn(ImmutableMultimap.of(1L, "a", 1L, "b", 2L, "c"));
assertFailureKeys("missing", "unexpecte... |
@Override
public List<ValidationMessage> validate(ValidationContext context) {
return context.query().tokens().stream()
.filter(this::isInvalidOperator)
.map(token -> {
final String errorMessage = String.format(Locale.ROOT, "Query contains invalid operator... | @Test
void testRepeatedInvalidTokens() {
final ValidationContext context = TestValidationContext.create("not(foo:bar)")
.build();
final List<ValidationMessage> messages = sut.validate(context);
assertThat(messages.size()).isEqualTo(1);
assertThat(messages.stream().all... |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void resolveScopeFromLifecycle_complete() {
PublishSubject<Integer> lifecycle = PublishSubject.create();
TestObserver<?> o = testSource(resolveScopeFromLifecycle(lifecycle, 3));
lifecycle.onNext(0);
o.assertNoErrors().assertNotComplete();
lifecycle.onNext(1);
o.assertNoErrors().... |
@Override
public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context,
Map<String, Long> recentlyUnloadedBundles,
Map<String, Long> recentlyUnloadedBrokers) {
final var conf = context.broker... | @Test
public void testGetAvailableBrokersFailed() {
UnloadCounter counter = new UnloadCounter();
TransferShedder transferShedder = new TransferShedder(pulsar, counter, null,
isolationPoliciesHelper, antiAffinityGroupPolicyHelper);
var ctx = setupContext();
BrokerRegis... |
@VisibleForTesting
void validateDictTypeUnique(Long id, String type) {
if (StrUtil.isEmpty(type)) {
return;
}
DictTypeDO dictType = dictTypeMapper.selectByType(type);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if... | @Test
public void testValidateDictTypeUnique_valueDuplicateForCreate() {
// 准备参数
String type = randomString();
// mock 数据
dictTypeMapper.insert(randomDictTypeDO(o -> o.setType(type)));
// 调用,校验异常
assertServiceException(() -> dictTypeService.validateDictTypeUnique(nul... |
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("start position") BigDecimal start) {
return invoke( list, start, null );
} | @Test
void invokeStartZero() {
FunctionTestUtil.assertResultError(sublistFunction.invoke(Arrays.asList(1, 2), BigDecimal.ZERO),
InvalidParametersEvent.class);
} |
@Override
public PartitionQuickStats buildQuickStats(ConnectorSession session, SemiTransactionalHiveMetastore metastore,
SchemaTableName table, MetastoreContext metastoreContext, String partitionId, Iterator<HiveFileInfo> files)
{
requireNonNull(session);
requireNonNull(metastore);
... | @Test
public void testStatsFromNestedColumnsAreNotIncluded()
{
String resourceDir = TestParquetQuickStatsBuilder.class.getClassLoader().getResource("quick_stats").toString();
// Table definition :
// CREATE TABLE nested_parquet(
// id bigint,
// x row(a bigint, b... |
public int weekOfYear() {
return getField(DateField.WEEK_OF_YEAR);
} | @Test
public void weekOfYearTest() {
DateTime date = DateUtil.parse("2016-12-27");
//noinspection ConstantConditions
assertEquals(2016, date.year());
//跨年的周返回的总是1
assertEquals(1, date.weekOfYear());
} |
public List<Issue> validateMetadata(ExtensionVersion extVersion) {
return Observation.createNotStarted("ExtensionValidator#validateMetadata", observations).observe(() -> {
var issues = new ArrayList<Issue>();
checkVersion(extVersion.getVersion(), issues);
checkTargetPlatform(... | @Test
public void testInvalidURL2() {
var extension = new ExtensionVersion();
extension.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL);
extension.setVersion("1.0.0");
extension.setRepository("https://");
var issues = validator.validateMetadata(extension);
assertThat... |
@Override
public CommandLineImpl parse(final List<String> originalArgs, final Logger logger) {
return CommandLineImpl.of(originalArgs, logger);
} | @Test
public void testRunHelp() throws Exception {
final CommandLineParserImpl parser = new CommandLineParserImpl();
final CommandLineImpl commandLine = parse(parser, "-h", "run");
assertEquals(Command.RUN, commandLine.getCommand());
assertEquals(
"Usage: embulk [co... |
@Udf(schema = "ARRAY<STRUCT<K STRING, V INT>>")
public List<Struct> entriesInt(
@UdfParameter(description = "The map to create entries from") final Map<String, Integer> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
return entr... | @Test
public void shouldComputeIntEntries() {
final Map<String, Integer> map = createMap(i -> i);
shouldComputeEntries(map, () -> entriesUdf.entriesInt(map, false));
} |
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
if (isAdmin(username)) {
UserDetails userDet... | @Test
void testCloseCaseSensitive() {
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord)).thenAnswer(
new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwabl... |
public <ConfigType extends ConfigInstance> ConfigType toInstance(Class<ConfigType> clazz, String configId) {
return ConfigInstanceUtil.getNewInstance(clazz, configId, this);
} | @Test
public void test_map_of_map() {
Slime slime = new Slime();
Cursor map = slime.setObject().setObject("nestedmap").setObject("my-nested").setObject("inner");
map.setLong("one", 1);
map.setLong("two", 2);
MaptypesConfig config = new ConfigPayload(slime).toInstance(Maptype... |
@Override
public ProcResult fetchResult() throws AnalysisException {
final BaseProcResult result = new BaseProcResult();
result.setNames(CurrentQueryStatisticsProcDir.TITLE_NAMES.asList());
List<QueryStatisticsInfo> queryInfos = QueryStatisticsInfo.makeListFromMetricsAndMgrs();
List<... | @Test
public void testFetchResult() throws AnalysisException {
try (MockedStatic<QueryStatisticsInfo> queryStatisticsInfo = mockStatic(QueryStatisticsInfo.class)) {
queryStatisticsInfo.when(QueryStatisticsInfo::makeListFromMetricsAndMgrs)
.thenReturn(LOCAL_TEST_QUERIES);
... |
public static <OutputT> OutputT getArgumentWithDefault(
@Nullable OutputT value, OutputT defaultValue) {
if (value == null) {
return defaultValue;
}
return value;
} | @Test
public void testGetArgumentWithDefault() {
assertEquals("value", SingleStoreUtil.getArgumentWithDefault("value", "default"));
} |
public boolean isBeforeOrAt(KinesisRecord other) {
if (shardIteratorType == AT_TIMESTAMP) {
return timestamp.compareTo(other.getApproximateArrivalTimestamp()) <= 0;
}
int result = extendedSequenceNumber().compareTo(other.getExtendedSequenceNumber());
if (result == 0) {
return shardIteratorTy... | @Test
public void testComparisonWithTimestamp() {
DateTime referenceTimestamp = DateTime.now();
assertThat(
checkpoint(AT_TIMESTAMP, referenceTimestamp.toInstant())
.isBeforeOrAt(recordWith(referenceTimestamp.minusMillis(10).toInstant())))
.isFalse();
assertThat(
... |
public ColumnFamilyOptions getColumnOptions() {
// initial options from common profile
ColumnFamilyOptions opt = createBaseCommonColumnOptions();
handlesToClose.add(opt);
// load configurable options on top of pre-defined profile
setColumnFamilyOptionsFromConfigurableOptions(opt... | @Test
public void testGetColumnFamilyOptionsWithPartitionedIndex() throws Exception {
LRUCache cache = new LRUCache(1024L);
WriteBufferManager wbm = new WriteBufferManager(1024L, cache);
ForStSharedResources sharedResources = new ForStSharedResources(cache, wbm, 1024L, true);
final T... |
RegistryEndpointProvider<Optional<URL>> initializer() {
return new Initializer();
} | @Test
public void testInitializer_getHttpMethod() {
Assert.assertEquals("POST", testBlobPusher.initializer().getHttpMethod());
} |
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException {
byte[] bytes = pollEntryBytes(timeout);
if (bytes == null) {
return null;
}
return DLQEntry.deserialize(bytes);
} | @Test
public void testFlushAfterSegmentComplete() throws Exception {
Event event = new Event();
final int EVENTS_BEFORE_FLUSH = randomBetween(1, 32);
event.setField("T", generateMessageContent(PAD_FOR_BLOCK_SIZE_EVENT));
Timestamp timestamp = new Timestamp();
try (DeadLetterQ... |
public static Object convertAvroFormat(
FieldType beamFieldType, Object avroValue, BigQueryUtils.ConversionOptions options) {
TypeName beamFieldTypeName = beamFieldType.getTypeName();
if (avroValue == null) {
if (beamFieldType.getNullable()) {
return null;
} else {
throw new Il... | @Test
public void testSubMilliPrecisionRejected() {
assertThrows(
"precision",
IllegalArgumentException.class,
() -> BigQueryUtils.convertAvroFormat(FieldType.DATETIME, 1000000001L, REJECT_OPTIONS));
} |
public static Bech32Data decode(final String str) throws AddressFormatException {
boolean lower = false, upper = false;
if (str.length() < 8)
throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length());
if (str.length() > 90)
throw new AddressFo... | @Test(expected = AddressFormatException.InvalidCharacter.class)
public void decode_invalidCharacter_notInAlphabet() {
Bech32.decode("A12OUEL5X");
} |
public String toHexString()
{
return Hex.getString(bytes);
} | @Test
void testGetHex()
{
String expected = "Test subject for testing getHex";
COSString test1 = new COSString(expected);
String hexForm = createHex(expected);
assertEquals(hexForm, test1.toHexString());
COSString escCS = new COSString(ESC_CHAR_STRING);
// Not sur... |
@Override
protected void write(final MySQLPacketPayload payload) {
payload.writeInt1(HEADER);
payload.writeStringNul(authPluginName);
payload.writeStringNul(new String(authPluginData.getAuthenticationPluginData()));
} | @Test
void assertWrite() {
when(authPluginData.getAuthenticationPluginData()).thenReturn(new byte[]{0x11, 0x22});
MySQLAuthSwitchRequestPacket authSwitchRequestPacket = new MySQLAuthSwitchRequestPacket("plugin", authPluginData);
authSwitchRequestPacket.write(payload);
verify(payload)... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatSubscriptExpression() {
assertThat(ExpressionFormatter.formatExpression(new SubscriptExpression(
new StringLiteral("abc"),
new IntegerLiteral(3))),
equalTo("'abc'[3]"));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.