focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
XmlStringBuilder xml = new XmlStringBuilder(this, enclosingNamespace);
xml.rightAngleBracket();
xml.emptyElement(compressFailureError);
xml.optElement(stanzaError);
xm... | @Test
public void simpleFailureTest() throws SAXException, IOException {
Failure failure = new Failure(Failure.CompressFailureError.processing_failed);
CharSequence xml = failure.toXML();
final String expectedXml = "<failure xmlns='http://jabber.org/protocol/compress'><processing-failed/></... |
@Override
public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_NULL);
// TODO not supported at the moment.
return ImmutableList.of();
} | @Test
public void testGetPortDeltaStatistics() {
manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
VirtualDevice virtualDevice = manager.createVirtualDevice(virtualNetwork.id(), DID1);... |
@Override
public void serialize(String name, byte[] message, OutputStream out) throws IOException {
byte[] header = new byte[4 + COMMAND_LEN + 4 + 4 /* checksum */];
ByteUtils.writeInt32BE(packetMagic, header, 0);
// The header array is initialized to zero by Java so we don't have to worry ... | @Test(expected = Error.class)
public void testSerializeUnknownMessage() throws Exception {
MessageSerializer serializer = MAINNET.getDefaultSerializer();
Message unknownMessage = new BaseMessage() {
@Override
protected void bitcoinSerializeToStream(OutputStream stream) {}
... |
public static SqlQueryBuilder select(String... columns) {
if (columns == null || columns.length == 0) {
throw new IllegalArgumentException("No columns provided with SELECT statement. Please mention column names or '*' to select all columns.");
}
StringBuilder sqlBuilder = new StringBuilder();
sqlB... | @Test
public void testSelect() {
String sql = SqlQueryBuilder.select("id", "rider", "time")
.from("trips")
.join("users").on("trips.rider = users.id")
.where("(trips.time > 100 or trips.time < 200)")
.orderBy("id", "time")
.limit(10).toString();
assertEquals("select id... |
@DeleteMapping("/clean/{timePoint}")
@RequiresPermissions("system:role:delete")
public AdminResult<Boolean> clean(@PathVariable @DateTimeFormat(pattern = DateUtils.DATE_FORMAT_DATETIME) final Date timePoint) {
return ResultUtil.ok(recordLogService.cleanHistory(timePoint));
} | @Test
public void testClean() throws Exception {
given(this.operationRecordLogService.cleanHistory(any())).willReturn(true);
this.mockMvc.perform(MockMvcRequestBuilders.delete("/operation-record/log/clean/" + "2020-10-22 10:10:10")
.contentType(MediaType.APPLICATION_JSON)
... |
public <V> Iterable<V> getAll(TupleTag<V> tag) {
int index = schema.getIndex(tag);
if (index < 0) {
throw new IllegalArgumentException("TupleTag " + tag + " is not in the schema");
}
@SuppressWarnings("unchecked")
Iterable<V> unions = (Iterable<V>) valueMap.get(index);
return unions;
} | @Test
@SuppressWarnings("BoxedPrimitiveEquality")
public void testCachedResults() {
// The caching strategies are different for the different implementations.
Assume.assumeTrue(useReiterator);
// Ensure we don't fail below due to a non-default java.lang.Integer.IntegerCache.high setting,
// as we w... |
@Override
public void execute(GraphModel graphModel) {
Graph graph;
if (isDirected) {
graph = graphModel.getDirectedGraphVisible();
} else {
graph = graphModel.getUndirectedGraphVisible();
}
execute(graph);
} | @Test
public void testColumnCreation() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1);
ClusteringCoefficient cc = new ClusteringCoefficient();
cc.execute(graphModel);
Assert.assertTrue(graphModel.getNodeTable().hasColumn(ClusteringCoefficient.CLUSTERING_COE... |
@Override
public String toString() {
final String nInfo = n == 1 ? "" : "(" + n + ")";
return getClass().getSimpleName() + nInfo + "[" + this.indicator + "]";
} | @Test
public void testToStringMethodWithNGreaterThen1() {
prevValueIndicator = new PreviousValueIndicator(openPriceIndicator, 2);
final String prevValueIndicatorAsString = prevValueIndicator.toString();
assertTrue(prevValueIndicatorAsString.startsWith("PreviousValueIndicator(2)["));
... |
public synchronized void refreshTableByEvent(HiveTable updatedHiveTable, HiveCommonStats commonStats, Partition partition) {
String dbName = updatedHiveTable.getDbName();
String tableName = updatedHiveTable.getTableName();
DatabaseTableName databaseTableName = DatabaseTableName.of(dbName, tableN... | @Test
public void testRefreshTableByEvent() {
CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore(
metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false);
HiveCommonStats stats = new HiveCommonStats(10, 100);
// unpartition
{
... |
@Override
public int size() {
return list.size();
} | @Test
public void testSize() {
Set<Integer> set = redisson.getSortedSet("set");
set.add(1);
set.add(2);
set.add(3);
set.add(3);
set.add(4);
set.add(5);
set.add(5);
Assertions.assertEquals(5, set.size());
} |
@Override
public boolean equals(final Object obj) {
// Make sure equals() is tune with hashCode() so works ok in a hashSet !
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DefaultAlarm other = (Defa... | @Test
public void testEquals() {
final DefaultAlarm a = new DefaultAlarm.Builder(ALARM_ID_2,
DeviceId.NONE, "desc", Alarm.SeverityLevel.MINOR, 3).build();
final DefaultAlarm b = new DefaultAlarm.Builder(ALARM_ID,
DeviceId.NONE, "desc", Alarm.SeverityLevel.MINOR, a.tim... |
@Override
public List<String> choices() {
if (commandLine.getArguments() == null) {
return Collections.emptyList();
}
List<String> argList = Lists.newArrayList();
String argOne = null;
if (argList.size() > 1) {
argOne = argList.get(1);
}
... | @Test
public void testOptArgCompleter() {
VplsOptArgCompleter completer = new VplsOptArgCompleter();
completer.vpls = new TestVpls();
((TestVpls) completer.vpls).initSampleData();
completer.interfaceService = new TestInterfaceService();
// Add interface to VPLS
comma... |
@VisibleForTesting
public void validateSmsTemplateCodeDuplicate(Long id, String code) {
SmsTemplateDO template = smsTemplateMapper.selectByCode(code);
if (template == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if (id == null) {
throw exception(... | @Test
public void testValidateDictDataValueUnique_success() {
// 调用,成功
smsTemplateService.validateSmsTemplateCodeDuplicate(randomLongId(), randomString());
} |
@Override
public CompletableFuture<HttpResponse> enqueue(DocumentId documentId, HttpRequest request) {
RetriableFuture<HttpResponse> result = new RetriableFuture<>(); // Carries the aggregate result of the operation, including retries.
if (destroyed.get()) {
result.complete();
... | @Test
void testShutdown() throws IOException {
MockCluster cluster = new MockCluster();
AtomicLong nowNanos = new AtomicLong(0);
CircuitBreaker breaker = new GracePeriodCircuitBreaker(nowNanos::get, Duration.ofSeconds(1), Duration.ofMinutes(10));
HttpRequestStrategy strategy = new Ht... |
Set<SourceName> analyzeExpression(
final Expression expression,
final String clauseType
) {
final Validator extractor = new Validator(clauseType);
extractor.process(expression, null);
return extractor.referencedSources;
} | @Test
public void shouldGetSourceForUnqualifiedColumnRef() {
// Given:
final ColumnName column = ColumnName.of("qualified");
final Expression expression = new QualifiedColumnReferenceExp(
SourceName.of("fully"),
column
);
when(sourceSchemas.sourcesWithField(any(), any())).thenRetu... |
public FEELFnResult<BigDecimal> invoke(@ParameterName("list") List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "the list cannot be null"));
}
if (list.isEmpty()) {
return FEELFnResult.ofResult(null); // DMN ... | @Test
void invokeListParamContainsUnsupportedNumber() {
FunctionTestUtil.assertResultError(sumFunction.invoke(Arrays.asList(10, 2, Double.NaN)),
InvalidParametersEvent.class);
} |
public final void containsEntry(@Nullable Object key, @Nullable Object value) {
Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value);
checkNotNull(actual);
if (!actual.entrySet().contains(entry)) {
List<@Nullable Object> keyList = singletonList(key);
List<@Nullable Ob... | @Test
public void containsNullEntryValue() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, null);
expectFailureWhenTestingThat(actual).containsEntry("kurt", null);
assertFailureKeys(
"expected to contain entry",
"but did not",
"though it did contain keys with... |
public boolean isTransient() {
return isTransient;
} | @Test
public void testTransient() {
assertTrue(converter(NULL_CONVERTER).isTransient());
assertTrue(converter(INTEGER_CONVERTER, NULL_CONVERTER).isTransient());
assertFalse(converter(INTEGER_CONVERTER).isTransient());
assertFalse(converter(INTEGER_CONVERTER, IDENTITY_CONVERTER).isTr... |
@Override
public NativeQuerySpec<Record> select(String sql, Object... args) {
return new NativeQuerySpecImpl<>(this, sql, args, DefaultRecord::new, false);
} | @Test
public void testAgg() {
DefaultQueryHelper helper = new DefaultQueryHelper(database);
database.dml()
.insert("s_test")
.value("id", "agg-test")
.value("name", "agg")
.value("age", 111)
.execute()
.... |
public void setContract(@Nullable Produce contract)
{
this.contract = contract;
setStoredContract(contract);
handleContractState();
} | @Test
public void redberriesContractRedberriesGrowing()
{
final long unixNow = Instant.now().getEpochSecond();
final long expectedCompletion = unixNow + 60;
// Get the bush patch
final FarmingPatch patch = farmingGuildPatches.get(Varbits.FARMING_4772);
assertNotNull(patch);
// Not ready to check
when... |
@Override
public void refreshPluginDataSelf(final List<PluginData> pluginDataList) {
LOG.info("start refresh plugin data self");
if (CollectionUtils.isEmpty(pluginDataList)) {
return;
}
BaseDataCache.getInstance().cleanPluginDataSelf(pluginDataList);
} | @Test
public void testRefreshPluginDataSelf() {
baseDataCache.cleanPluginData();
PluginData firstCachedPluginData = PluginData.builder().name(mockName1).build();
PluginData secondCachedPluginData = PluginData.builder().name(mockName2).build();
baseDataCache.cachePluginData(firstCache... |
@Override
public MergeAppend appendFile(DataFile file) {
add(file);
return this;
} | @TestTemplate
public void testAppendWithManifestScanExecutor() {
assertThat(listManifestFiles()).isEmpty();
TableMetadata base = readMetadata();
assertThat(base.currentSnapshot()).isNull();
assertThat(base.lastSequenceNumber()).isEqualTo(0);
AtomicInteger scanThreadsIndex = new AtomicInteger(0);
... |
public void setProjectionDataMapSerializer(ProjectionDataMapSerializer projectionDataMapSerializer)
{
RestliRequestOptions existingRequestOptions =
(_requestOptions == null) ? RestliRequestOptions.DEFAULT_OPTIONS : _requestOptions;
// If the desired value is same as existing, this is a no-op.
if ... | @Test
public void testSetProjectionDataMapSerializer()
{
ProjectionDataMapSerializer customSerializer = (paramName, pathSpecs) -> new DataMap();
GetRequest<TestRecord> getRequest = generateDummyRequestBuilder().build();
getRequest.setProjectionDataMapSerializer(customSerializer);
assertEquals(getReq... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeZero() {
FunctionTestUtil.assertResultBigDecimal(ceilingFunction.invoke(BigDecimal.ZERO), BigDecimal.ZERO);
} |
@Override
public void onMatch(RelOptRuleCall call) {
final Sort sort = call.rel(0);
final SortExchange exchange = call.rel(1);
final RelMetadataQuery metadataQuery = call.getMetadataQuery();
if (RelMdUtil.checkInputForCollationAndLimit(
metadataQuery,
exchange.getInput(),
sort... | @Test
public void shouldMatchLimitNoOffsetNoSort() {
// Given:
SortExchange exchange =
PinotLogicalSortExchange.create(_input, RelDistributions.SINGLETON, RelCollations.EMPTY, false, false);
Sort sort = LogicalSort.create(exchange, RelCollations.EMPTY, null, literal(1));
Mockito.when(_call.rel... |
@VisibleForTesting
WxMpService getWxMpService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMpService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MP.getType(), userType);
if (client != null && Objects.equals(client.getSta... | @Test
public void testGetWxMpService_clientDisable() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 数据
SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())
.setUserType(userTyp... |
public PrivateKey convertPrivateKey(final String privatePemKey) {
StringReader keyReader = new StringReader(privatePemKey);
try {
PrivateKeyInfo privateKeyInfo = PrivateKeyInfo
.getInstance(new PEMParser(keyReader).readObject());
return new JcaPEMKeyConverter... | @Test
void givenEmptyPrivateKey_whenConvertPrivateKey_thenThrowRuntimeException() {
// Given
String emptyPrivatePemKey = "";
// When & Then
assertThatThrownBy(() -> KeyConverter.convertPrivateKey(emptyPrivatePemKey))
.isInstanceOf(RuntimeException.class)
... |
@ShellMethod(key = "stats wa", value = "Write Amplification. Ratio of how many records were upserted to how many "
+ "records were actually written")
public String writeAmplificationStats(
@ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") final Integer limit,
@ShellOptio... | @Test
public void testWriteAmplificationStats() throws Exception {
// generate data and metadata
Map<String, Integer[]> data = new LinkedHashMap<>();
data.put("100", new Integer[] {15, 10});
data.put("101", new Integer[] {20, 10});
data.put("102", new Integer[] {15, 15});
for (Map.Entry<Strin... |
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
if (remaining.split("/").length > 1) {
throw new IllegalArgumentException("Invalid URI: " + URISupport.sanitizeUri(uri));
}
SplunkHECEndpoint answer = new... | @Test
public void testSplunkURLIsNotOverriddenByQuery() throws Exception {
SplunkHECEndpoint endpoint = (SplunkHECEndpoint) component.createEndpoint(
"splunk-hec:192.168.0.1:18808?token=11111111-1111-1111-1111-111111111111&splunkURL=ignored");
assertEquals("192.168.0.1:18808", endpoi... |
public int accumulateSum(int... nums) {
LOGGER.info(SOURCE_MODULE, VERSION);
return Arrays.stream(nums).reduce(0, Integer::sum);
} | @Test
void testAccumulateSum() {
assertEquals(0, source.accumulateSum(-1, 0, 1));
} |
public long computeTotalDiff() {
long diffTotal = 0L;
for (Entry<MessageQueue, OffsetWrapper> entry : this.offsetTable.entrySet()) {
diffTotal += entry.getValue().getBrokerOffset() - entry.getValue().getConsumerOffset();
}
return diffTotal;
} | @Test
public void testComputeTotalDiff() {
ConsumeStats stats = new ConsumeStats();
MessageQueue messageQueue = Mockito.mock(MessageQueue.class);
OffsetWrapper offsetWrapper = Mockito.mock(OffsetWrapper.class);
Mockito.when(offsetWrapper.getConsumerOffset()).thenReturn(1L);
M... |
public String convert(ILoggingEvent event) {
StringBuilder sb = new StringBuilder();
int pri = facility + LevelToSyslogSeverity.convert(event);
sb.append("<");
sb.append(pri);
sb.append(">");
sb.append(computeTimeStampString(event.getTimeStamp()));
sb.append(' ');
sb.append(localHost... | @Test
public void multipleConversions() {
LoggingEvent le = createLoggingEvent();
calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15);
le.setTimeStamp(calendar.getTimeInMillis());
assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le));
assertEquals("<191>Oct 11 22:14:15 " +... |
@Override
public Map<String, String> getTopicConfig(final String topicName) {
return topicConfig(topicName, true);
} | @Test
public void shouldGetTopicConfig() {
// Given:
givenTopicConfigs(
"fred",
overriddenConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "12345"),
defaultConfigEntry(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1")
);
// When:
final Map<String, String> config = kafkaTopicClient... |
@Override
public V put(K key, V value) {
checkNotNull(key, "Key cannot be null.");
checkNotNull(value, "Value cannot be null.");
byte[] prevVal = items.put(serializer.encode(key), serializer.encode(value));
if (prevVal == null) {
return null;
}
return seri... | @Test public void testPut() throws Exception {
//Tests insertion behavior (particularly the returning of previous value)
fillMap(10);
for (int i = 0; i < 10; i++) {
assertEquals("Put should return the previous value", Integer.valueOf(i), map.put(i, i + 1));
}
assertNu... |
public Mappings getMapping(String tableName) {
Map<String, Object> properties =
mappingStructures.containsKey(tableName) ?
mappingStructures.get(tableName).properties : new HashMap<>();
Mappings.Source source =
mappingStructures.containsKey(tableName) ?
... | @Test
public void getMapping() {
IndexStructures structures = new IndexStructures();
HashMap<String, Object> properties = new HashMap<>();
properties.put("a", "b");
properties.put("c", "d");
structures.putStructure(
"test", Mappings.builder()
... |
public Filter parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) {
if (!filterExpression.contains(FIELD_AND_VALUE_SEPARATOR)) {
throw new IllegalArgumentException(WRONG_FILTER_EXPR_FORMAT_ERROR_MSG);
}
final String[] split = filterExpression.... | @Test
void parsesFilterExpressionCorrectlyForObjectIdType() {
assertEquals(new SingleValueFilter("id", new ObjectId("5f4dfb9c69be46153b9a9a7b")),
toTest.parseSingleExpression("id:5f4dfb9c69be46153b9a9a7b",
List.of(EntityAttribute.builder()
... |
@Override
public KeyGroupsStateHandle getIntersection(KeyGroupRange keyGroupRange) {
KeyGroupRangeOffsets offsets = groupRangeOffsets.getIntersection(keyGroupRange);
if (offsets.getKeyGroupRange().getNumberOfKeyGroups() <= 0) {
return null;
}
return new KeyGroupsStateHand... | @Test
void testEmptyIntersection() {
KeyGroupRangeOffsets offsets = new KeyGroupRangeOffsets(0, 7);
byte[] dummy = new byte[10];
StreamStateHandle streamHandle = new ByteStreamStateHandle("test", dummy);
KeyGroupsStateHandle handle = new KeyGroupsStateHandle(offsets, streamHandle);
... |
public static String getMD5Checksum(File file) throws IOException, NoSuchAlgorithmException {
return getChecksum(MD5, file);
} | @Test
public void testGetMD5Checksum_File() throws Exception {
File file = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").toURI().getPath());
String expResult = "f0915c5f46b8cfa283e5ad67a09b3793";
String result = Checksum.getMD5Checksum(file);
assertEquals... |
protected FileStatus[] listStatus(JobConf job) throws IOException {
Path[] dirs = getInputPaths(job);
if (dirs.length == 0) {
throw new IOException("No input paths specified in job");
}
// get tokens for all the required FileSystems..
TokenCache.obtainTokensForNamenodes(job.getCredentials(), ... | @Test
public void testListStatusErrorOnNonExistantDir() throws IOException {
Configuration conf = new Configuration();
conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads);
org.apache.hadoop.mapreduce.lib.input.TestFileInputFormat
.configureTestErrorOnNonExistantDir(conf, localFs);
... |
@Override
public String toString() {
StringBuilder sb = new StringBuilder(256);
for (Timing type : Timing.values()) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(type.name().toLowerCase())
.append("Time=").append(get(type));
}
return sb.toString();
} | @Test
public void testToString() {
ProcessingDetails details = new ProcessingDetails(TimeUnit.MICROSECONDS);
details.set(Timing.ENQUEUE, 10);
details.set(Timing.QUEUE, 20, TimeUnit.MILLISECONDS);
assertEquals("enqueueTime=10 queueTime=20000 handlerTime=0 " +
"processingTime=0 lockfreeTime=0 l... |
ControllerResult<CreateTopicsResponseData> createTopics(
ControllerRequestContext context,
CreateTopicsRequestData request,
Set<String> describable
) {
Map<String, ApiError> topicErrors = new HashMap<>();
List<ApiMessageAndVersion> records = BoundedList.newArrayBacked(MAX_REC... | @Test
public void testCreateTopicsWithMutationQuotaExceeded() {
ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().build();
ReplicationControlManager replicationControl = ctx.replicationControl;
CreateTopicsRequestData request = new CreateTopicsRequestData();
... |
@Override
public ResultSet getBestRowIdentifier(final String catalog, final String schema, final String table, final int scope, final boolean nullable) throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getBestRowIdentifier(getActualCatalog(catalog), getActualSchema(schema),
... | @Test
void assertGetBestRowIdentifier() throws SQLException {
when(databaseMetaData.getBestRowIdentifier("test", null, null, 1, true)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getBestRowIdentifier("test", null, null, 1, true), instanceOf(DatabaseMetaDataResultSet.class));
... |
public FlowableHttpClient determineHttpClient() {
if (httpClient != null) {
return httpClient;
} else if (isApacheHttpComponentsPresent) {
// Backwards compatibility, if apache HTTP Components is present then it has priority
this.httpClient = new ApacheHttpComponentsF... | @Test
void determineHttpClientWhenNotSet() {
HttpClientConfig config = new HttpClientConfig();
assertThat(config.determineHttpClient()).isInstanceOf(ApacheHttpComponentsFlowableHttpClient.class);
} |
public static byte[] generateKey(ZUCAlgorithm algorithm) {
return KeyUtil.generateKey(algorithm.value).getEncoded();
} | @Test
public void zuc128Test(){
final byte[] secretKey = ZUC.generateKey(ZUC.ZUCAlgorithm.ZUC_128);
byte[] iv = RandomUtil.randomBytes(16);
final ZUC zuc = new ZUC(ZUC.ZUCAlgorithm.ZUC_128, secretKey, iv);
String msg = RandomUtil.randomString(500);
byte[] crypt2 = zuc.encrypt(msg);
String msg2 = zuc.decry... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
} | @Test
void should_execute_statement_with_request_timeout() {
// Given
String statement = "@requestTimeOut=10000000\n" +
"SELECT * FROM zeppelin.artists;";
// When
final InterpreterResult actual = interpreter.interpret(statement, intrContext);
// Then
assertEquals(Code.SUCCESS, actual... |
@Override
public List<RoleDO> getRoleListByStatus(Collection<Integer> statuses) {
return roleMapper.selectListByStatus(statuses);
} | @Test
public void testGetRoleListByStatus() {
// mock 数据
RoleDO dbRole01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
roleMapper.insert(dbRole01);
RoleDO dbRole02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));... |
@Override
public AuthenticationResult authenticate(final ChannelHandlerContext context, final PacketPayload payload) {
if (SSL_REQUEST_PAYLOAD_LENGTH == payload.getByteBuf().markReaderIndex().readInt() && SSL_REQUEST_CODE == payload.getByteBuf().readInt()) {
if (ProxySSLContext.getInstance().isS... | @Test
void assertSSLUnwilling() {
ByteBuf byteBuf = createByteBuf(8, 8);
byteBuf.writeInt(8);
byteBuf.writeInt(80877103);
PacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8);
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
... |
@Override
public boolean isReadable() {
return false;
} | @Test
public void testIsReadable() {
EmptyByteBuf empty = new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT);
assertFalse(empty.isReadable());
assertFalse(empty.isReadable(1));
} |
@SuppressWarnings("unchecked")
public static void addNamedOutput(Job job, String namedOutput, Class<? extends OutputFormat> outputFormatClass,
Schema keySchema) {
addNamedOutput(job, namedOutput, outputFormatClass, keySchema, null);
} | @Test
void avroInput() throws Exception {
Job job = Job.getInstance();
FileInputFormat.setInputPaths(job,
new Path(getClass().getResource("/org/apache/avro/mapreduce/mapreduce-test-input.avro").toURI().toString()));
job.setInputFormatClass(AvroKeyInputFormat.class);
AvroJob.setInputKeySchema(... |
public FEELFnResult<Boolean> invoke(@ParameterName( "range" ) Range range, @ParameterName( "point" ) Comparable point) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamRangeAndSingle() {
FunctionTestUtil.assertResult( startedByFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
"f" ),
Boolean.FALSE );
FunctionTestUtil.assertResult( startedByFunctio... |
public static <T> List<List<T>> splitBySize(List<T> list, int expectedSize)
throws NullPointerException, IllegalArgumentException {
Preconditions.checkNotNull(list, "list must not be null");
Preconditions.checkArgument(expectedSize > 0, "expectedSize must larger than 0");
if (1 == e... | @Test
public void testSplitBySizeWithNullList() {
List<Integer> lists = null;
int expectSize = 10;
expectedEx.expect(NullPointerException.class);
expectedEx.expectMessage("list must not be null");
ListUtil.splitBySize(lists, expectSize);
} |
@Override
public StorageObject upload(final Path file, Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback prompt) throws BackgroundException {
if(this.threshold(status)) {
try {
... | @Test
public void testUploadSinglePartUsEast() throws Exception {
final S3ThresholdUploadService service = new S3ThresholdUploadService(session, new S3AccessControlListFeature(session), 5 * 1024L);
final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.... |
@VisibleForTesting
static Map<String, Object> forCodec(
Map<String, Object> codec, boolean replaceWithByteArrayCoder) {
String coderType = (String) codec.get(PropertyNames.OBJECT_TYPE_NAME);
// Handle well known coders.
if (LENGTH_PREFIX_CODER_TYPE.equals(coderType)) {
if (replaceWithByteArra... | @Test
public void testLengthPrefixAndReplaceUnknownCoder() throws Exception {
Coder<WindowedValue<KV<String, Integer>>> windowedValueCoder =
WindowedValue.getFullCoder(
KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()), GlobalWindow.Coder.INSTANCE);
Map<String, Object> lengthPrefixedCode... |
@Override
public void prepare() throws ServiceNotProvidedException {
coordinator = new KubernetesCoordinator(getManager(), config);
this.registerServiceImplementation(ClusterRegister.class, coordinator);
this.registerServiceImplementation(ClusterNodesQuery.class, coordinator);
this.r... | @Test
public void prepare() {
provider.prepare();
} |
public static ExtensionInfo load(String className, ClassLoader classLoader) {
try (InputStream input = classLoader.getResourceAsStream(className.replace('.', '/') + ".class")) {
ExtensionInfo info = new ExtensionInfo(className);
new ClassReader(input).accept(new ExtensionVisitor(info), C... | @Test
void loadShouldReturnNullWhenClassDoesNotExist() {
ExtensionInfo info = ExtensionInfo.load("non.existent.Class", this.getClass().getClassLoader());
assertNull(info);
} |
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filte... | @Test
public void shouldRemoveBrokenNestedRefs() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH_3303);
openAPI.getPaths().get("/pet/{petId}").getGet().getResponses().getDefault().getHeaders().remove("X-Rate-Limit-Limit");
assertNotNull(openAPI.getComponents().getSchema... |
@Override
public int deserializeKV(DataInputStream in, SizedWritable<?> key,
SizedWritable<?> value) throws IOException {
if (!in.hasUnReadData()) {
return 0;
}
key.length = in.readInt();
value.length = in.readInt();
keySerializer.deserialize(in, key.length, key.v);
valueSeriali... | @Test
public void testDeserializer() throws IOException {
final DataInputStream in = Mockito.mock(DataInputStream.class);
Mockito.when(in.hasUnReadData()).thenReturn(true);
Assert.assertTrue(serializer.deserializeKV(in, key, value) > 0);
Mockito.verify(in, Mockito.times(4)).readInt();
Mockito.ver... |
public List<ListGroupsResponseData.ListedGroup> listGroups(
Set<String> statesFilter,
Set<String> typesFilter,
long committedOffset
) {
// Converts each state filter string to lower case for a case-insensitive comparison.
Set<String> caseInsensitiveFilterSet = statesFilter.st... | @Test
public void testListGroups() {
String consumerGroupId = "consumer-group-id";
String classicGroupId = "classic-group-id";
String shareGroupId = "share-group-id";
String memberId1 = Uuid.randomUuid().toString();
String fooTopicName = "foo";
MockPartitionAssignor ... |
Span handleStart(Req request, Span span) {
if (span.isNoop()) return span;
try {
parseRequest(request, span);
} catch (Throwable t) {
propagateIfFatal(t);
Platform.get().log("error parsing request {0}", request, t);
} finally {
// all of the above parsing happened before a times... | @Test void handleStart_nothingOnNoop_success() {
when(span.isNoop()).thenReturn(true);
handler.handleStart(request, span);
verify(span, never()).start();
} |
@Override
public String version() {
return AppInfoParser.getVersion();
} | @Test
public void testRegexRouterRetrievesVersionFromAppInfoParser() {
final RegexRouter<SinkRecord> router = new RegexRouter<>();
assertEquals(AppInfoParser.getVersion(), router.version());
} |
public PlainAccessResource buildPlainAccessResource(PlainAccessConfig plainAccessConfig) throws AclException {
checkPlainAccessConfig(plainAccessConfig);
return PlainAccessResource.build(plainAccessConfig, remoteAddressStrategyFactory.
getRemoteAddressStrategy(plainAccessConfig.getWhiteRemot... | @Test(expected = AclException.class)
public void accountNullTest() {
plainAccessConfig.setAccessKey(null);
plainPermissionManager.buildPlainAccessResource(plainAccessConfig);
} |
@ConstantFunction(name = "bitand", argTypes = {INT, INT}, returnType = INT)
public static ConstantOperator bitandInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt(first.getInt() & second.getInt());
} | @Test
public void bitandInt() {
assertEquals(10, ScalarOperatorFunctions.bitandInt(O_INT_10, O_INT_10).getInt());
} |
@Override
public boolean isEmpty() {
return pseudoHeaders.length == 0 && otherHeaders.length == 0;
} | @Test
public void testIsEmpty() {
Http2Headers headers = ReadOnlyHttp2Headers.trailers(false);
assertTrue(headers.isEmpty());
} |
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
ctx.channel().attr(PROTOCOL_NAME).set(PROTOCOL_HTTP_2);
configureHttp2(ctx.pipeline());
return;
}
... | @Test
void protocolCloseHandlerAddedByDefault() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel();
ChannelConfig channelConfig = new ChannelConfig();
channelConfig.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxHttp2HeaderListSize, 32768));
Http2OrHttpHandl... |
boolean hasReachedDeliveryTimeout(long deliveryTimeoutMs, long now) {
return deliveryTimeoutMs <= now - this.createdMs;
} | @Test
public void testBatchExpiration() {
long deliveryTimeoutMs = 10240;
ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
// Set `now` to 2ms before the create time.
assertFalse(batch.hasReachedDeliveryTimeout(deliveryTimeoutMs, now... |
public static String intLongToString(Long number) {
return intLongToString(number, DEC_RADIX);
} | @Test
public void numberToString_Test() {
Assertions.assertEquals("00111010", TbUtils.intLongToString(58L, MIN_RADIX));
Assertions.assertEquals("0000000010011110", TbUtils.intLongToString(158L, MIN_RADIX));
Assertions.assertEquals("00000000000000100000001000000001", TbUtils.intLongToString(1... |
@Override
public Output run(RunContext runContext) throws Exception {
URI from = new URI(runContext.render(this.from));
final PebbleExpressionPredicate predicate = getExpressionPredication(runContext);
final Path path = runContext.workingDir().createTempFile(".ion");
long processe... | @Test
void shouldFilterGivenValidBooleanExpressionForInclude() throws Exception {
// Given
RunContext runContext = runContextFactory.of();
FilterItems task = FilterItems
.builder()
.from(generateKeyValueFile(TEST_VALID_ITEMS, runContext).toString())
.filt... |
public long getCrc() {
return crc;
} | @Test
public void getCrcOutputZero() {
// Arrange
final LogHeader objectUnderTest = new LogHeader(0);
// Act
final long actual = objectUnderTest.getCrc();
// Assert result
Assert.assertEquals(0L, actual);
} |
@Override
public List<Document> get() {
try (var input = markdownResource.getInputStream()) {
Node node = parser.parseReader(new InputStreamReader(input));
DocumentVisitor documentVisitor = new DocumentVisitor(config);
node.accept(documentVisitor);
return documentVisitor.getDocuments();
}
catch (IO... | @Test
void testCodeWhenCodeBlockShouldNotBeSeparatedDocument() {
MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
.withHorizontalRuleCreateDocument(true)
.withIncludeCodeBlock(true)
.build();
MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/code.md", conf... |
public static Object get(final ConvertedMap data, final FieldReference field) {
final Object target = findParent(data, field);
return target == null ? null : fetch(target, field.getKey());
} | @Test
public void testDeepListGet() throws Exception {
Map<Serializable, Object> data = new HashMap<>();
List<String> inner = new ArrayList<>();
data.put("foo", inner);
inner.add("bar");
String reference = "[foo][0]";
assertEquals(
RubyUtil.RUBY.newString... |
public void removeFromFirstWhen(final Predicate<T> predicate) {
Segment<T> firstSeg = getFirst();
while (true) {
if (firstSeg == null) {
this.firstOffset = this.size = 0;
return;
}
int removed = firstSeg.removeFromFirstWhen(predicate);
... | @Test
public void testRemoveFromFirstWhen() {
fillList();
this.list.removeFromFirstWhen(x -> x < 200);
assertEquals(800, this.list.size());
assertEquals(200, (int) this.list.get(0));
for (int i = 0; i < 800; i++) {
assertEquals(200 + i, (int) this.list.get(i));
... |
@Override
public void deleteProject(Long id) {
// 校验存在
validateProjectExists(id);
// 删除
goViewProjectMapper.deleteById(id);
} | @Test
public void testDeleteProject_success() {
// mock 数据
GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class);
goViewProjectMapper.insert(dbGoViewProject);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbGoViewProject.getId();
// 调用
goViewProjectServ... |
public static FilterPredicate rewrite(FilterPredicate pred) {
Objects.requireNonNull(pred, "pred cannot be null");
return pred.accept(INSTANCE);
} | @Test
public void testNested() {
Contains<Integer> contains1 = contains(eq(intColumn, 1));
Contains<Integer> contains2 = contains(eq(intColumn, 2));
Contains<Integer> contains3 = contains(eq(intColumn, 3));
Contains<Integer> contains4 = contains(eq(intColumn, 4));
assertEquals(contains1.and(conta... |
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi... | @Test
public void testPermutorForRule_FEED_TITLE_DESC() {
Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.FEED_TITLE_Z_A);
List<FeedItem> itemList = getTestList();
assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting
permutor.reorder(itemList);
... |
@Override
public long getTotalSpace() {
throw new UnsupportedOperationException("Not implemented");
} | @Test(expectedExceptions = UnsupportedOperationException.class)
public void testGetTotalSpace() {
fs.getFile("nonsuch.txt").getTotalSpace();
} |
@Override
public void write(final OutputStream out) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
try {
out.write("[".getBytes(StandardCharsets.UTF_8));
write(out, buildHeader());
final BlockingRowQueue rowQueue = queryMetadata.getRowQueue();
while (!connectionClosed && queryMetadat... | @Test
public void shouldExitAndDrainIfQueryComplete() {
// Given:
doAnswer(streamRows("Row1", "Row2", "Row3"))
.when(rowQueue).drainTo(any());
writer = new QueryStreamWriter(
queryMetadata,
1000,
objectMapper,
new CompletableFuture<>()
);
out = new ByteArr... |
public static boolean stopTransferLeadership(final ThreadId id) {
final Replicator r = (Replicator) id.lock();
if (r == null) {
return false;
}
r.timeoutNowIndex = 0;
id.unlock();
return true;
} | @Test
public void testStopTransferLeadership() {
testTransferLeadership();
Replicator.stopTransferLeadership(this.id);
final Replicator r = getReplicator();
this.id.unlock();
assertEquals(0, r.getTimeoutNowIndex());
assertNull(r.getTimeoutNowInFly());
} |
Object getCellValue(Cell cell, Schema.FieldType type) {
ByteString cellValue = cell.getValue();
int valueSize = cellValue.size();
switch (type.getTypeName()) {
case BOOLEAN:
checkArgument(valueSize == 1, message("Boolean", 1));
return cellValue.toByteArray()[0] != 0;
case BYTE:
... | @Test
public void shouldParseBooleanTypeFalse() {
byte[] value = new byte[] {0};
assertEquals(false, PARSER.getCellValue(cell(value), BOOLEAN));
} |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldReturnValuesUpperBound() {
// Given:
when(kafkaStreams.query(any())).thenReturn(getIteratorResult());
// When:
final KsMaterializedQueryResult<Row> result = table.get(PARTITION, null, A_KEY2);
// Then:
Iterator<Row> rowIterator = result.getRowIterator();
assertTha... |
public void deletePartitionMetadataTable() {
List<String> ddl = new ArrayList<>();
if (this.isPostgres()) {
ddl.add("DROP INDEX \"" + CREATED_AT_START_TIMESTAMP_INDEX + "\"");
ddl.add("DROP INDEX \"" + WATERMARK_INDEX + "\"");
ddl.add("DROP TABLE \"" + tableName + "\"");
} else {
ddl... | @Test
public void testDeletePartitionMetadataTable() throws Exception {
when(op.get(TIMEOUT_MINUTES, TimeUnit.MINUTES)).thenReturn(null);
partitionMetadataAdminDao.deletePartitionMetadataTable();
verify(databaseAdminClient, times(1))
.updateDatabaseDdl(eq(INSTANCE_ID), eq(DATABASE_ID), statements.... |
public SampleMetadata getMetadata() {
return metadata;
} | @Test
public void testGetMetadata() {
try (CsvSampleReader reader = new CsvSampleReader(tempCsv, metadata)) {
assertThat(reader.getMetadata().toString(),
CoreMatchers.is(metadata.toString()));
}
} |
public static <C> Collection<Data> objectToDataCollection(Collection<C> collection,
SerializationService serializationService) {
List<Data> dataCollection = new ArrayList<>(collection.size());
objectToDataCollection(collection, dataCollection... | @Test
public void testObjectToDataCollection_size() {
SerializationService serializationService = new DefaultSerializationServiceBuilder().build();
Collection<Object> list = new ArrayList<>();
list.add(1);
list.add("foo");
Collection<Data> dataCollection = objectToDataCollec... |
@Override
public boolean isValidHeader(final int readableBytes) {
return readableBytes >= (startupPhase ? 0 : MESSAGE_TYPE_LENGTH) + PAYLOAD_LENGTH;
} | @Test
void assertIsValidHeader() {
assertTrue(new OpenGaussPacketCodecEngine().isValidHeader(50));
} |
public static String getType(String fileStreamHexHead) {
if(StrUtil.isBlank(fileStreamHexHead)){
return null;
}
if (MapUtil.isNotEmpty(FILE_TYPE_MAP)) {
for (final Entry<String, String> fileTypeEntry : FILE_TYPE_MAP.entrySet()) {
if (StrUtil.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())... | @Test
@Disabled
public void issue3024Test() {
String x = FileTypeUtil.getType(FileUtil.getInputStream("d:/test/TEST_WPS_DOC.doc"),true);
System.out.println(x);
} |
public static long parseLongAscii(final CharSequence cs, final int index, final int length)
{
if (length <= 0)
{
throw new AsciiNumberFormatException("empty string: index=" + index + " length=" + length);
}
final boolean negative = MINUS_SIGN == cs.charAt(index);
... | @Test
void shouldThrowExceptionWhenParsingLongWhichCanOverFlow()
{
final String maxValuePlusOneDigit = Long.MAX_VALUE + "1";
assertThrows(AsciiNumberFormatException.class,
() -> parseLongAscii(maxValuePlusOneDigit, 0, maxValuePlusOneDigit.length()),
maxValuePlusOneDigit);... |
public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) {
if (fqjt.isArray()) {
// if array, then calculate the name of the base (non-array) type
// then add the array indicators back in
String fqn = fqjt.getFullyQualifiedName();
... | @Test
void testGenericTypeWithWildCardSomeImported() {
Interface interfaze = new Interface(new FullyQualifiedJavaType("com.foo.UserMapper"));
interfaze.addImportedType(new FullyQualifiedJavaType("java.util.Map"));
interfaze.addImportedType(new FullyQualifiedJavaType("java.util.List"));
... |
public static Subject.Factory<Re2jStringSubject, String> re2jString() {
return Re2jStringSubject.FACTORY;
} | @Test
public void containsMatch_pattern_succeeds() {
assertAbout(re2jString()).that("this is a hello world").containsMatch(PATTERN);
} |
public DataSchemaParser.ParseResult parseSources(String[] rawSources) throws IOException
{
Set<String> fileExtensions = _parserByFileExtension.keySet();
Map<String, List<String>> byExtension = new HashMap<>(fileExtensions.size());
for (String fileExtension : fileExtensions)
{
byExtension.put(fil... | @Test(dataProvider = "entityRelationshipInputFiles")
public void testSchemaFilesInExtensionPathInJar(String[] files, String[] expectedExtensions) throws Exception
{
String tempDirectoryPath = _tempDir.getAbsolutePath();
String jarFile = tempDirectoryPath + FS + "test.jar";
String schemaDir = TEST_RESOUR... |
public PickTableLayoutWithoutPredicate pickTableLayoutWithoutPredicate()
{
return new PickTableLayoutWithoutPredicate(metadata);
} | @Test
public void doesNotFireIfTableScanHasTableLayout()
{
tester().assertThat(pickTableLayout.pickTableLayoutWithoutPredicate())
.on(p -> p.tableScan(
nationTableHandle,
ImmutableList.of(p.variable("nationkey", BIGINT)),
... |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldCreateAsSelectExistingTopicWithWritePermissionsAllowed() {
// Given:
final Statement statement = givenStatement(String.format(
"CREATE STREAM %s AS SELECT * FROM %s;", AVRO_STREAM_TOPIC, KAFKA_STREAM_TOPIC)
);
// When/Then:
authorizationValidator.checkAuthorization... |
@Override
public boolean put(File localFile, JobID jobId, BlobKey blobKey) throws IOException {
createBasePathIfNeeded();
String toBlobPath = BlobUtils.getStorageLocationPath(basePath, jobId, blobKey);
try (FSDataOutputStream os =
fileSystem.create(new Path(toBlobPath), FileS... | @Test
void testMissingFilePut() {
assertThatThrownBy(
() ->
testInstance.put(
new File("/not/existing/file"),
new JobID(),
new Perma... |
public static HostAndPort toHostAndPort(NetworkEndpoint networkEndpoint) {
switch (networkEndpoint.getType()) {
case IP:
return HostAndPort.fromHost(networkEndpoint.getIpAddress().getAddress());
case IP_PORT:
return HostAndPort.fromParts(
networkEndpoint.getIpAddress().getAdd... | @Test
public void toHostAndPort_withHostnameAndPort_returnsHostWithHostnameAndPort() {
NetworkEndpoint hostnameAndPortEndpoint =
NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.HOSTNAME_PORT)
.setPort(Port.newBuilder().setPortNumber(8888))
.setHostname(Hostna... |
public boolean insertGroupCapacity(final GroupCapacity capacity) {
GroupCapacityMapper groupCapacityMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.GROUP_CAPACITY);
MapperResult mapperResult;
MapperContext context = new MapperContext();
... | @Test
void testInsertGroupCapacity() {
doReturn(1).when(jdbcTemplate).update(anyString(), eq(""), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null));
// when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenReturn(1);
GroupCapacity capacity = new G... |
public abstract BuiltIndex<T> build(); | @Test
@UseDataProvider("indexAndTypeMappings")
public void fail_when_nested_with_no_field(NewIndex<?> newIndex, TypeMapping typeMapping) {
NestedFieldBuilder<TypeMapping> nestedFieldBuilder = typeMapping.nestedFieldBuilder("measures");
assertThatThrownBy(() -> nestedFieldBuilder.build())
.isInstanceO... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldThrowWhenUnparseableStringProvided() {
// Given:
final String nonsenseUnparsedQuery = "cat";
// Then:
Assert.assertThrows(ParsingException.class, () -> anon.anonymize(nonsenseUnparsedQuery));
} |
@Override
public void showPreviewForKey(
Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) {
KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme);
Point previewPosition =
mPositionCalculator.calculatePositionForPreview(
key, previ... | @Test
public void testCycleThroughPopupQueueWhenAllAreActive() {
KeyPreviewsManager underTest =
new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3);
final int[] reuseIndex = new int[] {0, 1, 2, 0, 1, 2, 0};
final List<TextView> usedWindows = new ArrayList<>();
for (int in... |
static Entry<ScramMechanism, String> parsePerMechanismArgument(String input) {
input = input.trim();
int equalsIndex = input.indexOf('=');
if (equalsIndex < 0) {
throw new FormatterException("Failed to find equals sign in SCRAM " +
"argument '" + input + "'");
... | @Test
public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() {
assertEquals("Expected configuration string to start with [",
assertThrows(FormatterException.class,
() -> ScramParser.parsePerMechanismArgument(
"SCRAM-SHA-256=name=scram-admin,p... |
public String deserialize(String password, String encryptedPassword, Validatable config) {
if (isNotBlank(password) && isNotBlank(encryptedPassword)) {
config.addError(PASSWORD, "You may only specify `password` or `encrypted_password`, not both!");
config.addError(ScmMaterialConfig.ENCRY... | @Test
public void shouldErrorOutWhenEncryptedPasswordIsInvalid() {
SvnMaterialConfig svnMaterialConfig = svn();
PasswordDeserializer passwordDeserializer = new PasswordDeserializer();
passwordDeserializer.deserialize(null, "invalidEncryptedPassword", svnMaterialConfig);
assertThat(sv... |
static java.sql.Date parseSqlDate(final String value) {
try {
// JDK format in Date.valueOf is compatible with DATE_FORMAT
return java.sql.Date.valueOf(value);
} catch (IllegalArgumentException e) {
return throwRuntimeParseException(value, new ParseException(value, 0)... | @Test
public void testSqlDateWithLeadingZerosInMonthAndDay() throws Exception {
// Given
long expectedDateInMillis = new SimpleDateFormat(SQL_DATE_FORMAT)
.parse("2003-01-04")
.getTime();
java.sql.Date expectedDate = new java.sql.Date(expectedDateInMillis);
... |
@Override
public Object merge(T mergingValue, T existingValue) {
if (existingValue == null) {
return null;
}
return existingValue.getRawValue();
} | @Test
@SuppressWarnings("ConstantConditions")
public void merge_existingValueAbsent() {
MapMergeTypes existing = null;
MapMergeTypes merging = mergingValueWithGivenValue(MERGING);
assertNull(mergePolicy.merge(merging, existing));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.