focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void open() throws Exception {
super.open();
forwardedInputSerializer = new RowDataSerializer(inputType);
this.lastKeyDataStartPos = 0;
windowBoundaryWithDataBaos = new ByteArrayOutputStreamWithPos();
windowBoundaryWithDataWrapper = new DataOutputViewStreamWr... | @Test
void testOverWindowAggregateFunction() throws Exception {
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
getTestHarness(new Configuration());
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
... |
@Override
public void deleteBrand(Long id) {
// 校验存在
validateBrandExists(id);
// 删除
brandMapper.deleteById(id);
} | @Test
public void testDeleteBrand_success() {
// mock 数据
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class);
brandMapper.insert(dbBrand);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbBrand.getId();
// 调用
brandService.deleteBrand(id);
// 校验数据不存在了
... |
void handleConfigDataChangeEvent(Event event) {
if (event instanceof ConfigDataChangeEvent) {
ConfigDataChangeEvent evt = (ConfigDataChangeEvent) event;
long dumpTs = evt.lastModifiedTs;
String dataId = evt.dataId;
String group = evt.group;
String tena... | @Test
void testHandleConfigDataChangeEvent() {
long timeStamp = System.currentTimeMillis();
List<Member> memberList = new ArrayList<>();
// member1 success
Member member1 = new Member();
member1.setIp("testip1" + timeStamp);
member1.setState(NodeState.UP);
... |
public static boolean hasPublicNullaryConstructor(Class<?> clazz) {
return Arrays.stream(clazz.getConstructors())
.anyMatch(constructor -> constructor.getParameterCount() == 0);
} | @Test
void testHasNullaryConstructorFalse() {
assertThat(InstantiationUtil.hasPublicNullaryConstructor(InstantiationUtil.class))
.isFalse();
} |
public static Map<String, String> removeHeaders(Map<String, String> headers, Collection<String> headerNames)
{
if (headers == null || headerNames == null || headerNames.isEmpty())
{
return headers;
}
Set<String> headersToRemove = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
headersToRemove... | @Test
public void testRemoveHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("X-header1", "header1Value");
headers.put("X-header2", "header2Value");
headers.put("X-header3", "header3Value");
List<String> headersToRemove = Arrays.asList("x-header3", "x-header4");
Map<St... |
@Override
public ResultSetMetaData getMetaData()
throws SQLException {
validateState();
return new PinotResultMetadata(_totalColumns, _columns, _columnDataTypes);
} | @Test
public void testGetResultMetadata()
throws Exception {
ResultSetGroup resultSetGroup = getResultSet(TEST_RESULT_SET_RESOURCE);
ResultSet resultSet = resultSetGroup.getResultSet(0);
PinotResultSet pinotResultSet = new PinotResultSet(resultSet);
ResultSetMetaData pinotResultSetMetadata = pin... |
public static RowExpression inlineVariables(Function<VariableReferenceExpression, ? extends RowExpression> mapping, RowExpression expression)
{
return RowExpressionTreeRewriter.rewriteWith(new RowExpressionVariableInliner(mapping), expression);
} | @Test
public void testInlineVariable()
{
assertEquals(RowExpressionVariableInliner.inlineVariables(
ImmutableMap.of(
variable("a"),
variable("b")),
variable("a")),
variable("b"));
} |
public static StringBuilder appends(StringBuilder builder, CharSequence... charSequences) {
if (builder == null) {
return createBuilder(charSequences);
}
if (charSequences == null || charSequences.length == 0) {
return builder;
}
for (CharSequence sequence... | @Test
public void appends() {
StringBuilder sb1 = StringUtil.appends(null, "H", "ippo", "4j");
Assert.assertEquals("Hippo4j", sb1.toString());
StringBuilder sb2 = StringUtil.appends(StringUtil.createBuilder("To "), null);
Assert.assertEquals("To ", sb2.toString());
StringBuil... |
public static Optional<Object> buildWithConstructor(String className, Class<?>[] paramsTypes, Object[] params) {
final Class<?> clazz = loadClass(className).orElse(null);
return buildWithConstructor(clazz, paramsTypes, params);
} | @Test
public void buildWithConstructor() {
final Optional<Object> result = ReflectUtils.buildWithConstructor(TestReflect.class.getName(), null, null);
Assert.assertTrue(result.isPresent() && result.get() instanceof TestReflect);
final Optional<Object> paramsResult = ReflectUtils.buildWithCon... |
@ApiOperation(value = "Delete Tenant Profile (deleteTenantProfile)",
notes = "Deletes the tenant profile. Referencing non-existing tenant profile Id will cause an error. Referencing profile that is used by the tenants will cause an error. " + SYSTEM_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('SYS_... | @Test
public void testDeleteTenantProfile() throws Exception {
loginSysAdmin();
TenantProfile tenantProfile = this.createTenantProfile("Tenant Profile");
TenantProfile savedTenantProfile = doPost("/api/tenantProfile", tenantProfile, TenantProfile.class);
Mockito.reset(tbClusterServi... |
public boolean appliesTo(Component project, @Nullable MetricEvaluationResult metricEvaluationResult) {
return metricEvaluationResult != null
&& metricEvaluationResult.evaluationResult.level() != Measure.Level.OK
&& METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricEvaluationResult.condition.getMetric... | @Test
public void should_not_change_for_bigger_changesets() {
QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR);
Component project = generateNewRootProject();
measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, new... |
public static Identifier parse(String stringValue) {
return parse(stringValue, -1);
} | @Test
public void testParseIntegerMinInclusive() {
Identifier.parse("0");
} |
public void receiveMessage(ProxyContext ctx, ReceiveMessageRequest request,
StreamObserver<ReceiveMessageResponse> responseObserver) {
ReceiveMessageResponseStreamWriter writer = createWriter(ctx, responseObserver);
try {
Settings settings = this.grpcClientSettingsManager.getClientS... | @Test
public void testReceiveMessageIllegalFilter() {
StreamObserver<ReceiveMessageResponse> receiveStreamObserver = mock(ServerCallStreamObserver.class);
ArgumentCaptor<ReceiveMessageResponse> responseArgumentCaptor = ArgumentCaptor.forClass(ReceiveMessageResponse.class);
doNothing().when(r... |
public static boolean isValidValue(Map<String, Object> serviceSuppliedConfig,
Map<String, Object> clientSuppliedServiceConfig,
String propertyName)
{
// prevent clients from violating SLAs as published by the service
if (propertyName.eq... | @Test
public void testValidHttpRequestTimeout()
{
Map<String, Object> serviceSuppliedProperties = new HashMap<>();
serviceSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "1000");
Map<String, Object> clientSuppliedProperties = new HashMap<>();
clientSuppliedProperties.put(PropertyKeys.HTTP... |
@Override
public byte[] serialize(final String topic, final LeftOrRightValue<V1, V2> data) {
if (data == null) {
return null;
}
final byte[] rawValue = (data.getLeftValue() != null)
? leftSerializer.serialize(topic, data.getLeftValue())
: rightSerializer.... | @Test
public void shouldThrowIfSerializeOtherValueAsNull() {
assertThrows(NullPointerException.class,
() -> STRING_OR_INTEGER_SERDE.serializer().serialize(TOPIC, LeftOrRightValue.makeRightValue(null)));
} |
public static InetAddress fixScopeIdAndGetInetAddress(final InetAddress inetAddress) throws SocketException {
if (!(inetAddress instanceof Inet6Address inet6Address)) {
return inetAddress;
}
if (!inetAddress.isLinkLocalAddress() && !inetAddress.isSiteLocalAddress()) {
re... | @Test
public void testFixScopeIdAndGetInetAddress_whenLinkLocalAddress() throws SocketException, UnknownHostException {
byte[] address = InetAddress.getByName(SOME_LINK_LOCAL_ADDRESS).getAddress();
Inet6Address inet6Address = Inet6Address.getByAddress(SOME_LINK_LOCAL_ADDRESS, address, 1);
as... |
@Override
public ConsumerBuilder<T> startPaused(boolean paused) {
conf.setStartPaused(paused);
return this;
} | @Test
public void testStartPaused() {
consumerBuilderImpl.startPaused(true);
verify(consumerBuilderImpl.getConf()).setStartPaused(true);
} |
SortMergeSubpartitionReader createSubpartitionReader(
BufferAvailabilityListener availabilityListener,
int targetSubpartition,
PartitionedFile resultFile)
throws IOException {
synchronized (lock) {
checkState(!isReleased, "Partition is already released... | @Test
void testOnSubpartitionReaderError() throws Exception {
SortMergeSubpartitionReader subpartitionReader =
readScheduler.createSubpartitionReader(
new NoOpBufferAvailablityListener(), 0, partitionedFile);
subpartitionReader.releaseAllResources();
... |
public static Area getArea(Integer id) {
return areas.get(id);
} | @Test
public void testGetArea() {
// 调用:北京
Area area = AreaUtils.getArea(110100);
// 断言
assertEquals(area.getId(), 110100);
assertEquals(area.getName(), "北京市");
assertEquals(area.getType(), AreaTypeEnum.CITY.getType());
assertEquals(area.getParent().getId(), 1... |
@Override
public Num calculate(BarSeries series, Position position) {
if (position == null || position.getEntry() == null || position.getExit() == null) {
return series.zero();
}
CashFlow cashFlow = new CashFlow(series, position);
return calculateMaximumDrawdown(series, n... | @Test
public void withTradesThatSellBeforeBuying() {
MockBarSeries series = new MockBarSeries(numFunction, 2, 1, 3, 5, 6, 3, 20);
AnalysisCriterion mdd = getCriterion();
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series),
Trade... |
@Override
public byte[] evaluateResponse( @Nonnull final byte[] response ) throws SaslException
{
if ( isComplete() )
{
throw new IllegalStateException( "Authentication exchange already completed." );
}
// The value as sent to us in the 'from' attribute of the stream... | @Test
public void testEmptyInitialResponse() throws Exception
{
// Setup test fixture.
final String streamID = "example.org";
when(session.getSessionData(SASLAuthentication.SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY)).thenReturn(true);
when(session.getDefaultIdentity()).thenRetur... |
public boolean containsShardingTable(final Collection<String> logicTableNames) {
for (String each : logicTableNames) {
if (isShardingTable(each)) {
return true;
}
}
return false;
} | @Test
void assertContainsShardingTableForMultipleTables() {
assertTrue(createMaximumShardingRule().containsShardingTable(Arrays.asList("logic_table", "table_0")));
} |
public QueryResult queryMessage(String topic, String key, int maxNum, long begin, long end)
throws MQClientException, InterruptedException {
return this.mQClientFactory.getMQAdminImpl().queryMessage(topic, key, maxNum, begin, end);
} | @Test
public void testQueryMessage() throws InterruptedException, MQClientException {
assertNull(defaultMQPushConsumerImpl.queryMessage(defaultTopic, defaultKey, 1, 0, 1));
} |
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return isWebSocketUpgrade(exchange.getRequest().getHeaders()) ? match() : notMatch();
} | @Test
void shouldMatchIfWebSocketProtocol() {
var httpRequest = MockServerHttpRequest.get("")
.header(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE)
.header(HttpHeaders.UPGRADE, "websocket")
.build();
var wsExchange = MockServerWebExchange.from(httpRequest);
... |
public static <T> Read<T> readAvrosWithBeamSchema(Class<T> clazz) {
if (clazz.equals(GenericRecord.class)) {
throw new IllegalArgumentException("For GenericRecord, please call readAvroGenericRecords");
}
AvroCoder<T> coder = AvroCoder.of(clazz);
org.apache.avro.Schema avroSchema = coder.getSchema(... | @Test
public void testAvroSpecificRecord() {
AvroCoder<AvroGeneratedUser> coder = AvroCoder.specific(AvroGeneratedUser.class);
List<AvroGeneratedUser> inputs =
ImmutableList.of(
new AvroGeneratedUser("Bob", 256, null),
new AvroGeneratedUser("Alice", 128, null),
new ... |
@Override
public Set<OAuth2AccessTokenEntity> getAllAccessTokens() {
TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_ALL, OAuth2AccessTokenEntity.class);
return new LinkedHashSet<>(query.getResultList());
} | @Test
public void testGetAllAccessTokens(){
Set<OAuth2AccessTokenEntity> tokens = repository.getAllAccessTokens();
assertEquals(4, tokens.size());
} |
public AlterSourceCommand create(final AlterSource statement) {
final DataSource dataSource = metaStore.getSource(statement.getName());
final String dataSourceType = statement.getDataSourceType().getKsqlType();
if (dataSource != null && dataSource.isSource()) {
throw new KsqlException(
Stri... | @Test
public void shouldThrowInAlterOnSourceTable() {
// Given:
final AlterSource alterSource = new AlterSource(TABLE_NAME, DataSourceType.KTABLE, NEW_COLUMNS);
when(ksqlTable.isSource()).thenReturn(true);
// When:
final Exception e = assertThrows(
KsqlException.class, () -> alterSourceFa... |
@Override
public void ack() {
Function.ProcessingGuarantees processingGuarantees = functionConfig.getProcessingGuarantees();
if (processingGuarantees == Function.ProcessingGuarantees.MANUAL) {
record.ack();
} else {
log.warn("Ignore this ack option, under this configu... | @Test
public void testAck() {
Record record = mock(Record.class);
Function.FunctionDetails functionDetails = Function.FunctionDetails.newBuilder().setAutoAck(true)
.setProcessingGuarantees(Function.ProcessingGuarantees.ATMOST_ONCE).build();
PulsarFunctionRecord pulsarFunction... |
private Function<KsqlConfig, Kudf> getUdfFactory(
final Method method,
final UdfDescription udfDescriptionAnnotation,
final String functionName,
final FunctionInvoker invoker,
final String sensorName
) {
return ksqlConfig -> {
final Object actualUdf = FunctionLoaderUtils.instan... | @Test
public void shouldEnsureFunctionReturnTypeIsDeepOptional() {
final List<SqlArgument> args = Collections.singletonList(SqlArgument.of(SqlTypes.STRING));
final KsqlScalarFunction complexFunction = FUNC_REG
.getUdfFactory(FunctionName.of("ComplexFunction"))
.getFunction(args);
assertTh... |
static boolean fieldMatchCaseInsensitive(Object repoObj, Object filterObj) {
return fieldMatch(repoObj, filterObj) || compareIgnoreCaseOnlyIfStringType(repoObj, filterObj);
} | @Test
public void testFieldMatchWithEqualObjectsShouldReturnTrue() {
assertTrue(Utilities.fieldMatchCaseInsensitive("repoObject", "repoObject"));
} |
public static Object[] realize(Object[] objs, Class<?>[] types) {
if (objs.length != types.length) {
throw new IllegalArgumentException("args.length != types.length");
}
Object[] dests = new Object[objs.length];
for (int i = 0; i < objs.length; i++) {
dests[i] = ... | @Test
public void testPojoGeneric4() throws NoSuchMethodException {
String personName = "testName";
Dgeneric generic = createDGenericPersonInfo(personName);
Object o = JSON.toJSON(generic);
{
Dgeneric personInfo = (Dgeneric) PojoUtils.realize(o, Dgeneric.class);
... |
@Operation(summary = "Start collecting of Metadata for one or all connections ")
@GetMapping(value = "collect_metadata/{id}", produces = "application/json")
public Map<String, String> collectMetadata(@PathVariable("id") String id) throws CollectSamlMetadataException {
return metadataProcessorService.col... | @Test
public void failedCollectingMetadata() throws CollectSamlMetadataException {
when(metadataProcessorServiceMock.collectSamlMetadata(anyString())).thenThrow(CollectSamlMetadataException.class);
assertThrows(CollectSamlMetadataException.class, () -> {
controllerMock.collectMetadata(an... |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testRetryOtherThanRemoteException() throws Throwable {
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
Collections.<Class<? extends Exception>, RetryPolicy>singletonMap(
IOException.class, RETRY_FOREVER);
UnreliableInterface unreliable = (UnreliableIn... |
@Override
public String toString() {
return toString(null);
} | @Test
public void testMultiSigOutputToString() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
ECKey myKey = new ECKey();
this.wallet.importKey(myKey);
// Simulate another signatory
ECKey otherKey = new ECKey();
// Create... |
@GET
@Path("{path:.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8})
public Response get(@PathParam("path") String path,
@Context UriInfo uriInfo,
@QueryParam(OperationParam.NAME) O... | @Test
@TestDir
@TestJetty
@TestHdfs
public void testNoRedirect() throws Exception {
createHttpFSServer(false, false);
final String testContent = "Test content";
final String path = "/testfile.txt";
final String username = HadoopUsersConfTestHelper.getHadoopUsers()[0];
// Trigger the creat... |
public static FunctionTypeInfo getFunctionTypeInfo(
final ExpressionTypeManager expressionTypeManager,
final FunctionCall functionCall,
final UdfFactory udfFactory,
final Map<String, SqlType> lambdaMapping
) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final List<Expression> argument... | @Test
public void shouldResolveLambdaWithoutGenerics() {
// Given:
givenUdfWithNameAndReturnType("SmallLambda", SqlTypes.DOUBLE);
when(function.parameters()).thenReturn(
ImmutableList.of(
ArrayType.of(ParamTypes.DOUBLE), LambdaType.of(ImmutableList.of(ParamTypes.INTEGER), ParamTypes.IN... |
protected boolean databaseForBothDbInterfacesIsTheSame( DatabaseInterface primary, DatabaseInterface secondary ) {
if ( primary == null || secondary == null ) {
throw new IllegalArgumentException( "DatabaseInterface shouldn't be null!" );
}
if ( primary.getPluginId() == null || secondary.getPluginId(... | @Test
public void databases_WithSameDbConnTypes_AreNotSame_IfPluginIdIsNull() {
DatabaseInterface mssqlServerDatabaseMeta = new MSSQLServerDatabaseMeta();
mssqlServerDatabaseMeta.setPluginId( null );
assertFalse(
databaseMeta.databaseForBothDbInterfacesIsTheSame( mssqlServerDatabaseMeta, mssqlServer... |
@Override
public void initializeState(StateInitializationContext context) throws Exception {
if (isPartitionCommitTriggerEnabled()) {
partitionCommitPredicate =
PartitionCommitPredicate.create(conf, getUserCodeClassloader(), partitionKeys);
}
currentNewPartit... | @Test
void testCommitFileWhenPartitionIsCommittableByProcessTime() throws Exception {
// the rolling policy is not to roll file by filesize and roll file after one day,
// it can ensure the file can be closed only when the partition is committable in this test.
FileSystemTableSink.TableRolli... |
public Expression toPredicate(TupleDomain<String> tupleDomain)
{
if (tupleDomain.isNone()) {
return FALSE_LITERAL;
}
Map<String, Domain> domains = tupleDomain.getDomains().get();
return domains.entrySet().stream()
.sorted(comparing(entry -> entry.getKey()... | @Test
public void testInOptimization()
{
Domain testDomain = Domain.create(
ValueSet.all(BIGINT)
.subtract(ValueSet.ofRanges(
Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L), Range.equal(BIGINT, 3L))), false);
TupleDomain<... |
@Override
public URL getResource(String name) {
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resource '{}'", name);
for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) {
URL url = null;
... | @Test
void parentLastGetResourceExistsInParentAndDependencyAndPlugin() throws URISyntaxException, IOException {
URL resource = parentLastPluginClassLoader.getResource("META-INF/file-in-both-parent-and-dependency-and-plugin");
assertFirstLine("plugin", resource);
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test(dataProvider = "restOrStream")
public void testSyncNullObject404(final RestOrStream restOrStream) throws Exception
{
final StatusCollectionResource statusResource = getMockResource(StatusCollectionResource.class);
EasyMock.expect(statusResource.get(eq(1L))).andReturn(null).once();
replay(statusRes... |
public Integer doCall() throws Exception {
if (all) {
client(Integration.class).delete();
printer().println("Integrations deleted");
} else {
if (names == null) {
throw new RuntimeCamelException("Missing integration name as argument or --all option.");... | @Test
public void shouldDeleteAll() throws Exception {
Integration integration1 = createIntegration("foo");
Integration integration2 = createIntegration("bar");
kubernetesClient.resources(Integration.class).resource(integration1).create();
kubernetesClient.resources(Integration.clas... |
@Override
public ExportResult<CalendarContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) {
if (!exportInformation.isPresent()) {
return exportCalendars(authData, Optional.empty());
} else {
StringPaginationToken paginationToke... | @Test
public void exportEventSubsequentSet() throws IOException {
setUpSingleEventResponse();
// Looking at subsequent page, with no pages after it
ContainerResource containerResource = new IdOnlyContainerResource(CALENDAR_ID);
PaginationData paginationData = new StringPaginationToken(EVENT_TOKEN_PRE... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuilder buf = new StringBuilder();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_ST... | @Test
public void literalContainingColon() throws ScanException {
String input = "a:b";
Tokenizer tokenizer = new Tokenizer(input);
List<Token> tokenList = tokenizer.tokenize();
witnessList.add(new Token(Token.Type.LITERAL, "a"));
witnessList.add(new Token(Token.Type.LITERAL,... |
@Override
public String getRawSourceHash(Component file) {
checkComponentArgument(file);
if (rawSourceHashesByKey.containsKey(file.getKey())) {
return checkSourceHash(file.getKey(), rawSourceHashesByKey.get(file.getKey()));
} else {
String newSourceHash = computeRawSourceHash(file);
rawS... | @Test
void getRawSourceHash_returns_hash_of_lines_from_SourceLinesRepository() {
sourceLinesRepository.addLines(FILE_REF, SOME_LINES);
String rawSourceHash = underTest.getRawSourceHash(FILE_COMPONENT);
SourceHashComputer sourceHashComputer = new SourceHashComputer();
for (int i = 0; i < SOME_LINES.l... |
public static CoordinatorRecord newGroupMetadataRecord(
ClassicGroup group,
Map<String, byte[]> assignment,
MetadataVersion metadataVersion
) {
List<GroupMetadataValue.MemberMetadata> members = new ArrayList<>(group.allMembers().size());
group.allMembers().forEach(member -> {... | @Test
public void testNewGroupMetadataRecordThrowsWhenNullSubscription() {
Time time = new MockTime();
List<GroupMetadataValue.MemberMetadata> expectedMembers = new ArrayList<>();
expectedMembers.add(
new GroupMetadataValue.MemberMetadata()
.setMemberId("member-1... |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test
public void test4412PathWildcards() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket4412Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /test/sws/{var}:\n" +
" get:\n" +
... |
protected static String[] getOAuthPrefix(final Host bookmark) {
if(StringUtils.isNotBlank(bookmark.getCredentials().getUsername())) {
return new String[]{
String.format("%s (%s)", bookmark.getProtocol().getOAuthClientId(), bookmark.getCredentials().getUsername()),
... | @Test
public void testGetOAuthPrefix() {
final String[] prefix = DefaultHostPasswordStore.getOAuthPrefix(new Host(new TestProtocol(Scheme.https) {
@Override
public String getOAuthClientId() {
return "clientid";
}
@Override
public S... |
public void restore(final List<Pair<byte[], byte[]>> backupCommands) {
// Delete the command topic
deleteCommandTopicIfExists();
// Create the command topic
KsqlInternalTopicUtils.ensureTopic(commandTopicName, serverConfig, topicClient);
// Restore the commands
restoreCommandTopic(backupComman... | @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT")
@Test
public void shouldThrowIfCannotCreateTopic() {
// Given:
when(topicClient.isTopicExists(COMMAND_TOPIC_NAME)).thenReturn(false);
doThrow(new RuntimeException("denied")).when(topicClient)
.createTopic(COMMAND_TOPIC_NAME, INTERNAL_... |
@Override
public boolean createTopic(
final String topic,
final int numPartitions,
final short replicationFactor,
final Map<String, ?> configs,
final CreateTopicsOptions createOptions
) {
final Optional<Long> retentionMs = KafkaTopicClient.getRetentionMs(configs);
if (isTopicE... | @Test
public void shouldNotCreateTopicIfItAlreadyExistsWithDefaultRf() {
// Given:
givenTopicExists("someTopic", 1, 2);
givenTopicConfigs(
"someTopic",
overriddenConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "8640000000")
);
// When:
kafkaTopicClient.createTopic("someTopic", 1,... |
public ECPoint getQ() {
return q;
} | @Test
public void shouldConvertPublicPoint() {
final EcPrivateKey key = new EcPrivateKey(new ECPrivateKeySpec(D, SPEC));
assertEquals(Q, key.getQ());
assertEquals(true, key.getQ().isNormalized());
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 2) {
onInvalidDataReceived(device, data);
return;
}
// Read flags
int offset = 0;
final int flags = data.getIntValue(Data.FORMAT_UINT8, offse... | @Test
public void onHeartRateMeasurementReceived_simple() {
success = false;
final Data data = new Data(new byte[] { 0, 85 });
response.onDataReceived(null, data);
assertTrue(response.isValid());
assertTrue(success);
assertEquals(85, heartRate);
assertNull(contactDetected);
assertNull(energyExpanded);
... |
@Override
public final String toString() {
StringBuilder out = new StringBuilder();
appendTo(out);
return out.toString();
} | @Test
void requireThatPredicatesCanBeConstructedUsingConstructors() {
assertEquals("country in [no, se] and age in [20..30]",
new Conjunction(new FeatureSet("country", "no", "se"),
new FeatureRange("age", 20L, 30L)).toString());
assertEquals("country not in [n... |
@InvokeOnHeader(Web3jConstants.ETH_COINBASE)
void ethCoinbase(Message message) throws IOException {
Request<?, EthCoinbase> request = web3j.ethCoinbase();
setRequestId(message, request);
EthCoinbase response = request.send();
boolean hasError = checkForError(message, response);
... | @Test
public void ethCoinbaseTest() throws Exception {
EthCoinbase response = Mockito.mock(EthCoinbase.class);
Mockito.when(mockWeb3j.ethCoinbase()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAddress()).thenReturn("123");
... |
@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 shouldReturnNullForAllNullInputs() {
final List<Long> result = udf.concat((List<Long>) null, (List<Long>) null);
assertThat(result, is(nullValue()));
} |
public static SerializableFunction<byte[], Row> getProtoBytesToRowFunction(
String fileDescriptorPath, String messageName) {
ProtoSchemaInfo dynamicProtoDomain = getProtoDomain(fileDescriptorPath, messageName);
ProtoDomain protoDomain = dynamicProtoDomain.getProtoDomain();
@SuppressWarnings("unchecke... | @Test
public void testProtoBytesToRowFunctionGenerateSerializableFunction() {
SerializableFunction<byte[], Row> protoBytesToRowFunction =
ProtoByteUtils.getProtoBytesToRowFunction(DESCRIPTOR_PATH, MESSAGE_NAME);
Assert.assertNotNull(protoBytesToRowFunction);
} |
public static <T> Iterator<T> iterator(Class<T> expectedType, String factoryId, ClassLoader classLoader) throws Exception {
Iterator<Class<T>> classIterator = classIterator(expectedType, factoryId, classLoader);
return new NewInstanceIterator<>(classIterator);
} | @Test
public void loadServicesTcclAndGivenClassLoader() throws Exception {
Class<ServiceLoaderTestInterface> type = ServiceLoaderTestInterface.class;
String factoryId = "com.hazelcast.ServiceLoaderTestInterface";
ClassLoader given = new URLClassLoader(new URL[0]);
Thread current = ... |
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates)
{
List<String> perColumnExpressions = new ArrayList<>();
int expressionLength = 0;
for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) {
String columnName = partition... | @Test
public void testBuildGlueExpressionTupleDomainEqualsSingleValue()
{
Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR)
.addStringValues("col1", "2020-01-01")
.addStringValues("col2", "2020-02-20")
.build();
Stri... |
@Override
public double cdf(double k) {
if (k < 0) {
return 0.0;
} else {
return regularizedIncompleteBetaFunction(r, k + 1, p);
}
} | @Test
public void testCdf() {
System.out.println("cdf");
NegativeBinomialDistribution instance = new NegativeBinomialDistribution(3, 0.3);
instance.rand();
assertEquals(0.027, instance.cdf(0), 1E-7);
assertEquals(0.0837, instance.cdf(1), 1E-7);
assertEquals(0.16308, i... |
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | @Test
public void testInvalidProfileLocation() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setSaveProfilesToGcs("file://my/staging/location");
try {
DataflowRunner.fromOptions(options);
fail("fromOptions should have failed");
} catch (IllegalArgum... |
@Override
public DistroData getData(DistroKey key, String targetServer) {
Member member = memberManager.find(targetServer);
if (checkTargetServerStatusUnhealthy(member)) {
throw new DistroException(
String.format("[DISTRO] Cancel get snapshot caused by target server %... | @Test
void testGetDataForMemberNonExist() {
assertThrows(DistroException.class, () -> {
transportAgent.getData(new DistroKey(), member.getAddress());
});
} |
public void importCounters(String[] counterNames, String[] counterKinds, long[] counterDeltas) {
final int length = counterNames.length;
if (counterKinds.length != length || counterDeltas.length != length) {
throw new AssertionError("array lengths do not match");
}
for (int i = 0; i < length; ++i)... | @Test
public void testSinglePreexistingCounter() throws Exception {
Counter<Long, Long> sumCounter =
counterSet.longSum(CounterName.named("stageName-systemName-dataset-sum_counter"));
sumCounter.addValue(1000L);
String[] names = {"sum_counter"};
String[] kinds = {"sum"};
long[] deltas = {1... |
@Override
public void warn(String msg) {
logger.warn(msg);
} | @Test
public void testWarn() {
Log mockLog = mock(Log.class);
InternalLogger logger = new CommonsLogger(mockLog, "foo");
logger.warn("a");
verify(mockLog).warn("a");
} |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromSnapshotTimestampWithInvalidIds() throws Exception {
appendTwoSnapshots();
long invalidSnapshotTimestampMs = snapshot2.timestampMillis() + 1000L;
ScanContext scanContextWithInvalidSnapshotId =
ScanContext.builder()
.startingStrategy(StreamingStart... |
LinkedList<RewriteOp> makeRewriteOps(
Iterable<String> srcFilenames,
Iterable<String> destFilenames,
boolean deleteSource,
boolean ignoreMissingSource,
boolean ignoreExistingDest)
throws IOException {
List<String> srcList = Lists.newArrayList(srcFilenames);
List<String> destL... | @Test
public void testMakeRewriteOpsInvalid() throws IOException {
GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Number of source files 3");
gcsUtil.makeRewriteOps(makeStrings("s", 3), makeStrings("d", 1), false, fa... |
public void checkForUpgradeAndExtraProperties() throws IOException {
if (upgradesEnabled()) {
checkForUpgradeAndExtraProperties(systemEnvironment.getAgentMd5(), systemEnvironment.getGivenAgentLauncherMd5(),
systemEnvironment.getAgentPluginsMd5(), systemEnvironment.getTfsImplMd5()... | @Test
void checkForUpgradeShouldKillAgentIfTfsMd5doesNotMatch() {
when(systemEnvironment.getAgentMd5()).thenReturn("not-changing");
expectHeaderValue(SystemEnvironment.AGENT_CONTENT_MD5_HEADER, "not-changing");
when(systemEnvironment.getGivenAgentLauncherMd5()).thenReturn("not-changing");
... |
public static FaloTheBardClue forText(String text)
{
for (FaloTheBardClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
} | @Test
public void forTextEmptyString()
{
assertNull(FaloTheBardClue.forText(""));
} |
public static String join(List<String> src, String delimiter) {
return src == null ? null : String.join(delimiter, src.toArray(new String[0]));
} | @Test
public void testJoin() {
assertEquals(join(Arrays.asList("a", "b"), "|"), ("a|b"));
assertNull(join(null, "|"));
assertEquals(join(Collections.singletonList("a"), "|"), ("a"));
} |
@Override
public boolean updateAccessConfig(PlainAccessConfig plainAccessConfig) {
return aclPlugEngine.updateAccessConfig(plainAccessConfig);
} | @Test(expected = AclException.class)
public void createAndUpdateAccessAclNullSkExceptionTest() {
String backupFileName = System.getProperty("rocketmq.home.dir")
+ File.separator + "conf/plain_acl_bak.yml".replace("/", File.separator);
String targetFileName = System.getProperty("rocke... |
@Override
public synchronized void updateDockerRunCommand(
DockerRunCommand dockerRunCommand, Container container)
throws ContainerExecutionException {
if (!requestsGpu(container)) {
return;
}
Set<GpuDevice> assignedResources = getAssignedGpus(container);
if (assignedResources == nul... | @Test
public void testPlugin() throws Exception {
DockerRunCommand runCommand = new DockerRunCommand("container_1", "user",
"fakeimage");
Map<String, List<String>> originalCommandline = copyCommandLine(
runCommand.getDockerCommandWithArguments());
MyNvidiaDockerV2CommandPlugin
co... |
public static Integer getInt(Map<?, ?> map, Object key) {
return get(map, key, Integer.class);
} | @Test
public void getIntTest(){
assertThrows(NumberFormatException.class, () -> {
final HashMap<String, String> map = MapUtil.of("age", "d");
final Integer age = MapUtil.getInt(map, "age");
assertNotNull(age);
});
} |
List<CSVResult> sniff(Reader reader) throws IOException {
if (!reader.markSupported()) {
reader = new BufferedReader(reader);
}
List<CSVResult> ret = new ArrayList<>();
for (char delimiter : delimiters) {
reader.mark(markLimit);
try {
C... | @Test
public void testCSVMidCellQuoteException() throws Exception {
List<CSVResult> results =
sniff(DELIMITERS, CSV_MID_CELL_QUOTE_EXCEPTION, StandardCharsets.UTF_8);
assertEquals(4, results.size());
} |
public static StatementExecutorResponse execute(
final ConfiguredStatement<Explain> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
return StatementExecutorResponse.handled(Optional
.of(Expla... | @Test
public void shouldExplainStatementWithStructFieldDereference() {
// Given:
engine.givenSource(DataSourceType.KSTREAM, "Y");
final String statementText = "SELECT address->street FROM Y EMIT CHANGES;";
final ConfiguredStatement<?> explain = engine.configure("EXPLAIN " + statementText);
// Whe... |
public List<ShardingCondition> createShardingConditions(final SQLStatementContext sqlStatementContext, final List<Object> params) {
if (!(sqlStatementContext instanceof WhereAvailable)) {
return Collections.emptyList();
}
Collection<ColumnSegment> columnSegments = ((WhereAvailable) s... | @Test
void assertCreateShardingConditionsForSelectRangeStatement() {
int between = 1;
int and = 100;
ColumnSegment left = new ColumnSegment(0, 0, new IdentifierValue("foo_sharding_col"));
ExpressionSegment betweenSegment = new LiteralExpressionSegment(0, 0, between);
Expressi... |
@Override
public void getErrors(ErrorCollection errors, String parentLocation) {
String location = getLocation(parentLocation);
super.getErrors(errors, parentLocation);
errors.checkMissing(location, "id", id);
errors.checkMissing(location, "store_id", storeId);
if (this.confi... | @Test
public void shouldCheckForTypeWhileDeserializing() {
String json = """
{
"id" : "id",
"store_id" : "s3"
}""";
CRPluggableArtifact crPluggableArtifact = gson.fromJson(json, CRPluggableArtifact.cla... |
@Override
public void handle(final RoutingContext routingContext) {
// We must set it to allow chunked encoding if we're using http1.1
if (routingContext.request().version() == HttpVersion.HTTP_1_1) {
routingContext.response().putHeader(TRANSFER_ENCODING, CHUNKED_ENCODING);
} else if (routingContext... | @Test
public void shouldSucceed_printQuery() {
// Given:
final QueryStreamArgs req = new QueryStreamArgs("print mytopic;",
Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap());
givenRequest(req);
// When:
handler.handle(routingContext);
endHandler.getValue().handle(... |
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
BlockingQueue<Runnable> workQueue = executor.getQueue();
Runnable firstWork = workQueue.poll();
boolean newTaskAdd = workQueue.offer(r);
... | @Test
public void testRejectedExecutionWhenATaskIsInTheQueueAndThePollReturnANullValue() {
when(threadPoolExecutor.isShutdown()).thenReturn(false);
when(threadPoolExecutor.getQueue()).thenReturn(workQueue);
when(workQueue.poll()).thenReturn(null);
when(workQueue.offer(runnable)).then... |
String path() { return path; } | @Test
public void testDecodePath() {
final String ESCAPED_PATH = "/test%25+1%26%3Dtest?op=OPEN&foo=bar";
final String EXPECTED_PATH = "/test%+1&=test";
Configuration conf = new Configuration();
QueryStringDecoder decoder = new QueryStringDecoder(
WebHdfsHandler.WEBHDFS_PREFIX + ESCAPED_PATH);
... |
public static String dataToAvroSchemaJson(DataSchema dataSchema)
{
return dataToAvroSchemaJson(dataSchema, new DataToAvroSchemaTranslationOptions());
} | @Test(dataProvider = "embeddingSchemaWithDataPropertyData")
public void testEmbeddingSchemaWithDataProperty(String schemaText, String expected) throws IOException
{
DataToAvroSchemaTranslationOptions options = new DataToAvroSchemaTranslationOptions(JsonBuilder.Pretty.SPACES, EmbedSchemaMode.ROOT_ONLY);
Stri... |
@Override public Revision getCurrentRevision(String requestedMaterialName) {
return UNKNOWN_REVISION;
} | @Test
public void shouldReturnUnknownModificationAsCurrent() {
assertThat(instanceModel.getCurrentRevision("foo"), is(PipelineInstanceModel.UNKNOWN_REVISION));
} |
@Override
public PageData<WidgetTypeInfo> findTenantWidgetTypesByTenantId(WidgetTypeFilter widgetTypeFilter, PageLink pageLink) {
boolean deprecatedFilterEnabled = !DeprecatedFilter.ALL.equals(widgetTypeFilter.getDeprecatedFilter());
boolean deprecatedFilterBool = DeprecatedFilter.DEPRECATED.equals(... | @Test
public void testTagsSearchInFindTenantWidgetTypesByTenantId() {
for (var entry : SHOULD_FIND_SEARCH_TO_TAGS_MAP.entrySet()) {
String searchText = entry.getKey();
String[] tags = entry.getValue();
WidgetTypeDetails savedWidgetType = createAndSaveWidgetType(TenantId.... |
@Override
public boolean canManageInput(EfestoInput toEvaluate, EfestoRuntimeContext context) {
return canManageEfestoInput(toEvaluate, context);
} | @Test
void canManageInput() {
modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME);
PMMLRuntimeContext context = getPMMLContext(FILE_NAME, MODEL_NAME, memoryCompilerClassLoader);
BaseEfestoInput inputPMML = new EfestoInputPMML(modelLocalUriId, context);
assert... |
public PipelineConfigs findGroup(String groupName) {
for (PipelineConfigs pipelines : this) {
if (pipelines.isNamed(groupName)) {
return pipelines;
}
}
throw new RecordNotFoundException(EntityType.PipelineGroup, groupName);
} | @Test
public void shouldThrowGroupNotFoundExceptionWhenSearchingForANonExistingGroup() {
PipelineConfig pipeline = createPipelineConfig("pipeline1", "stage1");
PipelineConfigs defaultGroup = createGroup("defaultGroup", pipeline);
PipelineGroups pipelineGroups = new PipelineGroups(defaultGrou... |
@Override
public Subscriber getSubscriber(Service service) {
return subscribers.get(service);
} | @Test
void getSubscriber() {
addServiceSubscriber();
Subscriber subscriber1 = abstractClient.getSubscriber(service);
assertNotNull(subscriber1);
} |
public static Write write() {
return Write.create();
} | @Test
public void testWriteClientRateLimitingAlsoSetReportMsecs() {
// client side flow control
BigtableIO.Write write = BigtableIO.write().withTableId("table").withFlowControl(true);
assertEquals(
60_000, (int) checkNotNull(write.getBigtableWriteOptions().getThrottlingReportTargetMs()));
// ... |
@Override
public ValidationResult validate(Object value) {
ValidationResult result = super.validate(value);
if (result instanceof ValidationResult.ValidationPassed) {
final String sValue = (String)value;
if (sValue.length() < minLength || sValue.length() > maxLength) {
... | @Test
public void testValidateNoString() {
assertThat(new LimitedStringValidator(1, 1).validate(123))
.isInstanceOf(ValidationResult.ValidationFailed.class);
} |
@Override
public void write(String propertyKey, @Nullable String value) {
checkPropertyKey(propertyKey);
try (DbSession dbSession = dbClient.openSession(false)) {
if (value == null || value.isEmpty()) {
dbClient.internalPropertiesDao().saveAsEmpty(dbSession, propertyKey);
} else {
... | @Test
public void write_throws_IAE_if_key_is_null() {
expectKeyNullOrEmptyIAE(() -> underTest.write(null, SOME_VALUE));
} |
@Override
public AppResponse process(Flow flow, ConfirmRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
var authAppSession = appSessionService.getSession(request.getAuthSessionId());
if (!isAppSessionAuthenticated(authAppSession) || !request.getUserAppId().eq... | @Test
public void processReturnsNokResponse() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
//given
authAppSession.setState("NOTAUTHENTICATED");
when(appSessionService.getSession(confirmRequest.getAuthSessionId())).thenReturn(authAppSession);
//when
... |
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
// TODO do not load everything in memory. Db rows should be scrolled.
List<IndexPermissions> authorizations = getAllAuthorizations();
Stream<AuthorizationScope> scopes = getScopes(uninitializedIndexTypes);
index(authorizati... | @Test
public void indexOnStartup_grants_access_to_anybody_on_public_project() {
ProjectDto project = createAndIndexPublicProject();
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
indexOnStartup();
verifyAnyoneAuthorized(project);
verifyAuthorized(project, ... |
public Object resolve(final Expression expression) {
return new Visitor().process(expression, null);
} | @Test
public void shouldThrowIfCannotParseTime() {
// Given:
final SqlType type = SqlTypes.TIME;
final Expression exp = new StringLiteral("abc");
// When:
final KsqlException e = assertThrows(
KsqlException.class,
() -> new GenericExpressionResolver(type, FIELD_NAME, registry, con... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testRelativeOffsetAssignmentNonCompressedV2() {
long now = System.currentTimeMillis();
MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V2, now, Compression.NONE);
long offset = 1234567;
checkOffsets(records, 0);
MemoryRecords messageWithOffse... |
@Override
public abstract boolean equals(Object other); | @Test
public void testEnumDataSchema() throws Exception
{
final String schemaString = "{ \"type\" : \"enum\", \"name\" : \"numbers\", \"symbols\" : [ \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\"], \"symbolDocs\" : { \"FIVE\" : \"DOC_FIVE\", \"ONE\" : \"DOC_ONE\" } }";
PegasusSchemaParser parser = schemaP... |
public synchronized ConnectionProfile createGCSDestinationConnectionProfile(
String connectionProfileId, String gcsBucketName, String gcsRootPath) {
checkArgument(
!Strings.isNullOrEmpty(connectionProfileId),
"connectionProfileId can not be null or empty");
checkArgument(!Strings.isNullOrE... | @Test
public void testCreateGCSDestinationConnectionProfileWithInvalidGCSRootPathShouldFail() {
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class,
() ->
testManager.createGCSDestinationConnectionProfile(
CONNECTION... |
@VisibleForTesting
public static UClassIdent create(String qualifiedName) {
List<String> topLevelPath = new ArrayList<>();
for (String component : Splitter.on('.').split(qualifiedName)) {
topLevelPath.add(component);
if (Character.isUpperCase(component.charAt(0))) {
break;
}
}
... | @Test
public void equality() throws CouldNotResolveImportException {
new EqualsTester()
.addEqualityGroup(UClassIdent.create("java.util.List"))
.addEqualityGroup(UClassIdent.create("com.sun.tools.javac.util.List"))
.addEqualityGroup(
UClassIdent.create("java.lang.String"),
... |
@Override
public Collection<V> valueRange(int startIndex, int endIndex) {
return get(valueRangeAsync(startIndex, endIndex));
} | @Test
public void testValueRange() {
RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple");
set.add(0, 1);
set.add(1, 2);
set.add(2, 3);
set.add(3, 4);
set.add(4, 5);
set.add(4, 5);
Collection<Integer> vals = set.valueRange(0, -1);
... |
public Record update(MetricsRecord mr, boolean includingTags) {
String name = mr.name();
RecordCache recordCache = map.get(name);
if (recordCache == null) {
recordCache = new RecordCache();
map.put(name, recordCache);
}
Collection<MetricsTag> tags = mr.tags();
Record record = recordC... | @SuppressWarnings("deprecation")
@Test public void testUpdate() {
MetricsCache cache = new MetricsCache();
MetricsRecord mr = makeRecord("r",
Arrays.asList(makeTag("t", "tv")),
Arrays.asList(makeMetric("m", 0), makeMetric("m1", 1)));
MetricsCache.Record cr = cache.update(mr);
verify(m... |
@Override
public void run() {
boolean isNeedFlush = false;
boolean sqlShowEnabled = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps().getValue(ConfigurationPropertyKey.SQL_SHOW);
try {
if (sqlShowEnabled) {
fillLogMDC();... | @Test
void assertRunNeedFlushByFalse() throws SQLException, BackendConnectionException {
when(queryCommandExecutor.execute()).thenReturn(Collections.emptyList());
when(engine.getCommandExecuteEngine().getCommandPacket(payload, commandPacketType, connectionSession)).thenReturn(commandPacket);
... |
@SuppressWarnings("unchecked")
public <V> V run(String callableName, RetryOperation<V> operation)
{
int attempt = 1;
while (true) {
try {
return operation.run();
}
catch (Exception e) {
if (!exceptionClass.isInstance(e)) {
... | @Test
public void testSuccess()
{
assertEquals(
retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION)),
Integer.valueOf(5));
} |
public IterableSubject asList() {
return checkNoNeedToDisplayBothValues("asList()").that(Longs.asList(checkNotNull(actual)));
} | @Test
public void asList() {
assertThat(array(5, 2, 9)).asList().containsAtLeast(2L, 9L);
} |
public static String getKey(String dataId, String group) {
return getKey(dataId, group, "");
} | @Test
public void testGetKey1() {
String[] strings = {"dataId", "group", "datumStr"};
String expected = "dataId+group+datumStr";
String key = GroupKey.getKey(strings);
Assert.isTrue(key.equals(expected));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.