focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Asn1Property(tagNo = 0x30, converter = DigestsConverter.class)
public Map<Integer, byte[]> getDigests() {
return digests;
} | @Test
public void readPcaRvigCms() throws Exception {
final LdsSecurityObject ldsSecurityObject = mapper.read(
readFromCms("pca-rvig"), LdsSecurityObject.class);
assertEquals(ImmutableSet.of(14), ldsSecurityObject.getDigests().keySet());
} |
@Override
@SuppressWarnings("DuplicatedCode")
public Integer cleanAccessLog(Integer exceedDay, Integer deleteLimit) {
int count = 0;
LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
// 循环删除,直到没有满足条件的数据
for (int i = 0; i < Short.MAX_VALUE; i++) {
in... | @Test
public void testCleanJobLog() {
// mock 数据
ApiAccessLogDO log01 = randomPojo(ApiAccessLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3))));
apiAccessLogMapper.insert(log01);
ApiAccessLogDO log02 = randomPojo(ApiAccessLogDO.class, o -> o.setCreateTime(addTime(Duratio... |
@LiteralParameters("x")
@ScalarOperator(BETWEEN)
@SqlType(StandardTypes.BOOLEAN)
public static boolean between(@SqlType("varchar(x)") Slice value, @SqlType("varchar(x)") Slice min, @SqlType("varchar(x)") Slice max)
{
return min.compareTo(value) <= 0 && value.compareTo(max) <= 0;
} | @Test
public void testBetween()
{
assertFunction("'foo' BETWEEN 'foo' AND 'foo'", BOOLEAN, true);
assertFunction("'foo' BETWEEN 'foo' AND 'bar'", BOOLEAN, false);
assertFunction("'foo' BETWEEN 'bar' AND 'foo'", BOOLEAN, true);
assertFunction("'foo' BETWEEN 'bar' AND 'bar'", BOOL... |
public static boolean checkpointsMatch(
Collection<CompletedCheckpoint> first, Collection<CompletedCheckpoint> second) {
if (first.size() != second.size()) {
return false;
}
List<Tuple2<Long, JobID>> firstInterestingFields = new ArrayList<>(first.size());
for (C... | @Test
void testCompareCheckpointsWithDifferentOrder() {
CompletedCheckpoint checkpoint1 =
new CompletedCheckpoint(
new JobID(),
0,
0,
1,
new HashMap<>(),
... |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testEqualToNull() {
String col = "col";
NamedReference namedReference = FieldReference.apply(col);
LiteralValue value = new LiteralValue(null, DataTypes.IntegerType);
org.apache.spark.sql.connector.expressions.Expression[] attrAndValue =
new org.apache.spark.sql.connector.ex... |
@Override
protected Class<? extends HttpApiV2ProxyRequest> getRequestClass() {
return HttpApiV2ProxyRequest.class;
} | @Test
void reflection_getRequestClass_returnsCorrectType() {
assertSame(HttpApiV2ProxyRequest.class, reader.getRequestClass());
} |
public CloseableHttpClient build(String name) {
final CloseableHttpClient client = buildWithDefaultRequestConfiguration(name).getClient();
// If the environment is present, we tie the client with the server lifecycle
if (environment != null) {
environment.lifecycle().manage(new Manag... | @Test
void buildWithAnotherBuilder() {
CustomBuilder builder = new CustomBuilder(new MetricRegistry(), anotherApacheBuilder);
builder.build("test");
assertThat(anotherApacheBuilder).extracting("requestExec")
.isInstanceOf(CustomRequestExecutor.class);
} |
@Override
public Mono<GetExpiringProfileKeyCredentialResponse> getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (t... | @Test
void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
final ClientZkProfileOperations clientZ... |
@VisibleForTesting
public static RemoteIterator<S3AFileStatus> toProvidedFileStatusIterator(
S3AFileStatus[] fileStatuses) {
return filteringRemoteIterator(
remoteIteratorFromArray(fileStatuses),
Listing.ACCEPT_ALL_BUT_S3N::accept);
} | @Test
public void testProvidedFileStatusIteratorEnd() throws Exception {
S3AFileStatus s3aStatus = new S3AFileStatus(
100, 0, new Path("s3a://blah/blah"),
8192, null, null, null);
S3AFileStatus[] statuses = {
s3aStatus
};
RemoteIterator<S3AFileStatus> it = Listing.toProvidedFi... |
public static RepositoryMetadataStore getInstance() {
return repositoryMetadataStore;
} | @Test
public void shouldReturnNullForMetadataIfPluginIdIsNotProvided() {
assertNull(RepositoryMetadataStore.getInstance().getMetadata(""));
} |
@Override
@Deprecated
public <KR, VR> KStream<KR, VR> transform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, KeyValue<KR, VR>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(transformerSuppl... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNamesOnTransformWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.transform(transformerSupplier, Named.as("transform"), (String[]) null));
... |
public void unregisterStream(String id) {
removeGrantsForTarget(grnRegistry.newGRN(GRNTypes.STREAM, id));
} | @Test
void unregisterStream() {
entityOwnershipService.unregisterStream("123");
assertGrantRemoval(GRNTypes.STREAM, "123");
} |
public static String substVars(String val, PropertyContainer pc1) throws ScanException {
return substVars(val, pc1, null);
} | @Test
public void defaultValueReferencingAVariable() throws ScanException {
context.putProperty("v1", "k1");
String result = OptionHelper.substVars("${undef:-${v1}}", context);
assertEquals("k1", result);
} |
@Override
public void debug(String msg) {
logger.debug(msg);
} | @Test
void testDebugWithException() {
Exception exception = new Exception();
jobRunrDashboardLogger.debug("Debug", exception);
verify(slfLogger).debug("Debug", exception);
} |
public AccessPrivilege getAccessPrivilege(InetAddress addr) {
return getAccessPrivilege(addr.getHostAddress(),
addr.getCanonicalHostName());
} | @Test
public void testCidrLongRW() {
NfsExports matcher = new NfsExports(CacheSize, ExpirationPeriod,
"192.168.0.0/255.255.252.0 rw");
Assert.assertEquals(AccessPrivilege.READ_WRITE,
matcher.getAccessPrivilege(address1, hostname1));
Assert.assertEquals(AccessPrivilege.NONE,
matche... |
public String queryParam(String queryParamName) {
return optionalQueryParam(queryParamName).orElse(null);
} | @Test
void testRequestUrlQueryParam() {
RequestUrl requestUrl = new MatchUrl("/api/jobs/enqueued?present=2").toRequestUrl("/api/jobs/:state");
assertThat(requestUrl.queryParam("present")).isEqualTo("2");
} |
@Override
public AwsProxyResponse handle(Throwable ex) {
log.error("Called exception handler for:", ex);
// adding a print stack trace in case we have no appender or we are running inside SAM local, where need the
// output to go to the stderr.
ex.printStackTrace();
if (ex i... | @Test
void streamHandle_InvalidResponseObjectException_502State()
throws IOException {
ByteArrayOutputStream respStream = new ByteArrayOutputStream();
exceptionHandler.handle(new InvalidResponseObjectException(INVALID_RESPONSE_MESSAGE, null), respStream);
assertNotNull(respStrea... |
public Optional<ResT> waitForComplete(long timeoutMs) throws IOException {
if (mCompleted || mCanceled) {
return Optional.empty();
}
ResT prevResponse;
ResT response = null;
do {
// wait until inbound stream is closed from server.
prevResponse = response;
response = receive(t... | @Test
public void waitForComplete() throws Exception {
WriteResponse[] responses = Stream.generate(() -> WriteResponse.newBuilder().build())
.limit(BUFFER_SIZE * 2).toArray(WriteResponse[]::new);
EXECUTOR.submit(() -> {
for (WriteResponse response : responses) {
mResponseObserver.onNext... |
public String getValueForDisplay(){
return getValue();
} | @Test
public void shouldReturnValueForDisplay() {
ParamConfig paramConfig = new ParamConfig("foo", "bar");
assertThat(paramConfig.getValueForDisplay(), is("bar"));
} |
@Override
public <T> T get(String key, Class<T> type) {
ClusterConfig config = findClusterConfig(key);
if (config == null) {
LOG.debug("Couldn't find cluster config of type {}", key);
return null;
}
T result = extractPayload(config.payload(), type);
... | @Test
public void getWithKeyReturnsExistingConfig() throws Exception {
DBObject dbObject = new BasicDBObjectBuilder()
.add("type", "foo")
.add("payload", Collections.singletonMap("text", "TEST"))
.add("last_updated", TIME.toString())
.add("last... |
@Override
public BasicTypeDefine reconvert(Column column) {
try {
return super.reconvert(column);
} catch (SeaTunnelRuntimeException e) {
throw CommonError.convertToConnectorTypeError(
DatabaseIdentifier.KINGBASE,
column.getDataType().g... | @Test
public void testReconvertString() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(BasicType.STRING_TYPE)
.columnLength(null)
.build();
BasicTypeDefine typeDefine ... |
@Override
public Set<String> getClusterList(String topic) throws RemotingConnectException, RemotingSendRequestException,
RemotingTimeoutException, MQClientException, InterruptedException {
return this.defaultMQAdminExtImpl.getClusterList(topic);
} | @Test
public void testGetClusterList() throws InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException {
Set<String> clusterlist = defaultMQAdminExt.getClusterList("UnitTest");
assertThat(clusterlist.contains("default-cluster-one")).is... |
public static void register(Class<? extends Event> eventClass, Subscriber subscriber) {
CopyOnWriteArraySet<Subscriber> set = SUBSCRIBER_MAP.get(eventClass);
if (set == null) {
set = new CopyOnWriteArraySet<Subscriber>();
CopyOnWriteArraySet<Subscriber> old = SUBSCRIBER_MAP.putIf... | @Test
public void register() throws Exception {
Subscriber subscriber = new TestSubscriber();
try {
Assert.assertEquals(EventBus.isEnable(TestEvent.class), false);
EventBus.register(TestEvent.class, subscriber);
Assert.assertEquals(EventBus.isEnable(TestEvent.clas... |
public String asPairsWithComment(String comment) {
return new PropertiesWriter(pairs).writeString(comment);
} | @Test
public void pairsWithComment() {
assertThat(createTestKeyValues().asPairsWithComment("this is a comment"),
is("# this is a comment\n" +
"first=1\n" +
"second=2\n" +
"third=3\n" +
"FOURTH=4\n... |
@Override
public void run() {
try {
interceptorChain.doInterceptor(task);
} catch (Exception e) {
Loggers.SRV_LOG.info("Interceptor health check task {} failed", task.getTaskId(), e);
}
} | @Test
void testRunHealthyInstanceWithHeartBeat() {
injectInstance(true, System.currentTimeMillis());
when(globalConfig.isExpireInstance()).thenReturn(true);
taskWrapper.run();
assertFalse(client.getAllInstancePublishInfo().isEmpty());
assertTrue(client.getInstancePublishInfo(... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void doNotRetryFromPredicateUsingMaybe() {
RetryConfig config = RetryConfig.custom()
.retryOnException(t -> t instanceof IOException)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);
giv... |
public void rollbackVersions(List<Job> jobsThatFailed) {
Set<UUID> jobIdsThatFailed = jobsThatFailed.stream().map(Job::getId).collect(toSet());
this.jobVersioners.stream()
.filter(jobVersioner -> !jobIdsThatFailed.contains(jobVersioner.getJob().getId()))
.forEach(JobVersi... | @Test
void testJobListVersionerInTryWithResourcesOnRollbackOfSomeJobsVersionIsDecreasedForThoseJobs() {
// GIVEN
Job job1 = aScheduledJob().withVersion(5).build();
Job job2 = aScheduledJob().withVersion(5).build();
// WHEN
try (JobListVersioner jobListVersioner = new JobList... |
public static int doubleCompare(double a, double b)
{
// these three ifs can only be true if neither value is NaN
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
// this check ensure doubleCompare(+0, -0) will return 0
// if we just ... | @Test
public void testDoubleCompare()
{
assertEquals(doubleCompare(0, Double.parseDouble("-0")), 0);
assertEquals(doubleCompare(Double.NaN, Double.NaN), 0);
//0x7ff8123412341234L is a different representation of NaN
assertEquals(doubleCompare(Double.NaN, longBitsToDouble(0x7ff812... |
@Override
@Private
public boolean isApplicationActive(ApplicationId id) throws YarnException {
ApplicationReport report = null;
try {
report = client.getApplicationReport(id);
} catch (ApplicationNotFoundException e) {
// the app does not exist
return false;
} catch (IOException e)... | @Test
void testNonExistentApp() throws Exception {
YarnClient client = createCheckerWithMockedClient();
ApplicationId id = ApplicationId.newInstance(1, 1);
// test for null
doReturn(null).when(client).getApplicationReport(id);
assertFalse(checker.isApplicationActive(id));
// test for Applica... |
public List<InetAddress> addresses(String inetHost, ResolvedAddressTypes resolvedAddressTypes) {
String normalized = normalize(inetHost);
ensureHostsFileEntriesAreFresh();
switch (resolvedAddressTypes) {
case IPV4_ONLY:
return inet4Entries.get(normalized);
... | @Test
public void shouldntFindWhenAddressesTypeDoesntMatch() {
HostsFileEntriesProvider.Parser parser = givenHostsParserWith(
LOCALHOST_V4_ADDRESSES,
Collections.<String, List<InetAddress>>emptyMap()
);
DefaultHostsFileEntriesResolver resolver = new DefaultHo... |
@PUT
@Path("/{pluginName}/config/validate")
@Operation(summary = "Validate the provided configuration against the configuration definition for the specified pluginName")
public ConfigInfos validateConfigs(
final @PathParam("pluginName") String pluginName,
final Map<String, String> connectorC... | @Test
public void testValidateConfigWithSimpleName() throws Throwable {
@SuppressWarnings("unchecked")
ArgumentCaptor<Callback<ConfigInfos>> configInfosCallback = ArgumentCaptor.forClass(Callback.class);
doAnswer(invocation -> {
ConfigDef connectorConfigDef = ConnectorConfig.conf... |
public HollowOrdinalIterator findKeysWithPrefix(String prefix) {
TST current;
HollowOrdinalIterator it;
do {
current = prefixIndexVolatile;
it = current.findKeysWithPrefix(prefix);
} while (current != this.prefixIndexVolatile);
return it;
} | @Test
public void testAutoExpandFieldPath() throws Exception {
for (Movie movie : getReferenceList()) {
objectMapper.add(movie);
}
StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine);
HollowPrefixIndex index = new HollowPrefixIndex(readStateEngine... |
public void detectAndResolve() {
createTopologyGraph();
} | @TestTemplate
void testDeadlockCausedByExchange() {
// P1 = PIPELINED + priority 1
//
// 0 -(P0)-> exchange --(P0)-> 1
// \-(P1)-/
TestingBatchExecNode[] nodes = new TestingBatchExecNode[2];
for (int i = 0; i < nodes.length; i++) {
nodes... |
@Override
public void createApiConfig(K8sApiConfig config) {
checkNotNull(config, ERR_NULL_CONFIG);
configStore.createApiConfig(config);
log.info(String.format(MSG_CONFIG, endpoint(config), MSG_CREATED));
} | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateConfig() {
target.createApiConfig(apiConfig1);
target.createApiConfig(apiConfig1);
} |
public static int sum(byte[] x) {
int sum = 0;
for (int n : x) {
sum += n;
}
return sum;
} | @Test
public void testSum_doubleArr() {
System.out.println("sum");
double[] data = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
assertEquals(45, MathEx.sum(data), 1E-6);
} |
Configuration getEffectiveConfiguration(String[] args) throws CliArgsException {
final CommandLine commandLine = cli.parseCommandLineOptions(args, true);
final Configuration effectiveConfiguration = new Configuration(baseConfiguration);
effectiveConfiguration.addAll(cli.toConfiguration(commandLi... | @Test
void testHeapMemoryPropertyWithOldConfigKey() throws Exception {
Configuration configuration = new Configuration();
configuration.set(DeploymentOptions.TARGET, KubernetesSessionClusterExecutor.NAME);
configuration.set(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY_MB, 2048);
configu... |
public double d(int[] x, int[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length));
}
double dist = 0.0;
if (weight == null) {
for (int i = 0; i < x.length; i++) {
... | @Test
public void testDistance() {
System.out.println("distance");
double[] x = {1.0, 2.0, 3.0, 4.0};
double[] y = {4.0, 3.0, 2.0, 1.0};
assertEquals(4.472136, new EuclideanDistance().d(x, y), 1E-6);
double[] w = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};... |
public static boolean hasIllegalNodeAddress(List<RemoteInstance> remoteInstances) {
if (CollectionUtils.isEmpty(remoteInstances)) {
return false;
}
Set<String> remoteAddressSet = remoteInstances.stream().map(remoteInstance ->
remoteInstance.getAddress().getHost()).col... | @Test
public void hasIllegalNodeAddressFalse() {
List<RemoteInstance> remoteInstances = new ArrayList<>();
remoteInstances.add(new RemoteInstance(new Address("123.23.4.2", 8899, true)));
boolean flag = OAPNodeChecker.hasIllegalNodeAddress(remoteInstances);
Assertions.assertFalse(flag... |
@SuppressWarnings("unchecked")
public DATA_TYPE getData() {
Object data = this.execution.taskInstance.getData();
if (data == null) {
return null;
} else if (dataClass.isInstance(data)) {
return (DATA_TYPE) data;
}
throw new DataClassMismatchException(dataClass, data.getClass());
} | @Test
public void test_data_class_type_not_equals() {
DataClassMismatchException dataClassMismatchException =
assertThrows(
DataClassMismatchException.class,
() -> {
Instant now = Instant.now();
OneTimeTask<Integer> task =
TestTasks.one... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
new SwiftAttributesFinderFeature(session).find(file, listener);
return true;
}
catch(N... | @Test
public void testFindKeyWithSameSuffix() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final String suffix = new AlphanumericRandomStringService().random();
fin... |
public static String validIdentifier(String value, int maxLen, String name) {
Check.notEmpty(value, name);
if (value.length() > maxLen) {
throw new IllegalArgumentException(
MessageFormat.format("[{0}] = [{1}] exceeds max len [{2}]", name, value, maxLen));
}
if (!IDENTIFIER_PATTERN.matcher... | @Test(expected = IllegalArgumentException.class)
public void validIdentifierInvalid3() throws Exception {
Check.validIdentifier("1", 1, "");
} |
@Override
public void initialize(String name, Map<String, String> properties) {
String uri = properties.get(CatalogProperties.URI);
Preconditions.checkArgument(null != uri, "JDBC connection URI is required");
try {
// We'll ensure the expected JDBC driver implementation class is initialized through
... | @Test
public void testInitializeNullFileIO() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> catalog.initialize(TEST_CATALOG_NAME, fakeClient, null, properties))
.withMessageContaining("fileIOFactory must be non-null");
} |
public boolean execute(
WorkflowSummary workflowSummary, Step step, StepRuntimeSummary runtimeSummary) {
StepRuntime.Result result =
getStepRuntime(runtimeSummary.getType())
.execute(workflowSummary, step, cloneSummary(runtimeSummary));
runtimeSummary.mergeRuntimeUpdate(result.getTimel... | @Test
public void testExecuteFailure() {
StepInstance.StepRetry stepRetry = new StepInstance.StepRetry();
stepRetry.setErrorRetryLimit(1);
stepRetry.setPlatformRetryLimit(1);
stepRetry.incrementByStatus(StepInstance.Status.USER_FAILED);
count.incrementAndGet();
StepRuntimeSummary summary =
... |
@Override
public int hashCode() {
return msgId.hashCode();
} | @Test
public void hashCodeTest() {
MessageIdImpl msgId1 = new MessageIdImpl(0, 0, 0);
MessageIdImpl msgId2 = new BatchMessageIdImpl(1, 1, 1, 1);
TopicMessageIdImpl topicMsgId1 = new TopicMessageIdImpl("topic-partition-1", msgId1);
TopicMessageIdImpl topic2MsgId1 = new TopicMessageIdI... |
public BackOffTimer(ScheduledExecutorService scheduler) {
this.scheduler = scheduler;
} | @Test
public void testBackOffTimer() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
final BackOff backOff = BackOff.builder().dela... |
@Override
public boolean add(V value) {
lock.lock();
try {
checkComparator();
BinarySearchResult<V> res = binarySearch(value);
int index = 0;
if (res.getIndex() < 0) {
index = -(res.getIndex() + 1);
} else {
... | @Test
public void testIteratorSequence() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
for (int i = 0; i < 1000; i++) {
set.add(Integer.valueOf(i));
}
Queue<Integer> setCopy = new PriorityQueue<Integer>();
for (int i = 0; i < 1000; i++) {
... |
@GetMapping("/secretInfo")
public ShenyuAdminResult info() {
return ShenyuAdminResult.success(null, secretService.info());
} | @Test
public void testQuerySecretInfo() throws Exception {
final String querySecretInfoUri = "/platform/secretInfo";
this.mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, querySecretInfoUri))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code", is(CommonEr... |
protected void populateSettings(CliParser cli) throws InvalidSettingException {
final File propertiesFile = cli.getFileArgument(CliParser.ARGUMENT.PROP);
if (propertiesFile != null) {
try {
settings.mergeProperties(propertiesFile);
} catch (FileNotFoundException e... | @Test
public void testPopulateSettings() throws Exception {
File prop = new File(this.getClass().getClassLoader().getResource("sample.properties").toURI().getPath());
String[] args = {"-P", prop.getAbsolutePath()};
Map<String, Boolean> expected = new HashMap<>();
expected.put(Setting... |
public String asPairsWithComment(String comment) {
return new PropertiesWriter(pairs).writeString(comment);
} | @Test
public void pairsWithMultineComment() {
assertThat(new OrderedProperties().asPairsWithComment("this\nis\n\ra\rcomment\\"),
is("# this\n" +
"# is\n" +
"# a\n" +
"# comment\\\n"));
} |
@VisibleForTesting
boolean checkSymlink(File jar) {
if (Files.isSymbolicLink(jar.toPath())) {
try {
java.nio.file.Path link = Files.readSymbolicLink(jar.toPath());
java.nio.file.Path jarPath = Paths.get(jar.getAbsolutePath());
String linkString = link.toString();
java.nio.fil... | @Test
void testNativeIO() throws IOException {
FrameworkUploader uploader = new FrameworkUploader();
File parent = new File(testDir);
try {
// Create a parent directory
parent.deleteOnExit();
assertTrue(parent.mkdirs());
// Create a target file
File targetFile = new File(par... |
@Override
public boolean isSecure() {
return delegate.isSecure();
} | @Test
public void delegate_methods_for_cookie() {
javax.servlet.http.Cookie mockCookie = new javax.servlet.http.Cookie("name", "value");
mockCookie.setSecure(true);
mockCookie.setPath("path");
mockCookie.setHttpOnly(true);
mockCookie.setMaxAge(100);
Cookie cookie = new JavaxHttpRequest.JavaxC... |
static void dissectReplaySessionError(
final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
int absoluteOffset = offset;
absoluteOffset += dissectLogHeader(CONTEXT, REPLAY_SESSION_ERROR, buffer, absoluteOffset, builder);
final long sessionId = buffer.ge... | @Test
void replaySessionError()
{
internalEncodeLogHeader(buffer, 0, 6, 100, () -> 5_600_000_000L);
buffer.putLong(LOG_HEADER_LENGTH, -8, LITTLE_ENDIAN);
buffer.putLong(LOG_HEADER_LENGTH + SIZE_OF_LONG, 42, LITTLE_ENDIAN);
buffer.putStringAscii(LOG_HEADER_LENGTH + SIZE_OF_LONG * ... |
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 shouldLoadFunctionWithStructReturnType() {
// Given:
final UdfFactory toStruct = FUNC_REG.getUdfFactory(FunctionName.of("tostruct"));
// When:
final List<SqlArgument> args = Collections.singletonList(SqlArgument.of(SqlTypes.STRING));
final KsqlScalarFunction function
= t... |
public static NetworkEndpoint forHostnameAndPort(String hostname, int port) {
checkArgument(
0 <= port && port <= MAX_PORT_NUMBER,
"Port out of range. Expected [0, %s], actual %s.",
MAX_PORT_NUMBER,
port);
return forHostname(hostname).toBuilder()
.setType(NetworkEndpoint... | @Test
public void forHostnameAndPort_withHostnameAndPort_returnsHostnameAndPortNetworkEndpoint() {
assertThat(NetworkEndpointUtils.forHostnameAndPort("localhost", 8888))
.isEqualTo(
NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.HOSTNAME_PORT)
.setPo... |
void updateSlobrokList(ApplicationInfo application) {
List<String> slobrokSpecs = getSlobrokSpecs(application);
slobrokList.setup(slobrokSpecs.toArray(new String[0]));
} | @Test
public void testUpdateSlobrokList() {
ApplicationInfo applicationInfo = ExampleModel.createApplication(
"tenant",
"application-name")
.build();
} |
public static <T> ExtensionLoader<T> getExtensionLoader(final Class<T> clazz, final ClassLoader cl) {
Objects.requireNonNull(clazz, "extension clazz is null");
if (!clazz.isInterface()) {
throw new IllegalArgumentException("extension clazz (" + clazz + ") is not interface!"... | @Test
public void loadResourcesIOException()
throws NoSuchMethodException, MalformedURLException, IllegalAccessException {
Method loadResourcesMethod = getLoadResources();
ExtensionLoader<JdbcSPI> extensionLoader = ExtensionLoader.getExtensionLoader(JdbcSPI.class);
try {
... |
@Nullable static String route(ContainerRequest request) {
ExtendedUriInfo uriInfo = request.getUriInfo();
List<UriTemplate> templates = uriInfo.getMatchedTemplates();
int templateCount = templates.size();
if (templateCount == 0) return "";
StringBuilder builder = null; // don't allocate unless you n... | @Test void route_basePath() {
setBaseUri("/base");
when(uriInfo.getMatchedTemplates()).thenReturn(Arrays.asList(
new PathTemplate("/"),
new PathTemplate("/items/{itemId}")
));
assertThat(SpanCustomizingApplicationEventListener.route(request))
.isEqualTo("/base/items/{itemId}");
} |
public MemoryLRUCacheBytesIterator reverseRange(final String namespace, final Bytes from, final Bytes to) {
final NamedCache cache = getCache(namespace);
if (cache == null) {
return new MemoryLRUCacheBytesIterator(Collections.emptyIterator(), new NamedCache(namespace, this.metrics));
... | @Test
public void shouldGetSameKeyAsPeekNextReverseRange() {
final ThreadCache cache = setupThreadCache(1, 1, 10000L, true);
final Bytes theByte = Bytes.wrap(new byte[]{1});
final ThreadCache.MemoryLRUCacheBytesIterator iterator = cache.reverseRange(namespace, Bytes.wrap(new byte[]{0}), theB... |
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) {
GuardedByExpression expr = BINDER.visit(exp, context);
checkGuardedBy(expr != null, String.valueOf(exp));
checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp);
return expr;
} | @Test
public void implicitThisOuterClassMethod() {
assertThat(
bind(
"Inner",
"endpoint().lock()",
forSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Outer {",
... |
@Override
public PipelineConfigs getLocal() {
for (PipelineConfigs part : this.parts) {
if (part.isLocal())
return part;
}
return null;
} | @Test
public void shouldReturnFilePartForGetLocalWhenHasRemoteAndFilePart() {
BasicPipelineConfigs filePart = new BasicPipelineConfigs();
filePart.setOrigin(new FileConfigOrigin());
BasicPipelineConfigs secondPart = new BasicPipelineConfigs();
secondPart.setOrigin(new RepoConfigOrig... |
@Override
public JreInfoRestResponse getJreMetadata(String id) {
return jresHandler.getJreMetadata(id);
} | @Test
void getJre_shouldReturnMetadataAsJson() throws Exception {
String anyId = "anyId";
JreInfoRestResponse jreInfoRestResponse = new JreInfoRestResponse(anyId, "filename", "sha256", "javaPath", "os", "arch");
when(jresHandler.getJreMetadata(anyId)).thenReturn(jreInfoRestResponse);
String expectedJs... |
@UdafFactory(description = "Compute average of column with type Long.",
aggregateSchema = "STRUCT<SUM bigint, COUNT bigint>")
public static TableUdaf<Long, Struct, Double> averageLong() {
return getAverageImplementation(
0L,
STRUCT_LONG,
(sum, newValue) -> sum.getInt64(SUM) + newValu... | @Test
public void shouldAggregateLongs() {
final TableUdaf<Long, Struct, Double> udaf = AverageUdaf.averageLong();
Struct agg = udaf.initialize();
final Long[] values = new Long[] {1L, 1L, 1L, 1L, 1L};
for (final Long thisValue : values) {
agg = udaf.aggregate(thisValue, agg);
}
assertTh... |
@Override
public SelResult childrenAccept(SelParserVisitor visitor, Object data) {
SelResult res = SelResult.NONE;
if (children != null) {
for (int i = 0; i < children.length; ++i) {
res = (SelResult) children[i].jjtAccept(visitor, data);
switch (res) {
case BREAK:
... | @Test
public void testVisitedReturnNode() {
root.jjtAddChild(returnNode, 2);
root.jjtAddChild(returnNode, 1);
root.jjtAddChild(returnNode, 0);
SelResult res = root.childrenAccept(null, null);
assertEquals(SelResult.RETURN, res);
assertArrayEquals(new int[] {0, 0, 1, 0, 0}, visited);
} |
public static TimeUnit getMetricsDurationUnit(Map<String, Object> daemonConf) {
return getTimeUnitForConfig(daemonConf, Config.STORM_DAEMON_METRICS_REPORTER_PLUGIN_DURATION_UNIT);
} | @Test
public void getMetricsDurationUnit() {
Map<String, Object> daemonConf = new HashMap<>();
assertNull(MetricsUtils.getMetricsDurationUnit(daemonConf));
daemonConf.put(Config.STORM_DAEMON_METRICS_REPORTER_PLUGIN_DURATION_UNIT, "SECONDS");
assertEquals(TimeUnit.SECONDS, MetricsUt... |
public static ExecutorService getSingleThreadExecutor() {
setup();
return singleThreadExecutor;
} | @Test
public void singleThread() {
ExecutorService a = SharedExecutors.getSingleThreadExecutor();
assertNotNull("ExecutorService must not be null", a);
ExecutorService b = SharedExecutors.getSingleThreadExecutor();
assertSame("factories should be same", a, b);
} |
static <T, W extends BoundedWindow>
ThrowingFunction<KV<T, Iterable<W>>, KV<T, KV<Iterable<W>, Iterable<KV<W, Iterable<W>>>>>>
createMapFunctionForPTransform(String ptransformId, PTransform ptransform)
throws IOException {
RunnerApi.FunctionSpec payload =
RunnerApi.FunctionSpec... | @Test
public void testWindowMergingWithMergingWindowFn() throws Exception {
ThrowingFunction<
KV<Object, Iterable<BoundedWindow>>,
KV<
Object,
KV<Iterable<BoundedWindow>, Iterable<KV<BoundedWindow, Iterable<BoundedWindow>>>>>>
mapFunction =
... |
@Override
public final String toString() {
StringBuilder out = new StringBuilder();
appendTo(out);
return out.toString();
} | @Test
void requireThatPredicatesCanBeBuiltUsingSeparateMethodCalls() {
Conjunction conjunction = new Conjunction();
FeatureSet countrySet = new FeatureSet("country");
countrySet.addValue("no");
countrySet.addValue("se");
conjunction.addOperand(countrySet);
FeatureRang... |
public boolean compareAndSet(T expectedState, T newState)
{
checkState(!Thread.holdsLock(lock), "Can not set state while holding the lock");
requireNonNull(expectedState, "expectedState is null");
requireNonNull(newState, "newState is null");
FutureStateChange<T> futureStateChange;
... | @Test
public void testCompareAndSet()
throws Exception
{
StateMachine<State> stateMachine = new StateMachine<>("test", executor, State.BREAKFAST, ImmutableSet.of(State.DINNER));
assertEquals(stateMachine.get(), State.BREAKFAST);
// no match with new state
assertNoSta... |
@Override
public void createDataStream(String dataStreamName, String timestampField, Map<String, Map<String, String>> mappings,
Policy ismPolicy) {
updateDataStreamTemplate(dataStreamName, timestampField, mappings);
dataStreamAdapter.createDataStream(dataStreamName);... | @SuppressWarnings("unchecked")
@Test
public void templateDoesNotOverwriteTimestampMapping() {
final Map<String, Map<String, String>> mappings = new HashMap<>();
String ts = "ts";
mappings.put(ts, Map.of("type", "date", "format", "mycustomformat"));
dataStreamService.createDataStr... |
@Override
public ScalarOperator visitMultiInPredicate(MultiInPredicateOperator operator, Void context) {
return shuttleIfUpdate(operator);
} | @Test
void testMultiInPredicateOperator() {
ColumnRefOperator column1 = new ColumnRefOperator(1, INT, "id", true);
MultiInPredicateOperator operator = new MultiInPredicateOperator(false,
Lists.newArrayList(column1, column1), Lists.newArrayList(column1, column1));
{
... |
public double[] rowMeans() {
double[] x = rowSums();
for (int i = 0; i < m; i++) {
x[i] /= n;
}
return x;
} | @Test
public void testRowMeans() {
System.out.println("rowMeans");
double[][] A = {
{ 0.7220180, 0.07121225, 0.6881997f},
{-0.2648886, -0.89044952, 0.3700456f},
{-0.6391588, 0.44947578, 0.6240573f}
};
double[] r = {0.4938100, -0.26176... |
public static void print(final Options options) {
print(options, new TerminalHelpFormatter());
} | @Test
@Ignore
public void testPrintWidth20DefaultFormatter() {
final HelpFormatter f = new TerminalHelpFormatter();
f.setWidth(20);
TerminalHelpPrinter.print(TerminalOptionsBuilder.options(), f);
} |
public void checkIfAnyComponentsNeedIssueSync(DbSession dbSession, List<String> componentKeys) {
boolean isAppOrViewOrSubview = dbClient.componentDao().existAnyOfComponentsWithQualifiers(dbSession, componentKeys, APP_VIEW_OR_SUBVIEW);
boolean needIssueSync;
if (isAppOrViewOrSubview) {
needIssueSync = ... | @Test
public void checkIfAnyComponentsNeedIssueSync_throws_exception_if_at_least_one_component_has_need_issue_sync_TRUE() {
ProjectData projectData1 = insertProjectWithBranches(false, 0);
ProjectData projectData2 = insertProjectWithBranches(true, 0);
DbSession session = db.getSession();
List<String> ... |
public void connect() throws ConnectException {
connect(s -> {}, t -> {}, () -> {});
} | @Test
public void testConnectViaWebSocketClient() throws Exception {
service.connect();
verify(webSocketClient).connectBlocking();
} |
protected synchronized Timestamp convertStringToTimestamp( String string ) throws KettleValueException {
// See if trimming needs to be performed before conversion
//
string = Const.trimToType( string, getTrimType() );
if ( Utils.isEmpty( string ) ) {
return null;
}
Timestamp returnValue;... | @Test
public void testConvertStringToTimestamp() throws Exception {
ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp();
assertEquals( Timestamp.valueOf( "2012-04-05 04:03:02.123456" ), valueMetaTimestamp
.convertStringToTimestamp( "2012/4/5 04:03:02.123456" ) );
assertEquals( Timestamp... |
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("LazySet is not modifiable");
} | @Test(expected = UnsupportedOperationException.class)
public void testRetainAll_throwsException() {
set.retainAll(Collections.emptyList());
} |
public static RowRanges calculateRowRanges(
FilterCompat.Filter filter, ColumnIndexStore columnIndexStore, Set<ColumnPath> paths, long rowCount) {
return filter.accept(new FilterCompat.Visitor<RowRanges>() {
@Override
public RowRanges visit(FilterPredicateCompat filterPredicateCompat) {
tr... | @Test
public void testFilteringOnMissingColumns() {
Set<ColumnPath> paths = paths("column1", "column2", "column3", "column4");
// Missing column filter is always true
assertAllRows(
calculateRowRanges(
FilterCompat.get(notEq(intColumn("missing_column"), 0)), STORE, paths, TOTAL_ROW_CO... |
private void processData() {
Map<String, InstanceInfo> instanceInfoMap = InstanceCache.INSTANCE_MAP;
if (instanceInfoMap.isEmpty()) {
LOGGER.log(Level.FINE,"Instance information is empty");
return;
}
for (Iterator<Map.Entry<String, InstanceInfo>> iterator = instan... | @Test
public void testProcessData() throws InterruptedException {
requestDataCountTask = new RequestDataCountTask();
requestDataCountTask.start();
Thread.sleep(15000);
InstanceInfo info = InstanceCache.INSTANCE_MAP.get(KEY);
Assert.assertTrue(info != null && info.getCountData... |
public boolean putKey(final String key, final long phyOffset, final long storeTimestamp) {
if (this.indexHeader.getIndexCount() < this.indexNum) {
int keyHash = indexKeyHashMethod(key);
int slotPos = keyHash % this.hashSlotNum;
int absSlotPos = IndexHeader.INDEX_HEADER_SIZE +... | @Test
public void testPutKey() throws Exception {
IndexFile indexFile = new IndexFile("100", HASH_SLOT_NUM, INDEX_NUM, 0, 0);
for (long i = 0; i < (INDEX_NUM - 1); i++) {
boolean putResult = indexFile.putKey(Long.toString(i), i, System.currentTimeMillis());
assertThat(putResu... |
@CanIgnoreReturnValue
public final Ordered containsAtLeastElementsIn(@Nullable Iterable<?> expectedIterable) {
List<?> actual = Lists.newLinkedList(checkNotNull(this.actual));
Collection<?> expected = iterableToCollection(expectedIterable);
List<@Nullable Object> missing = newArrayList();
List<@Nulla... | @Test
@SuppressWarnings("ContainsAllElementsInWithVarArgsToContainsAtLeast")
public void iterableContainsAtLeastElementsInIterable() {
assertThat(asList(1, 2, 3)).containsAtLeastElementsIn(asList(1, 2));
expectFailureWhenTestingThat(asList(1, 2, 3)).containsAtLeastElementsIn(asList(1, 2, 4));
assertFai... |
public static boolean pathExists(Path path, Configuration conf) {
try {
FileSystem fileSystem = FileSystem.get(path.toUri(), conf);
return fileSystem.exists(path);
} catch (Exception e) {
LOG.error("Failed to check path {}", path, e);
throw new StarRocksCo... | @Test
public void testPathExists() {
Path path = new Path("hdfs://127.0.0.1:9000/user/hive/warehouse/db");
ExceptionChecker.expectThrowsWithMsg(StarRocksConnectorException.class,
"Failed to check path",
() -> HiveWriteUtils.pathExists(path, new Configuration()));
... |
public Location setZ(double z) {
return new Location(extent, position.withZ(z), yaw, pitch);
} | @Test
public void testSetZ() throws Exception {
World world = mock(World.class);
Location location1 = new Location(world, Vector3.ZERO);
Location location2 = location1.setZ(TEST_VALUE);
assertEquals(0, location1.getZ(), EPSILON);
assertEquals(0, location2.getX(), EPSILON);
... |
int retrieveEdits(long requestedStartTxn, int maxTxns,
List<ByteBuffer> outputBuffers) throws IOException {
int txnCount = 0;
try (AutoCloseableLock l = readLock.acquire()) {
if (lowestTxnId == INVALID_TXN_ID || requestedStartTxn < lowestTxnId) {
throw getCacheMissException(requestedStartTx... | @Test(expected = JournaledEditsCache.CacheMissException.class)
public void testReadUninitializedCache() throws Exception {
cache.retrieveEdits(1, 10, new ArrayList<>());
} |
private RemotingCommand deleteAcl(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
DeleteAclRequestHeader requestHeader = request.decodeCommandCustomHeader(DeleteAclRequestHeader.c... | @Test
public void testDeleteAcl() throws RemotingCommandException {
when(authorizationMetadataManager.deleteAcl(any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
DeleteAclRequestHeader deleteAclRequestHeader = new DeleteAclRequestHeader();
deleteAclRequ... |
@Udf
public String elt(
@UdfParameter(description = "the nth element to extract") final int n,
@UdfParameter(description = "the strings of which to extract the nth") final String... args
) {
if (args == null) {
return null;
}
if (n < 1 || n > args.length) {
return null;
}
... | @Test
public void shouldHandleNulls() {
// When:
final String el = elt.elt(2, "a", null);
// Then:
assertThat(el, is(nullValue()));
} |
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 testDeploymentDesciptorMergeKeepAll() {
DeploymentDescriptor primary = new DeploymentDescriptorImpl("org.jbpm.domain");
primary.getBuilder()
.addMarshalingStrategy(new ObjectModel("org.jbpm.test.CustomStrategy", new Object[]{"param2"}))
.setLimitSer... |
public String getLabel() {
if (period == null) {
final DateFormat dateFormat = I18N.createDateFormat();
return dateFormat.format(startDate) + " - " + dateFormat.format(endDate);
}
return period.getLabel();
} | @Test
public void testGetLabel() {
assertNotNull("getLabel", periodRange.getLabel());
assertNotNull("getLabel", customRange.getLabel());
} |
@Override
public V poll() {
return get(pollAsync());
} | @Test
public void testPoll() throws InterruptedException {
RBlockingQueue<String> queue = redisson.getBlockingQueue("test");
RDelayedQueue<String> dealyedQueue = redisson.getDelayedQueue(queue);
dealyedQueue.offer("1", 1, TimeUnit.SECONDS);
dealyedQueue.offer("2", 2, TimeUni... |
public Date getStartDate() {
return startDate;
} | @Test
public void testGetStartDate() {
assertNull("getStartDate", periodRange.getStartDate());
assertNotNull("getStartDate", customRange.getStartDate());
} |
@Override
public Set<Path> getPaths(ElementId src, ElementId dst, LinkWeigher weigher) {
checkNotNull(src, ELEMENT_ID_NULL);
checkNotNull(dst, ELEMENT_ID_NULL);
LinkWeigher internalWeigher = weigher != null ? weigher : DEFAULT_WEIGHER;
// Get the source and destination edge locatio... | @Test
public void testDevicePaths() {
topoMgr.definePaths(ImmutableSet.of(path1));
Set<Path> pathsAC = service.getPaths(did("A"), did("C"), new TestWeigher());
checkPaths(pathsAC);
} |
@Override
public boolean equals(Object object) {
if (object != null && getClass() == object.getClass()) {
if (!super.equals(object)) {
return false;
}
DefaultPortDescription that = (DefaultPortDescription) object;
return Objects.equal(this.numb... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(portDescription1, sameAsPortDescription1)
.addEqualityGroup(portDescription2)
.addEqualityGroup(portDescription3)
.testEquals();
} |
@Override
public void restRequest(RestRequest request, Callback<RestResponse> callback, String routeKey)
{
this.restRequest(request, new RequestContext(), callback, routeKey);
} | @Test
public void testBadRequest()
{
RouteLookup routeLookup = new SimpleTestRouteLookup();
final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build();
d2Client.start(new FutureCallback<>());
RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup... |
public InetSocketAddress getManagedPort(
final UdpChannel udpChannel,
final InetSocketAddress bindAddress) throws BindException
{
InetSocketAddress address = bindAddress;
if (bindAddress.getPort() != 0)
{
portSet.add(bindAddress.getPort());
}
else... | @Test
void shouldPassThroughWithExplicitBindAddressOutSideRange() throws BindException
{
final InetSocketAddress bindAddress = new InetSocketAddress("localhost", 1000);
final WildcardPortManager manager = new WildcardPortManager(portRange, true);
assertThat(manager.getManagedPort(
... |
public static AttributesBuilder newAttributesBuilder() {
AttributesBuilder attributesBuilder;
if (attributesBuilderSupplier == null) {
attributesBuilderSupplier = Attributes::builder;
}
attributesBuilder = attributesBuilderSupplier.get();
LABEL_MAP.forEach(attributesB... | @Test
public void testNewAttributesBuilder() {
Attributes attributes = BrokerMetricsManager.newAttributesBuilder().put("a", "b")
.build();
assertThat(attributes.get(AttributeKey.stringKey("a"))).isEqualTo("b");
} |
@Override
public InputStream getInputStream(final int columnIndex, final String type) throws SQLException {
return queryResult.getInputStream(columnIndex, type);
} | @Test
void assertGetInputStream() throws SQLException {
QueryResult queryResult = mock(QueryResult.class);
InputStream value = mock(InputStream.class);
when(queryResult.getInputStream(1, "Ascii")).thenReturn(value);
TransparentMergedResult actual = new TransparentMergedResult(queryRe... |
public void executeTransformation( final TransMeta transMeta, final boolean local, final boolean remote,
final boolean cluster, final boolean preview, final boolean debug, final Date replayDate, final boolean safe,
LogLevel logLevel ) throws KettleException {
if ( transMeta == null ) {
return;
... | @Test
@SuppressWarnings( "ResultOfMethodCallIgnored" )
public void testSetParamsIntoMetaInExecuteTransformation() throws KettleException {
doCallRealMethod().when( delegate ).executeTransformation( transMeta, true, false, false,
false, false, null, false, LogLevel.BASIC );
RowMetaInterface rowM... |
@Override
public WorkProcessor<Page> buildResult()
{
if (groupByHash.getGroupCount() == 0) {
return WorkProcessor.fromIterator(emptyIterator());
}
return WorkProcessor.fromIterator(new ResultIterator(IntStream.range(0, groupByHash.getGroupCount()).iterator(), false));
} | @Test
public void testEmptyInput()
{
InMemoryGroupedTopNBuilder groupedTopNBuilder = new InMemoryGroupedTopNBuilder(
ImmutableList.of(BIGINT),
(left, leftPosition, right, rightPosition) -> {
throw new UnsupportedOperationException();
},... |
Set<String> getConvertedUserIds() {
return Collections.unmodifiableSet(idToDirectoryNameMap.keySet());
} | @Test
public void testInitialUserIds() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
assertThat(mapper.getConvertedUserIds(), empty());
} |
@Override
public CompletableFuture<Void> offload(ReadHandle readHandle,
UUID uuid,
Map<String, String> extraMetadata) {
final String managedLedgerName = extraMetadata.get(MANAGED_LEDGER_NAME);
final String topicNam... | @Test
public void testOffloadEmpty() throws Exception {
CompletableFuture<LedgerEntries> noEntries = new CompletableFuture<>();
noEntries.completeExceptionally(new BKException.BKReadException());
ReadHandle readHandle = Mockito.mock(ReadHandle.class);
Mockito.doReturn(-1L).when(read... |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testConsumerGroupRebalanceSensor() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
Uuid barTopicId =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.