focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public PulsarAdmin build() throws PulsarClientException {
return new PulsarAdminImpl(conf.getServiceUrl(), conf, clientBuilderClassLoader, acceptGzipCompression);
} | @Test
public void testBuildFailsWhenServiceUrlNotSet() {
assertThatIllegalArgumentException().isThrownBy(() -> PulsarAdmin.builder().build())
.withMessageContaining("Service URL needs to be specified");
} |
@Override
public void recordMisses(int count) {
missCount.inc(count);
} | @Test
public void miss() {
stats.recordMisses(2);
assertThat(registry.counter(PREFIX + ".misses").getCount()).isEqualTo(2);
} |
public boolean overlaps(final BoundingBox pBoundingBox, double pZoom) {
//FIXME this is a total hack but it works around a number of issues related to vertical map
//replication and horiztonal replication that can cause polygons to completely disappear when
//panning
if (pZoom < 3)
... | @Test
public void testOverlapsDateLine2() {
// ________________
// | | |
// |** ?? | **|
// |-*----+-----*-|
// |** | **|
// | | |
// ----------------
//box is notated as *
//test area is notated as ?
... |
@Override
public void trackAppInstall(JSONObject properties, boolean disableCallback) {
} | @Test
public void testTrackAppInstall() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
}... |
public static ExpansionServer create(ExpansionService service, String host, int port)
throws IOException {
return new ExpansionServer(service, host, port);
} | @Test
public void testNonEmptyFilesToStage() {
String[] args = {"--filesToStage=nonExistent1.jar,nonExistent2.jar"};
ExpansionService service = new ExpansionService(args);
assertThat(
service
.createPipeline(PipelineOptionsFactory.create())
.getOptions()
.as(Por... |
@Override
public void commitJob(JobContext originalContext) throws IOException {
commitJobs(Collections.singletonList(originalContext), Operation.OTHER);
} | @Test
public void testRetryTask() throws IOException {
HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter();
Table table = table(temp.getRoot().getPath(), false);
JobConf conf = jobConf(table, 2);
// Write records and abort the tasks
writeRecords(table.name(), 2, 0, false, true... |
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_STATE:
handleLiteralState(... | @Test
public void colon() 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, ":b"));
assertEquals(witnessList, ... |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldLoadStageArtifactPurgeSettingsFromXmlPartial() throws Exception {
String stageXmlPartial =
"""
<stage name="mingle" artifactCleanupProhibited="true">
<jobs>
<job name="functional">
... |
public String getCeTaskId() {
verifyInitialized();
return ceTaskId;
} | @Test
public void getCeTaskId_should_fail_if_not_initialized() {
assertThatThrownBy(() -> underTest.getCeTaskId())
.isInstanceOf(IllegalStateException.class);
} |
public static RateLimiterRegistry of(Configuration configuration, CompositeCustomizer<RateLimiterConfigCustomizer> customizer){
CommonRateLimiterConfigurationProperties rateLimiterProperties = CommonsConfigurationRateLimiterConfiguration.of(configuration);
Map<String, RateLimiterConfig> rateLimiterConfi... | @Test
public void testRateLimiterRegistryFromPropertiesFile() throws ConfigurationException {
Configuration config = CommonsConfigurationUtil.getConfiguration(PropertiesConfiguration.class, TestConstants.RESILIENCE_CONFIG_PROPERTIES_FILE_NAME);
RateLimiterRegistry registry = CommonsConfigurationRat... |
public static void checkDrivingLicenceMrz(String mrz) {
if (mrz.charAt(0) != 'D') {
throw new VerificationException("MRZ should start with D");
}
if (mrz.charAt(1) != '1') {
throw new VerificationException("Only BAP configuration is supported (1)");
}
if (... | @Test
public void checkDrivingLicenceMrzCountryWrong() {
assertThrows(VerificationException.class, () -> {
MrzUtils.checkDrivingLicenceMrz("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
});
} |
public static <T> List<List<T>> splitAvg(List<T> list, int limit) {
if (CollUtil.isEmpty(list)) {
return empty();
}
return (list instanceof RandomAccess)
? new RandomAccessAvgPartition<>(list, limit)
: new AvgPartition<>(list, limit);
} | @Test
public void splitAvgTest() {
List<List<Object>> lists = ListUtil.splitAvg(null, 3);
assertEquals(ListUtil.empty(), lists);
lists = ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 1);
assertEquals("[[1, 2, 3, 4]]", lists.toString());
lists = ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 2);
assertEquals(... |
@Override
public void handle(final RoutingContext routingContext) {
routingContext.addEndHandler(ar -> {
// After the response is complete, log results here.
final int status = routingContext.request().response().getStatusCode();
if (!loggingRateLimiter.shouldLog(logger, routingContext.request()... | @Test
public void shouldProduceLog() {
// Given:
when(response.getStatusCode()).thenReturn(200);
// When:
loggingHandler.handle(routingContext);
verify(routingContext).addEndHandler(endCallback.capture());
endCallback.getValue().handle(null);
// Then:
verify(logger).info(logStringCap... |
@CheckForNull
public Duration calculate(DefaultIssue issue) {
if (issue.isFromExternalRuleEngine()) {
return issue.effort();
}
Rule rule = ruleRepository.getByKey(issue.ruleKey());
DebtRemediationFunction fn = rule.getRemediationFunction();
if (fn != null) {
verifyEffortToFix(issue, fn... | @Test
public void linear_with_offset_function() {
double effortToFix = 3.0;
int coefficient = 2;
int offset = 5;
issue.setGap(effortToFix);
rule.setFunction(new DefaultDebtRemediationFunction(
DebtRemediationFunction.Type.LINEAR_OFFSET, coefficient + "min", offset + "min"));
assertThat(... |
public ModelAndView() {
} | @Test
public void testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
Assert.assertEquals(0, modelAndView.getModel().size());
} |
public boolean isUnknown() {
return Double.isInfinite(getRowCount())
|| Double.isInfinite(getRate())
|| Double.isInfinite(getWindow());
} | @Test
public void testKnownRel() {
String sql = " select * from ORDER_DETAILS1 ";
RelNode root = env.parseQuery(sql);
NodeStats nodeStats =
root.metadata(NodeStatsMetadata.class, root.getCluster().getMetadataQuery()).getNodeStats();
Assert.assertFalse(nodeStats.isUnknown());
} |
public List<String> toList(boolean trim) {
return toList((str) -> trim ? StrUtil.trim(str) : str);
} | @Test
public void splitByLengthTest(){
String text = "1234123412341234";
SplitIter splitIter = new SplitIter(text,
new LengthFinder(4),
Integer.MAX_VALUE,
false
);
final List<String> strings = splitIter.toList(false);
assertEquals(4, strings.size());
} |
public List<Service> getServices() {
synchronized (serviceList) {
return Collections.unmodifiableList(new ArrayList<>(serviceList));
}
} | @Test
public void testServiceStartup() {
ServiceManager serviceManager = new ServiceManager("ServiceManager");
// Add services
for (int i = 0; i < NUM_OF_SERVICES; i++) {
CompositeServiceImpl service = new CompositeServiceImpl(i);
if (i == FAILED_SERVICE_SEQ_NUMBER) {
service.setThrow... |
@Override
public V getNow(V valueIfAbsent) {
V value = super.getNow(valueIfAbsent);
return (deserialize && value instanceof Data) ? serializationService.toObject(value)
: value;
} | @Test
public void test_getNow_Data() {
Object value = "value";
DeserializingCompletableFuture<Object> future = new DeserializingCompletableFuture<>(serializationService, deserialize);
future.complete(serializationService.toData(value));
if (deserialize) {
assertEquals(v... |
public void extractTablesFromSelect(final SelectStatement selectStatement) {
if (selectStatement.getCombine().isPresent()) {
CombineSegment combineSegment = selectStatement.getCombine().get();
extractTablesFromSelect(combineSegment.getLeft().getSelect());
extractTablesFromSel... | @Test
void assertExtractJoinTableSegmentsFromSelect() {
JoinTableSegment joinTableSegment = new JoinTableSegment();
joinTableSegment.setLeft(new SimpleTableSegment(new TableNameSegment(16, 22, new IdentifierValue("t_order"))));
joinTableSegment.setRight(new SimpleTableSegment(new TableNameSe... |
@Override
public Serde<GenericKey> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> schemaRegistryClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
f... | @Test
public void shouldThrowOnNestedMapKeyColumn() {
// Given:
schema = PersistenceSchema.from(
ImmutableList.of(column(SqlTypes.struct()
.field("F", SqlTypes.map(SqlTypes.STRING, SqlTypes.STRING))
.build())),
SerdeFeatures.of()
);
// When:
final Exception... |
@Override
public BigDecimal getBigNumber( Object object ) throws KettleValueException {
Long timestampAsInteger = getInteger( object );
if ( null != timestampAsInteger ) {
return BigDecimal.valueOf( timestampAsInteger );
} else {
return null;
}
} | @Test
public void testConvertTimestampToBigNumber_DefaultMode() throws KettleValueException {
System.setProperty( Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE,
Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE_LEGACY );
ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp();
BigDecimal result... |
public List<String> getAllTableNames(String dbName) {
return get(tableNamesCache, dbName);
} | @Test
public void testGetAllTableNames() {
CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore(
metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false);
List<String> databaseNames = cachingHiveMetastore.getAllTableNames("xxx");
Assert.ass... |
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
throws KettleException {
try {
encoding = rep.getStepAttributeString( id_step, "encoding" );
nameSpace = rep.getStepAttributeString( id_step, "name_space" );
mainElement = rep.getStepAtt... | @SuppressWarnings( "ConstantConditions" )
@Test
public void testReadRep() throws Exception {
XMLOutputMeta xmlOutputMeta = new XMLOutputMeta();
Repository rep = mock( Repository.class );
IMetaStore metastore = mock( IMetaStore.class );
DatabaseMeta dbMeta = mock( DatabaseMeta.class );
String en... |
public static String getSimpleQuery(Map<String, Object> params, String script, boolean noteForm) {
String replaced = script;
Pattern pattern = noteForm ? VAR_NOTE_PTN : VAR_PTN;
Matcher match = pattern.matcher(replaced);
while (match.find()) {
int first = match.start();
if (!noteForm && f... | @Test
void testFormSubstitution() {
// test form substitution without new forms
String script = "INPUT=${input_form=}SELECTED=${select_form(Selection Form)=" +
",s_op1|s_op2|s_op3}\nCHECKED=${checkbox:checkbox_form=c_op1|c_op2,c_op1|c_op2|c_op3}";
Map<String, Object> params = new HashMap<>();
... |
public static HintValueContext extractHint(final String sql) {
if (!containsSQLHint(sql)) {
return new HintValueContext();
}
HintValueContext result = new HintValueContext();
int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
String hintKeyValueText = sql.su... | @Test
void assertSQLHintShardingDatabaseValueWithStringHintValue() {
HintValueContext actual = SQLHintUtils.extractHint("/* SHARDINGSPHERE_HINT: t_order.SHARDING_DATABASE_VALUE=a */");
assertThat(actual.getHintShardingDatabaseValue("t_order"), is(Collections.singletonList("a")));
} |
public double p90() {
return getLinearInterpolation(0.90);
} | @Test
public void testP90() {
HistogramData histogramData1 = HistogramData.linear(0, 0.2, 50);
histogramData1.record(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
assertThat(String.format("%.3f", histogramData1.p90()), equalTo("8.200"));
HistogramData histogramData2 = HistogramData.linear(0, 0.02, 50);
histogra... |
public static boolean equals(FlatRecordTraversalObjectNode left, FlatRecordTraversalObjectNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (!left.getSchema().getName().equals(right.ge... | @Test
public void shouldUseExactFlagToConsiderExtraFieldsInEquality_usingPrimitives() {
TypeState1 typeState1 = new TypeState1();
typeState1.longField = 1L;
typeState1.stringField = "A";
typeState1.doubleField = 1.0;
typeState1.basicIntField = 1;
typeState1.valueOnlyI... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(false);
}
boolean result = false;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
r... | @Test
void invokeListParamNull() {
FunctionTestUtil.assertResult(anyFunction.invoke((List) null), false);
} |
@Override
public double interpolate(double x1, double x2) {
int i = x1terp.search(x1);
int j = x2terp.search(x2);
double t = (x1-x1terp.xx[i])/(x1terp.xx[i+1]-x1terp.xx[i]);
double u = (x2-x2terp.xx[j])/(x2terp.xx[j+1]-x2terp.xx[j]);
return (1.-t)*(1.-u)*y[i][j] + t*(1.-u)*... | @Test
public void testInterpolate() {
System.out.println("interpolate");
double[] x1 = {1950, 1960, 1970, 1980, 1990};
double[] x2 = {10, 20, 30};
double[][] y = {
{150.697, 199.592, 187.625},
{179.323, 195.072, 250.287},
{203.212, 179.092, 322.767... |
public static void free(final DirectBuffer buffer)
{
if (null != buffer)
{
free(buffer.byteBuffer());
}
} | @Test
void freeIsANoOpIfDirectBufferContainsNonDirectByteBuffer()
{
final DirectBuffer buffer = mock(DirectBuffer.class);
final ByteBuffer byteBuffer = ByteBuffer.allocate(4);
when(buffer.byteBuffer()).thenReturn(byteBuffer);
BufferUtil.free(buffer);
byteBuffer.put(1, (... |
@Override
public Path resolveSibling(Path other) {
throw new UnsupportedOperationException();
} | @Test
public void testResolveSibling() {
assertEquals(
"gs://bucket/bar/moo",
GcsPath.fromUri("gs://bucket/bar/foo").resolveSibling("moo").toString());
assertEquals(
"gs://bucket/moo", GcsPath.fromUri("gs://bucket/foo").resolveSibling("moo").toString());
thrown.expect(UnsupportedOp... |
@Override
public String rpcType() {
return RpcTypeEnum.WEB_SOCKET.getName();
} | @Test
public void testRpcType() {
Assertions.assertEquals(webSocketShenyuContextDecorator.rpcType(), "websocket");
} |
@ConstantFunction(name = "subtract", argTypes = {BIGINT, BIGINT}, returnType = BIGINT, isMonotonic = true)
public static ConstantOperator subtractBigInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createBigint(Math.subtractExact(first.getBigint(), second.getBigint()));
} | @Test
public void subtractBigInt() {
assertEquals(0, ScalarOperatorFunctions.subtractBigInt(O_BI_100, O_BI_100).getBigint());
} |
@Override
public LogicalSchema getSchema() {
return schema;
} | @Test
public void shouldHaveFullyQualifiedSchema() {
// When:
final LogicalSchema schema = node.getSchema();
// Then:
assertThat(schema, is(REAL_SCHEMA.withPseudoAndKeyColsInValue(false)));
} |
@Override
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
} | @Test
public void testLoadXML() throws Exception {
SystemDataMeta systemDataMeta = new SystemDataMeta();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuil... |
public static DeploymentDescriptor merge(List<DeploymentDescriptor> descriptorHierarchy, MergeMode mode) {
if (descriptorHierarchy == null || descriptorHierarchy.isEmpty()) {
throw new IllegalArgumentException("Descriptor hierarchy list cannot be empty");
}
if (descriptorHierarchy.si... | @Test
public void testDeploymentDesciptorMergeMergeCollectionsAvoidDuplicates() {
DeploymentDescriptor primary = new DeploymentDescriptorImpl("org.jbpm.domain");
primary.getBuilder()
.addMarshalingStrategy(new ObjectModel("org.jbpm.test.CustomStrategy", new Object[]{"param2"}));
... |
@Override
public void updateMember(ShareGroupMember newMember) {
if (newMember == null) {
throw new IllegalArgumentException("newMember cannot be null.");
}
ShareGroupMember oldMember = members.put(newMember.memberId(), newMember);
maybeUpdateSubscribedTopicNamesAndGroup... | @Test
public void testUpdateSubscriptionMetadata() {
Uuid fooTopicId = Uuid.randomUuid();
Uuid barTopicId = Uuid.randomUuid();
Uuid zarTopicId = Uuid.randomUuid();
MetadataImage image = new MetadataImageBuilder()
.addTopic(fooTopicId, "foo", 1)
.addTopic(barT... |
@Udf
public List<Long> generateSeriesLong(
@UdfParameter(description = "The beginning of the series") final long start,
@UdfParameter(description = "Marks the end of the series (inclusive)") final long end
) {
return generateSeriesLong(start, end, end - start > 0 ? 1 : -1);
} | @Test
public void shouldComputeNegativeLongRange() {
final List<Long> range = rangeUdf.generateSeriesLong(9, 0);
assertThat(range, hasSize(10));
long val = 9;
for (final Long i : range) {
assertThat(val--, is(i));
}
} |
@Override
public Optional<HealthStatus> deflectorHealth(Collection<String> indices) {
if (indices.isEmpty()) {
return Optional.of(HealthStatus.Green);
}
final Map<String, String> aliasMapping = catApi.aliases();
final Set<String> mappedIndices = indices
.... | @Test
void testDeflectorHealth() {
when(catApi.aliases()).thenReturn(Map.of(
"foo_deflector", "foo_42",
"bar_deflector", "bar_17",
"baz_deflector", "baz_23"
));
when(catApi.indices()).thenReturn(List.of(
new IndexSummaryRespons... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{
PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name()));
if (userSession.hasSession() && userSession.isLoggedIn()
&& userSess... | @Test
public void doFilter_givenNotLoggedInAndRequired_dontRedirect() throws Exception {
PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession);
when(userSession.hasSession()).thenReturn(true);
when(userSession.isLoggedIn()).thenReturn(false);
when(configura... |
public LinkedList<LinkedList<Node>> computeWeaklyConnectedComponents(Graph graph, HashMap<Node, Integer> indices) {
int N = graph.getNodeCount();
//Keep track of which nodes have been seen
int[] color = new int[N];
Progress.start(progress, N);
int seenCount = 0;
Linke... | @Test
public void testNullGraphWeaklyConnectedComponents() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(5);
UndirectedGraph graph = graphModel.getUndirectedGraph();
Node n0 = graph.getNode("0");
Node n1 = graph.getNode("1");
Node n2 = graph.getNode("2"... |
@Override
public Class<? extends MaxLabeledStorageBuilder> builder() {
return MaxLabeledStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1);
function.calculate();
StorageBuilder<MaxLabeledFunction> storageBuilder = function.builder().newInstance();
... |
public Record convert(final AbstractWALEvent event) {
if (filter(event)) {
return createPlaceholderRecord(event);
}
if (!(event instanceof AbstractRowEvent)) {
return createPlaceholderRecord(event);
}
PipelineTableMetaData tableMetaData = getPipelineTableM... | @Test
void assertConvertPlaceholderEvent() {
Record record = walEventConverter.convert(new PlaceholderEvent());
assertThat(record, instanceOf(PlaceholderRecord.class));
} |
@Override
public ReadWriteBuffer onCall(Command command, ReadWriteBuffer parameter) throws IOException {
Path p = null;
if (null == command) {
return null;
}
if (command.equals(GET_OUTPUT_PATH)) {
p = output.getOutputFileForWrite(-1);
} else if (command.equals(GET_OUTPUT_INDEX... | @Test
public void testOnCall() throws IOException {
this.handler = new NativeCollectorOnlyHandler(taskContext, nativeHandler, pusher, combiner);
boolean thrown = false;
try {
handler.onCall(new Command(-1), null);
} catch(final IOException e) {
thrown = true;
}
Assert.assertTrue("e... |
public void add(String element) {
addAsync(element).toCompletableFuture().join();
} | @Test
@Timeout(5)
public void testEventuallyExpires() throws InterruptedException {
final FaultTolerantRedisCluster redisCluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
final CardinalityEstimator estimator = new CardinalityEstimator(redisCluster, "test", Duration.ofMillis(100));
estimator.add("1");... |
@ConstantFunction(name = "timediff", argTypes = {DATETIME, DATETIME}, returnType = TIME, isMonotonic = true)
public static ConstantOperator timeDiff(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createTime(Duration.between(second.getDatetime(), first.getDatetime()).getSeconds())... | @Test
public void timeDiff() {
assertEquals(-2534400.0, ScalarOperatorFunctions.timeDiff(O_DT_20101102_183010, O_DT_20101202_023010).getTime(),
1);
} |
@Override
public int run(String[] argv) {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-safemode".equals(cmd)) {
if (argv.length != 2) ... | @Test
public void testRefreshProxyUser() throws Exception {
Path dirPath = new Path("/testdir1");
Path subDirPath = new Path("/testdir1/subdir1");
UserGroupInformation loginUserUgi = UserGroupInformation.getLoginUser();
String proxyUser = "fakeuser";
String realUser = loginUserUgi.getShortUserNam... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testExplainAnalyzeFormatJson()
{
analyze("EXPLAIN ANALYZE (format JSON) SELECT * FROM t1");
} |
@Override
public Set<String> getAssociatedRoles() {
Subject subject = org.apache.shiro.SecurityUtils.getSubject();
Set<String> roles = new HashSet<>();
Map<String, String> allRoles = null;
if (subject.isAuthenticated()) {
Collection<Realm> realmsList = getRealmsList();
for (Realm realm : ... | @Test
void testKnoxGetRoles() {
setupPrincipalName("test");
KnoxJwtRealm realm = spy(new KnoxJwtRealm());
LifecycleUtils.init(realm);
Set<String> testRoles = new HashSet<String>();
testRoles.add("role1");
testRoles.add("role2");
when(realm.mapGroupPrincipals("test")).thenReturn(testRoles... |
@Nonnull
@Override
public Result addChunk(ByteBuf buffer) {
final byte[] readable = new byte[buffer.readableBytes()];
buffer.readBytes(readable, buffer.readerIndex(), buffer.readableBytes());
final GELFMessage msg = new GELFMessage(readable);
final ByteBuf aggregatedBuffer;
... | @Test
public void addSingleChunk() {
final ByteBuf[] singleChunk = createChunkedMessage(512, 1024);
final CodecAggregator.Result result = aggregator.addChunk(singleChunk[0]);
assertNotNull("message should be complete", result.getMessage());
assertEquals(1, counterValueNamed(metric... |
@VisibleForTesting
S3Client getS3Client() {
return this.s3Client.get();
} | @Test
public void testGetPathStyleAccessEnabledWithS3Options() throws URISyntaxException {
S3FileSystem s3FileSystem = new S3FileSystem(s3OptionsWithPathStyleAccessEnabled());
URL s3Url =
s3FileSystem
.getS3Client()
.utilities()
.getUrl(GetUrlRequest.builder().bucke... |
@Override
public Database getDb(String dbName) {
org.apache.hadoop.hive.metastore.api.Database db = client.getDb(dbName);
return HiveMetastoreApiConverter.toDatabase(db, dbName);
} | @Test
public void testGetDb() {
HiveMetaClient client = new MockedHiveMetaClient();
HiveMetastore metastore = new HiveMetastore(client, "xxx", MetastoreType.HMS);
Database database = metastore.getDb("db1");
Assert.assertEquals("db1", database.getFullName());
try {
... |
@ScalarOperator(EQUAL)
@SqlType(StandardTypes.BOOLEAN)
@SqlNullable
public static Boolean equal(@SqlType(StandardTypes.BIGINT) long left, @SqlType(StandardTypes.BIGINT) long right)
{
return left == right;
} | @Test
public void testEqual()
{
assertFunction("100000000037 = 100000000037", BOOLEAN, true);
assertFunction("37 = 100000000017", BOOLEAN, false);
assertFunction("100000000017 = 37", BOOLEAN, false);
assertFunction("100000000017 = 100000000017", BOOLEAN, true);
} |
static boolean calculateActualParam(NamedParameter np, List<String> names, Object[] actualParams,
boolean isVariableParameters, String variableParamPrefix,
List<Object> variableParams) {
logger.trace("calculateActualParam {} {} {} {... | @Test
void calculateActualParam() {
// populate by NamedParameter value
NamedParameter np = new NamedParameter("n", BigDecimal.valueOf(1.5));
List<String> names = Collections.singletonList("n");
Object[] actualParams = new Object[1];
boolean isVariableParameters = false;
... |
@Override
public void close() throws Exception {
Exception exception = null;
for (CompletableFuture<CloseableFnDataReceiver<BeamFnApi.Elements>> receiver :
ImmutableList.copyOf(receivers.values())) {
// Cancel any observer waiting for the client to complete. If the receiver has already been
... | @Test
public void testClose() throws Exception {
Collection<BeamFnApi.Elements> outboundValues = new ArrayList<>();
Collection<Throwable> errorWasReturned = new ArrayList<>();
AtomicBoolean wasClosed = new AtomicBoolean();
final BeamFnDataGrpcMultiplexer multiplexer =
new BeamFnDataGrpcMultipl... |
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public ErrorWebExceptionHandler errorWebExceptionHandler() {
return new GlobalErrorHandler();
} | @Test
public void testErrorWebExceptionHandler() {
applicationContextRunner.run(context -> {
ErrorWebExceptionHandler globalErrorHandler = context.getBean("errorWebExceptionHandler", ErrorWebExceptionHandler.class);
assertNotNull(globalErrorHandler);
});
} |
public static Schema reassignOrRefreshIds(Schema schema, Schema idSourceSchema) {
return reassignOrRefreshIds(schema, idSourceSchema, true);
} | @Test
public void testReassignOrRefreshIds() {
Schema schema =
new Schema(
Lists.newArrayList(
required(10, "a", Types.IntegerType.get()),
required(11, "c", Types.IntegerType.get()),
required(12, "B", Types.IntegerType.get())),
Sets.n... |
@POST
@Path(KMSRESTConstants.KEYS_RESOURCE)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8)
@SuppressWarnings("unchecked")
public Response createKey(Map jsonKey) throws Exception {
try{
LOG.trace("Entering createKey Method.");
KMSWebApp.get... | @Test
public void testKMSAuthFailureRetry() throws Exception {
Configuration conf = new Configuration();
conf.set("hadoop.security.authentication", "kerberos");
final File testDir = getTestDir();
conf = createBaseKMSConf(testDir, conf);
conf.set("hadoop.kms.authentication.kerberos.keytab",
... |
public Flux<TopicMessageEventDTO> loadMessages(KafkaCluster cluster,
String topic,
ConsumerPosition consumerPosition,
@Nullable String containsStringFilter,
... | @Test
void loadMessagesReturnsExceptionWhenTopicNotFound() {
StepVerifier.create(messagesService
.loadMessages(cluster, NON_EXISTING_TOPIC,
new ConsumerPosition(PollingModeDTO.TAILING, NON_EXISTING_TOPIC, List.of(), null, null),
null, null, 1, "String", "String"))
... |
@NotNull
@Override
public List<InetAddress> lookup(@NotNull String host) throws UnknownHostException {
InetAddress address = InetAddress.getByName(host);
if (configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY).orElse(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE)
&& (address.isLoopbackAddress() || addr... | @Test
public void lookup_fail_on_ipv6_local_case_insensitive() throws UnknownHostException, SocketException {
Optional<InetAddress> inet6Address = Collections.list(NetworkInterface.getNetworkInterfaces())
.stream()
.flatMap(ni -> Collections.list(ni.getInetAddresses()).stream())
.filter(i -> i i... |
FleetControllerOptions getOptions() { return options; } | @Test
void testSimple() throws Exception {
ClusterController controller = new ClusterController();
StorDistributionConfig.Builder distributionConfig = new StorDistributionConfig.Builder();
StorDistributionConfig.Group.Builder group = new StorDistributionConfig.Group.Builder();
group.... |
@Override
public Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Optional<AthenzPrincipal> certificatePrincipal = getClientCertificate(request)
.map(AthenzIdentities::from)
.map(AthenzPrincipal::new);
if (certificatePrincipal.... | @Test
void certificate_is_accepted() {
DiscFilterRequest request = FilterTestUtils.newRequestBuilder().withClientCertificate(CERTIFICATE).build();
ResponseHandlerMock responseHandler = new ResponseHandlerMock();
AthenzPrincipalFilter filter = createFilter(false);
filter.filter(requ... |
@Override
public ProcessingResult process(ReplicationTask task) {
try {
EurekaHttpResponse<?> httpResponse = task.execute();
int statusCode = httpResponse.getStatusCode();
Object entity = httpResponse.getEntity();
if (logger.isDebugEnabled()) {
... | @Test
public void testNonBatchableTaskExecution() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(200).build();
ProcessingResult status = replicationTaskProcessor.process(task);
assertThat(status, is(ProcessingResu... |
public synchronized ClientInstanceIds clientInstanceIds(final Duration timeout) {
if (timeout.isNegative()) {
throw new IllegalArgumentException("The timeout cannot be negative.");
}
if (state().hasNotStarted()) {
throw new IllegalStateException("KafkaStreams has not been... | @Test
public void shouldThrowOnClientInstanceIdsWithNegativeTimeout() {
prepareStreams();
prepareStreamThread(streamThreadOne, 1);
prepareStreamThread(streamThreadTwo, 2);
try (final KafkaStreams streams = new KafkaStreams(getBuilderWithSource().build(), props, supplier, time)) {
... |
public List<Attendee> availableAttendeesOf(List<Schedule> schedules) {
Map<Attendee, Long> groupAttendeeByScheduleCount = schedules.stream()
.filter(this::isScheduleWithinDateTimeRange)
.collect(groupingBy(Schedule::getAttendee, counting()));
long confirmedTimeSlotCount ... | @DisplayName("ํ์ ๋ ์ฝ์์ ๋ฒ์์ ํฌํจ๋๋ ์ค์ผ์ค๋ค ์ค ์ฐธ์ ๊ฐ๋ฅํ ์ฐธ์์๋ค์ ๋ฐํํ๋ค.")
@Test
void availableAttendeesOf() {
Meeting meeting = MeetingFixture.MOVIE.create();
Attendee attendee1 = AttendeeFixture.GUEST_MARK.create(meeting);
Attendee attendee2 = AttendeeFixture.HOST_JAZZ.create(meeting);
LocalDa... |
@Override
public String buildContext() {
final ResourceDO after = (ResourceDO) getAfter();
if (Objects.isNull(getBefore())) {
return String.format("the resource [%s] is %s", after.getTitle(), StringUtils.lowerCase(getType().getType().toString()));
}
return String.format("... | @Test
public void resourceDeleteBuildContextTest() {
ResourceChangedEvent resourceDeleteEvent = new ResourceChangedEvent(after, after, EventTypeEnum.RESOURCE_DELETE, "test-operator");
String typeStr = StringUtils.lowerCase(EventTypeEnum.RESOURCE_DELETE.getType().toString());
String context ... |
@Override
public GetResourceProfileResponse getResourceProfile(
GetResourceProfileRequest request) throws YarnException, IOException {
if (request == null || request.getProfileName() == null) {
routerMetrics.incrGetResourceProfileFailedRetrieved();
String msg = "Missing getResourceProfile reques... | @Test
public void testGetResourceProfile() throws Exception {
LOG.info("Test FederationClientInterceptor : Get Resource Profile request.");
// null request
LambdaTestUtils.intercept(YarnException.class,
"Missing getResourceProfile request or profileName.",
() -> interceptor.getResourcePro... |
UuidGenerator loadUuidGenerator() {
Class<? extends UuidGenerator> objectFactoryClass = options.getUuidGeneratorClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<UuidGenerator> loader = ServiceLoader.load(UuidGenerator.class, classLoader);
if (objectFactoryClass... | @Test
void test_case_13() {
Options options = () -> null;
UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader(
() -> new ServiceLoaderTestClassLoader(UuidGenerator.class,
IncrementingUuidGenerator.class),
options);
assertThat(loader.load... |
public static String loadText(InputStream in) throws IOException {
return new String(in.readAllBytes());
} | @Test
public void testFileToString() throws Exception {
File file = ResourceUtils.getResourceAsFile("filecontent/a.txt");
assertEquals("dk19i21)@+#(OR", PackageHelper.loadText(file));
} |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
if(proxy.isSupported(source, target)) {
return proxy.copy(source, target, status, callback, listener);
... | @Test
public void testCopyToEncryptedDataRoom() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room1 = new SDSDirectoryFeature(session, nodeid).createRoom(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.di... |
@Override
@Nonnull
public <T> Future<T> submit(@Nonnull Callable<T> task) {
throwRejectedExecutionExceptionIfShutdown();
try {
T result = task.call();
return new CompletedFuture<>(result, null);
} catch (Exception e) {
return new CompletedFuture<>(nu... | @Test
void testSubmitCallableWithNoopShutdown() {
final CompletableFuture<Thread> future = new CompletableFuture<>();
testWithNoopShutdown(testInstance -> testInstance.submit(callableFromFuture(future)));
assertThat(future).isCompletedWithValue(Thread.currentThread());
} |
public static TimeUnit getMetricsRateUnit(Map<String, Object> daemonConf) {
return getTimeUnitForConfig(daemonConf, Config.STORM_DAEMON_METRICS_REPORTER_PLUGIN_RATE_UNIT);
} | @Test
public void getMetricsRateUnit() {
Map<String, Object> daemonConf = new HashMap<>();
assertNull(MetricsUtils.getMetricsRateUnit(daemonConf));
daemonConf.put(Config.STORM_DAEMON_METRICS_REPORTER_PLUGIN_RATE_UNIT, "SECONDS");
assertEquals(TimeUnit.SECONDS, MetricsUtils.getMetri... |
public Set<Long> getSkipTokens() {
return this.skipTokens;
} | @Test
public void tesSkipTokens() {
Set<Long> skipTokens = embedder.getSkipTokens();
assertTrue(skipTokens.contains(999L));
assertTrue(skipTokens.contains(1000L));
assertTrue(skipTokens.contains(1001L));
assertTrue(skipTokens.contains(1002L));
assertTrue(skipTokens.co... |
@Override
public void updateSubnet(Subnet osSubnet) {
checkNotNull(osSubnet, ERR_NULL_SUBNET);
checkArgument(!Strings.isNullOrEmpty(osSubnet.getId()), ERR_NULL_SUBNET_ID);
checkArgument(!Strings.isNullOrEmpty(osSubnet.getNetworkId()), ERR_NULL_SUBNET_NET_ID);
checkArgument(!Strings.i... | @Test(expected = NullPointerException.class)
public void testUpdateSubnetWithNull() {
target.updateSubnet(null);
} |
@Override
public PTransform<PCollection<Row>, PCollectionTuple> buildTransform(
FileWriteSchemaTransformConfiguration configuration, Schema schema) {
return new PTransform<PCollection<Row>, PCollectionTuple>() {
@Override
public PCollectionTuple expand(PCollection<Row> input) {
FileWrit... | @Test
public void timeContainingSchemaWithListRemovedShouldWriteCSV() {
String prefix =
folder(TimeContaining.class, "timeContainingSchemaWithListRemovedShouldWriteCSV");
String validField = "instant";
PCollection<Row> input =
writePipeline.apply(
Create.of(DATA.timeContainingR... |
public static Configuration unix() {
return UnixHolder.UNIX;
} | @Test
public void testDefaultUnixConfiguration() {
Configuration config = Configuration.unix();
assertThat(config.pathType).isEqualTo(PathType.unix());
assertThat(config.roots).containsExactly("/");
assertThat(config.workingDirectory).isEqualTo("/work");
assertThat(config.nameCanonicalNormalizati... |
void importPlaylistItems(
List<MusicPlaylistItem> playlistItems,
IdempotentImportExecutor executor,
UUID jobId,
TokensAndUrlAuthData authData)
throws Exception {
if (playlistItems != null && !playlistItems.isEmpty()) {
Map<String, List<MusicPlaylistItem>> playlistItemsByPlaylist ... | @Test
public void importPlaylistItemsCreatePlaylistFailure() throws Exception {
MusicPlaylistItem playlistItem1 =
new MusicPlaylistItem(
new MusicRecording(
"item1_isrc", null, 180000L, new MusicRelease("r1_icpn", null, null), null, false),
"p1_id",
1);
... |
public static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName) {
Preconditions.checkNotNull(value, "Property '" + propertyName + "' cannot be null");
Preconditions.checkArgument(
!value.trim().isEmpty(), "Property '" + propertyName + "' cannot be an empty string");
} | @Test
public void testCheckNotEmpty_collectionPass() {
Validator.checkNotNullAndNotEmpty(ImmutableList.of("value"), "ignored");
// pass
} |
public String getFilepath() {
return filepath;
} | @Test
public void testConstructorMessageAndFilepath() {
try {
throw new KettleFileNotFoundException( errorMessage, filepath );
} catch ( KettleFileNotFoundException e ) {
assertEquals( null, e.getCause() );
assertTrue( e.getMessage().contains( errorMessage ) );
assertEquals( filepath, ... |
public RepeatRegistrationException(String message) {
super(message);
} | @Test
void testRepeatRegistrationException() {
assertAll(
() -> assertThrowsExactly(RepeatRegistrationException.class, () -> {
throw new RepeatRegistrationException("error");
}),
() -> assertThrowsExactly(RepeatRegistrationException.class, ... |
public static Packet ensureUniqueAndStableStanzaID( final Packet packet, final JID self )
{
if ( !JiveGlobals.getBooleanProperty( "xmpp.sid.enabled", true ) )
{
return packet;
}
if ( packet instanceof IQ && !JiveGlobals.getBooleanProperty( "xmpp.sid.iq.enabled", false ) ... | @Test
public void testGeneratesStanzaIDElement() throws Exception
{
// Setup fixture.
final Packet input = new Message();
final JID self = new JID( "foobar" );
// Execute system under test.
final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );
... |
public String getType() {
return type;
} | @Test
void getType_shouldReturnTypePassedInConstructor() {
Notification notification = new Notification("type");
assertThat(notification.getType()).isEqualTo("type");
} |
public EndpointResponse streamQuery(
final KsqlSecurityContext securityContext,
final KsqlRequest request,
final CompletableFuture<Void> connectionClosedFuture,
final Optional<Boolean> isInternalRequest,
final MetricsCallbackHolder metricsCallbackHolder,
final Context context
) {
... | @Test
public void shouldThrowOnHandleStatementIfNotConfigured() {
// Given:
testResource = new StreamedQueryResource(
mockKsqlEngine,
ksqlRestConfig,
mockStatementParser,
commandQueue,
DISCONNECT_CHECK_INTERVAL,
COMMAND_QUEUE_CATCHUP_TIMOEUT,
activenessR... |
@Override
public ObjectName createName(String type, String domain, String name) {
try {
ObjectName objectName;
Hashtable<String, String> properties = new Hashtable<>();
properties.put("name", name);
properties.put("type", type);
objectName = new O... | @Test
public void createsObjectNameWithNameAsKeyPropertyName() {
DefaultObjectNameFactory f = new DefaultObjectNameFactory();
ObjectName on = f.createName("type", "com.domain", "something.with.dots");
assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots");
} |
public static String canonicalNameToJvmName(String canonicalName) {
boolean isArray = canonicalName.endsWith("[]");
if (isArray) {
String t = ""; // ่ฎกๆฐ๏ผ็ไธๅ ็ปดๆฐ็ป
while (isArray) {
canonicalName = canonicalName.substring(0, canonicalName.length() - 2);
... | @Test
public void canonicalNameToJvmName() throws Exception {
} |
public CounterProducer(MetricsEndpoint endpoint) {
super(endpoint);
} | @Test
public void testCounterProducer() {
assertThat(producer.getEndpoint().equals(endpoint), is(true));
} |
public static boolean isOriginalOrder(List<Integer> joinOrder)
{
for (int i = 0; i < joinOrder.size(); i++) {
if (joinOrder.get(i) != i) {
return false;
}
}
return true;
} | @Test
public void testIsOriginalOrder()
{
assertTrue(isOriginalOrder(ImmutableList.of(0, 1, 2, 3, 4)));
assertFalse(isOriginalOrder(ImmutableList.of(0, 2, 1, 3, 4)));
} |
public String azimuth2compassPoint(double azimuth) {
String cp;
double slice = 360.0 / 16;
if (azimuth < slice) {
cp = "N";
} else if (azimuth < slice * 3) {
cp = "NE";
} else if (azimuth < slice * 5) {
cp = "E";
} else if (azimuth < s... | @Test
public void testAzimuthCompassPoint() {
assertEquals("S", AC.azimuth2compassPoint(199));
} |
public GrpcChannel acquireChannel(GrpcNetworkGroup networkGroup,
GrpcServerAddress serverAddress, AlluxioConfiguration conf, boolean alwaysEnableTLS) {
GrpcChannelKey channelKey = getChannelKey(networkGroup, serverAddress, conf);
CountingReference<ManagedChannel> channelRef =
mChannels.compute(cha... | @Test
public void testRoundRobin() throws Exception {
int streamingGroupSize =
sConf.getInt(PropertyKey.USER_NETWORK_STREAMING_MAX_CONNECTIONS);
try (CloseableTestServer server = createServer()) {
List<GrpcServerAddress> addresses = new ArrayList<>(streamingGroupSize);
// Create channel k... |
@ApiOperation(value = "Parse a processing pipeline without saving it")
@POST
@Path("/parse")
@NoAuditEvent("only used to parse a pipeline, no changes made in the system")
public PipelineSource parse(@ApiParam(name = "pipeline", required = true) @NotNull PipelineSource pipelineSource) throws ParseExcepti... | @Test
public void shouldParseAPipelineSuccessfully() {
final PipelineSource pipelineSource = PipelineSource.builder()
.source("pipeline \"Graylog Git Pipline\"\nstage 0 match either\n" +
"rule \"geo loc of dev\"\nrule \"open source dev\"\nend")
.stages... |
@Override
public CompletableFuture<JobID> submitJob(@Nonnull JobGraph jobGraph) {
CompletableFuture<java.nio.file.Path> jobGraphFileFuture =
CompletableFuture.supplyAsync(
() -> {
try {
final java.nio.file.Pa... | @Test
@Timeout(value = 120_000, unit = TimeUnit.MILLISECONDS)
void testJobSubmissionWithUserArtifact(@TempDir java.nio.file.Path temporaryPath)
throws Exception {
try (final TestRestServerEndpoint restServerEndpoint =
createRestServerEndpoint(new TestJobSubmitHandler())) {
... |
@Override
public void getErrors(ErrorCollection errors, String parentLocation) {
String location = this.getLocation(parentLocation);
errors.checkMissing(location, "spec", spec);
} | @Test
public void shouldDeserializeFromAPILikeObject() {
String json = """
{
"spec": "0 0 22 ? * MON-FRI",
"only_on_changes": true
}""";
CRTimer deserializedValue = gson.fromJson(json,CRTimer.class);
assertThat(deseri... |
@Override
public int fieldMetaIndex( int index ) {
return ( index >= fieldsCount || index < 0 ) ? FieldsMapping.FIELD_DOES_NOT_EXIST : index;
} | @Test
public void fieldMetaIndex() {
assertEquals( 1, fieldsMapping.fieldMetaIndex( 1 ) );
} |
@GetSize
public double getSize(
@Element SubscriptionPartition subscriptionPartition,
@Restriction OffsetByteRange restriction) {
if (restriction.getRange().getTo() != Long.MAX_VALUE) {
return restriction.getByteCount();
}
return newTracker(subscriptionPartition, restriction).getProgress... | @Test
public void getProgressBoundedReturnsBytes() {
assertTrue(
DoubleMath.fuzzyEquals(
123.0,
sdf.getSize(PARTITION, OffsetByteRange.of(new OffsetRange(87, 8000), 123)),
.0001));
verifyNoInteractions(tracker);
} |
static Properties loadPropertiesFile(File homeDir) {
Properties p = new Properties();
File propsFile = new File(new File(homeDir, "conf"), "sonar.properties");
if (propsFile.exists()) {
try (Reader reader = new InputStreamReader(new FileInputStream(propsFile), UTF_8)) {
p.load(reader);
... | @Test
public void loadPropertiesFile_fails_with_ISE_if_sonar_properties_not_in_conf_dir() throws IOException {
File homeDir = temporaryFolder.newFolder();
assertThatThrownBy(() -> Shutdowner.loadPropertiesFile(homeDir))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Configuration file no... |
@Override
public void open(Configuration parameters) throws Exception {
this.rateLimiterTriggeredCounter =
getRuntimeContext()
.getMetricGroup()
.addGroup(
TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT)
.counter(TableMain... | @Test
void testDataFileCount() throws Exception {
TriggerManager manager =
manager(
sql.tableLoader(TABLE_NAME), new TriggerEvaluator.Builder().dataFileCount(3).build());
try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness =
harness(manager)) {
... |
@Override
public JavaKeyStore load(SecureConfig config) {
if (!exists(config)) {
throw new SecretStoreException.LoadException(
String.format("Can not find Logstash keystore at %s. Please verify this file exists and is a valid Logstash keystore.",
c... | @Test
public void testNoPathDefined() {
assertThrows(SecretStoreException.LoadException.class, () -> {
new JavaKeyStore().load(new SecureConfig());
});
} |
public RowExpression extract(PlanNode node)
{
return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null);
} | @Test
public void testTopN()
{
PlanNode node = new TopNNode(
Optional.empty(),
newId(),
filter(baseTableScan,
and(
equals(AV, BV),
equals(BV, CV),
... |
public static String encodeBytes(byte[] bytes) {
return Base64.encodeToString(bytes, false);
} | @Test
public void testBytes() {
byte[] bytes = { 1, 100, 127, 0, 60, 15, -128, -1, 14, -55 };
String bytesString = Protocol.encodeBytes(bytes);
byte[] bytes2 = Base64.decode(bytesString);
assertArrayEquals(bytes, bytes2);
Gateway g = new Gateway(null);
ReturnObject rObject = g.getReturnObject(bytes);
as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.