focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
@SuppressWarnings("MissingDefault")
public boolean offer(final E e) {
if (e == null) {
throw new NullPointerException();
}
long mask;
E[] buffer;
long pIndex;
while (true) {
long producerLimit = lvProducerLimit();
pIndex = lvProducerIndex(this);
// lower b... | @Test(dataProvider = "full")
public void offer_whenFull(MpscGrowableArrayQueue<Integer> queue) {
assertThat(queue.offer(1)).isFalse();
assertThat(queue).hasSize(FULL_SIZE);
} |
@Override
public Observable<Void> fetchObservable() {
return this.toObservable();
} | @Test
public void testFetchObservable() {
assertNotNull(hystrixCommand.fetchObservable());
} |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void accept_empty_query() {
ProjectMeasuresQuery result = newProjectMeasuresQuery(emptyList(), emptySet());
assertThat(result.getMetricCriteria()).isEmpty();
} |
public static String loadMigrationRule(Set<ClassLoader> classLoaders, String fileName) {
String rawRule = "";
if (checkFileNameExist(fileName)) {
try {
try (FileInputStream input = new FileInputStream(fileName)) {
return readString(input);
... | @Test
void testLoadMigrationRule() {
Set<ClassLoader> classLoaderSet = new HashSet<>();
classLoaderSet.add(ClassUtils.getClassLoader());
String rule = ConfigUtils.loadMigrationRule(classLoaderSet, "dubbo-migration.yaml");
Assertions.assertNotNull(rule);
} |
public int validate(
final ServiceContext serviceContext,
final List<ParsedStatement> statements,
final SessionProperties sessionProperties,
final String sql
) {
requireSandbox(serviceContext);
final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext));
... | @Test
public void shouldExecuteWithSpecifiedServiceContext() {
// Given:
final List<ParsedStatement> statements = givenParsed(SOME_STREAM_SQL);
final ServiceContext otherServiceContext =
SandboxedServiceContext.create(TestServiceContext.create());
// When:
validator.validate(otherServiceC... |
@Override
public int union(String... names) {
return get(unionAsync(names));
} | @Test
public void testUnion() {
RScoredSortedSet<String> set1 = redisson.getScoredSortedSet("simple1");
set1.add(1, "one");
set1.add(2, "two");
RScoredSortedSet<String> set2 = redisson.getScoredSortedSet("simple2");
set2.add(1, "one");
set2.add(2, "two");
set... |
public static String wrapWithColorTag(final String str, final Color color)
{
return prependColorTag(str, color) + CLOSING_COLOR_TAG;
} | @Test
public void wrapWithColorTag()
{
COLOR_HEXSTRING_MAP.forEach((color, hex) ->
{
assertEquals("<col=" + hex + ">test</col>", ColorUtil.wrapWithColorTag("test", color));
assertEquals("<col=" + hex + "></col>", ColorUtil.wrapWithColorTag("", color));
});
} |
@Override
public Num calculate(BarSeries series, Position position) {
if (position.isClosed()) {
Num entryPrice = position.getEntry().getValue();
return position.getProfit().dividedBy(entryPrice).multipliedBy(series.hundred());
}
return series.zero();
} | @Test
public void calculateWithWinningShortPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 90, 100, 95, 95, 100);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(1, series),
Trade.sellAt(2, series), Trade.buyAt(3, seri... |
@Override
public MetadataNode child(String name) {
if (name.equals(ClusterImageBrokersNode.NAME)) {
return new ClusterImageBrokersNode(image);
} else if (name.equals(ClusterImageControllersNode.NAME)) {
return new ClusterImageControllersNode(image);
} else {
... | @Test
public void testControllersChild() {
MetadataNode child = NODE.child("controllers");
assertNotNull(child);
assertEquals(ClusterImageControllersNode.class, child.getClass());
} |
public static NetworkInterface findNetworkInterface() {
List<NetworkInterface> validNetworkInterfaces = emptyList();
try {
validNetworkInterfaces = getValidNetworkInterfaces();
} catch (Throwable e) {
logger.warn(e);
}
NetworkInterface result = null;
... | @Test
void testIgnoreGivenPrefixInterfaceName() {
// store the origin ignored interfaces
String originIgnoredInterfaces = this.getIgnoredInterfaces();
try {
NetworkInterface networkInterface = NetUtils.findNetworkInterface();
assertNotNull(networkInterface);
... |
public Model parse(File file) throws PomParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parse(fis);
} catch (IOException ex) {
if (ex instanceof PomParseException) {
throw (PomParseException) ex;
}
LOGGER.deb... | @Test
public void testParse_File() throws Exception {
File file = BaseTest.getResourceAsFile(this, "pom/mailapi-1.4.3.pom");
PomParser instance = new PomParser();
String expVersion = "1.4.3";
Model result = instance.parse(file);
assertEquals("Invalid version extracted", expVe... |
public static Find find(String regex) {
return find(regex, 0);
} | @Test
@Category(NeedsRunner.class)
public void testFindNameGroup() {
PCollection<String> output =
p.apply(Create.of("aj", "xj", "yj", "zj"))
.apply(Regex.find("(?<namedgroup>[xyz])", "namedgroup"));
PAssert.that(output).containsInAnyOrder("x", "y", "z");
p.run();
} |
public void assignStates() {
checkStateMappingCompleteness(allowNonRestoredState, operatorStates, tasks);
Map<OperatorID, OperatorState> localOperators = new HashMap<>(operatorStates);
// find the states of all operators belonging to this task and compute additional
// information in f... | @Test
public void testChannelStateAssignmentTwoGatesPartiallyDownscaling()
throws JobException, JobExecutionException {
JobVertex upstream1 = createJobVertex(new OperatorID(), 2);
JobVertex upstream2 = createJobVertex(new OperatorID(), 2);
JobVertex downstream = createJobVertex(n... |
public synchronized <K, V> KStream<K, V> stream(final String topic) {
return stream(Collections.singleton(topic));
} | @Test
public void shouldThrowWhenSubscribedToAPatternWithSetAndUnsetResetPolicies() {
builder.stream(Pattern.compile("some-regex"), Consumed.with(AutoOffsetReset.EARLIEST));
builder.stream(Pattern.compile("some-regex"));
assertThrows(TopologyException.class, builder::build);
} |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testIsNotNull() {
Expression expr = resolve(Expressions.$("field1").isNotNull());
Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert(expr);
assertThat(actual).isPresent();
UnboundPredicate<Object> expected =
org.apache.iceberg.expressions.Expres... |
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
} | @Test
public void shouldHandleArbitraryErrorsOnGetRequests() {
// Given:
server.setErrorCode(417);
// When:
KsqlTarget target = ksqlClient.target(serverUri);
RestResponse<ServerInfo> response = target.getServerInfo();
// Then:
assertThat(server.getHttpMethod(), is(HttpMethod.GET));
... |
public Object toIdObject(String baseId) throws AmqpProtocolException {
if (baseId == null) {
return null;
}
try {
if (hasAmqpUuidPrefix(baseId)) {
String uuidString = strip(baseId, AMQP_UUID_PREFIX_LENGTH);
return UUID.fromString(uuidStrin... | @Test
public void testToIdObjectWithEncodedUlong() throws Exception {
UnsignedLong longId = UnsignedLong.valueOf(123456789L);
String provided = AMQPMessageIdHelper.AMQP_ULONG_PREFIX + "123456789";
Object idObject = messageIdHelper.toIdObject(provided);
assertNotNull("null object sho... |
public static Path getJobAttemptPath(JobContext context, Path out) {
return getJobAttemptPath(getAppAttemptId(context), out);
} | @Test
public void testJobCommit() throws Exception {
Path jobAttemptPath = jobCommitter.getJobAttemptPath(job);
FileSystem fs = jobAttemptPath.getFileSystem(conf);
Set<String> uploads = runTasks(job, 4, 3);
assertNotEquals(0, uploads.size());
assertPathExists(fs, "No job attempt path", jobAttemp... |
public boolean isProactiveSupportEnabled() {
if (properties == null) {
return false;
}
return getMetricsEnabled();
} | @Test
public void isProactiveSupportDisabledFull() {
// Given
Properties serverProperties = new Properties();
serverProperties
.setProperty(BaseSupportConfig.CONFLUENT_SUPPORT_METRICS_ENABLE_CONFIG, "false");
serverProperties.setProperty(
BaseSupportConfig.CONFLUENT_SUPPORT_METRICS_EN... |
@Override
public boolean tryInit(long expectedInsertions, double falseProbability) {
return get(tryInitAsync(expectedInsertions, falseProbability));
} | @Test
public void test() {
RBloomFilter<String> filter = redisson.getBloomFilter("filter");
filter.tryInit(550000000L, 0.5);
test(filter);
filter.delete();
assertThat(filter.tryInit(550000000L, 0.03)).isTrue();
test(filter);
} |
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream, ChannelPromise promise) {
return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise);
} | @Test
public void headersWriteShouldOpenStreamForPush() throws Exception {
writeAllFlowControlledFrames();
Http2Stream parent = createStream(STREAM_ID, false);
reservePushStream(PUSH_STREAM_ID, parent);
ChannelPromise promise = newPromise();
encoder.writeHeaders(ctx, PUSH_ST... |
static JavaType constructType(Type type) {
try {
return constructTypeInner(type);
} catch (Exception e) {
throw new InvalidDataTableTypeException(type, e);
}
} | @Test
void wild_card_list_types_use_upper_bound_in_equality() {
JavaType javaType = TypeFactory.constructType(LIST_OF_WILD_CARD_NUMBER);
JavaType other = TypeFactory.constructType(LIST_OF_NUMBER);
assertThat(javaType, equalTo(other));
TypeFactory.ListType listType = (TypeFactory.List... |
public Map<K, V> getAll(Iterable<K> keys) {
List<K> missingKeys = new ArrayList<>();
Map<K, V> result = new HashMap<>();
for (K key : keys) {
V value = map.get(key);
if (value == null && !map.containsKey(key)) {
missingKeys.add(key);
} else {
result.put(key, value);
}... | @Test
public void getAllNullable() {
// ask for 3 keys but only 2 are available in backed (third key is missing)
List<String> keys = Arrays.asList("one", "two", "three");
Map<String, String> values = new HashMap<>();
values.put("one", "un");
values.put("two", "deux");
when(loader.loadAll(keys)... |
public boolean isStructType() {
return this instanceof StructType;
} | @Test
public void testStructSerialAndDeser() {
// "struct<struct_test:int,c1:struct<c1:int,cc1:string>>"
StructType c1 = new StructType(Lists.newArrayList(
new StructField("c1", ScalarType.createType(PrimitiveType.INT)),
new StructField("cc1", ScalarType.createDefault... |
public synchronized void submitRunTaskCommand(long jobId, long taskId, JobConfig jobConfig,
Object taskArgs, long workerId) {
RunTaskCommand.Builder runTaskCommand = RunTaskCommand.newBuilder();
runTaskCommand.setJobId(jobId);
runTaskCommand.setTaskId(taskId);
try {
runTaskCommand.setJobConf... | @Test
public void submitRunTaskCommand() throws Exception {
long jobId = 0L;
int taskId = 1;
JobConfig jobConfig = new TestPlanConfig("/test");
long workerId = 2L;
List<Integer> args = Lists.newArrayList(1);
mManager.submitRunTaskCommand(jobId, taskId, jobConfig, args, workerId);
List<JobC... |
public CompletableFuture<Void> handlePullQuery(
final ServiceContext serviceContext,
final PullPhysicalPlan pullPhysicalPlan,
final ConfiguredStatement<Query> statement,
final RoutingOptions routingOptions,
final PullQueryWriteStream pullQueryQueue,
final CompletableFuture<Void> shou... | @Test
public void shouldNotRouteToFilteredHost() throws InterruptedException, ExecutionException {
// Given:
location1 = new PartitionLocation(Optional.empty(), 1, ImmutableList.of(badNode, node1));
when(ksqlClient.makeQueryRequest(any(), any(), any(), any(), any(), any(), any()))
.then(invocation... |
public static long calculate(PhysicalRel rel, ExpressionEvalContext evalContext) {
GcdCalculatorVisitor visitor = new GcdCalculatorVisitor(evalContext);
visitor.go(rel);
if (visitor.gcd == 0) {
// there's no window aggr in the rel, return the value for joins, which is already capped... | @Test
public void when_unionAboveSlidingWindows_then_returnGcdOfWindowsSize() {
HazelcastTable table = streamGeneratorTable("s1", 1);
HazelcastTable table2 = streamGeneratorTable("s2", 10);
HazelcastTable table3 = streamGeneratorTable("s3", 100);
List<QueryDataType> parameterTypes = ... |
public static <InputT> Builder<InputT> withoutHold(AppliedPTransform<?, ?, ?> transform) {
return new Builder(transform, BoundedWindow.TIMESTAMP_MAX_VALUE);
} | @Test
public void producedBundlesAndAdditionalOutputProducedOutputs() {
TransformResult<Integer> result =
StepTransformResult.<Integer>withoutHold(transform)
.addOutput(bundleFactory.createBundle(pc))
.withAdditionalOutput(OutputType.PCOLLECTION_VIEW)
.build();
ass... |
public static WindowBytesStoreSupplier persistentTimestampedWindowStore(final String name,
final Duration retentionPeriod,
final Duration windowSize,
... | @Test
public void shouldThrowIfIPersistentTimestampedWindowStoreStoreNameIsNull() {
final Exception e = assertThrows(NullPointerException.class, () -> Stores.persistentTimestampedWindowStore(null, ZERO, ZERO, false));
assertEquals("name cannot be null", e.getMessage());
} |
@Override
public @Nullable SplitResult<TimestampRange> trySplit(double fractionOfRemainder) {
if (InitialPartition.isInitialPartition(partition.getPartitionToken())) {
return null;
}
return super.trySplit(fractionOfRemainder);
} | @Test
public void testTrySplitReturnsNullForInitialPartition() {
when(partition.getPartitionToken()).thenReturn(InitialPartition.PARTITION_TOKEN);
assertNull(tracker.trySplit(0.0D));
} |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void longLivedReferenceJwt() throws Exception {
Map<String, String> custom = new HashMap<>();
custom.put("consumer_application_id", "361");
custom.put("request_transit", "67");
JwtClaims claims = ClaimsUtil.getCustomClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c... |
public void computeCpd(Component component, Collection<Block> originBlocks, Collection<Block> duplicationBlocks) {
CloneIndex duplicationIndex = new PackedMemoryCloneIndex();
populateIndex(duplicationIndex, originBlocks);
populateIndex(duplicationIndex, duplicationBlocks);
List<CloneGroup> duplications... | @Test
public void add_duplication_for_java_even_when_no_token() {
Component javaFile = builder(FILE, 1)
.setKey(ORIGIN_FILE_KEY)
.setFileAttributes(new FileAttributes(false, "java", 10))
.build();
Collection<Block> originBlocks = singletonList(
// This block contains 0 token
new... |
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) {
List<String> diagramLines = filterOutComments(rawDiagramLines);
Set<PlantUmlComponent> components = parseComponents(diagramLines);
PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components);
List<Parse... | @Test
@UseDataProvider("dependency_arrow_testcases")
public void parses_various_types_of_dependency_arrows(String dependency) {
PlantUmlDiagram diagram = createDiagram(TestDiagram.in(temporaryFolder)
.component("SomeOrigin").withStereoTypes("..origin..")
.component("SomeT... |
void setDeprecationHeaders(Request request, Response response, DeprecatedAPI controller) {
String deprecatedRelease = controller.deprecatedIn();
String removalRelease = controller.removalIn();
String entityName = controller.entityName();
ApiVersion deprecatedApiVersion = controller.depre... | @Test
void shouldAddDeprecationHeaders() {
DoNothingApiV1 doNothingApiV1 = new DoNothingApiV1();
RoutesHelper helper = new RoutesHelper(doNothingApiV1);
Request request = mock(Request.class);
Response response = mock(Response.class);
when(request.url()).thenReturn("http://t... |
protected void saveAndRunJobFilters(List<Job> jobs) {
if (jobs.isEmpty()) return;
try {
jobFilterUtils.runOnStateElectionFilter(jobs);
storageProvider.save(jobs);
jobFilterUtils.runOnStateAppliedFilters(jobs);
} catch (ConcurrentJobModificationException concu... | @Test
void ifStateChangeHappensStateChangeFiltersAreInvoked() {
Job aJobInProgress = aJobInProgress().build();
aJobInProgress.succeeded();
task.saveAndRunJobFilters(singletonList(aJobInProgress));
assertThat(logAllStateChangesFilter.getStateChanges(aJobInProgress)).containsExactly(... |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public GenericRow apply(
final GenericKey k,
final GenericRow rowValue,
final GenericRow aggRowValue
) {
final GenericRow result = GenericRow.fromList(aggRowValue.values());
for (int idx = 0; idx < nonAggColumnCount; idx++) {
... | @Test
public void shouldApplyUndoableMultiParamAggregateFunctions() {
when(func1.convertToInput(any())).thenAnswer(
(invocation) -> {
List<?> inputs = invocation.getArgument(0, List.class);
return Pair.of(inputs.get(0), inputs.get(1));
}
);
when(func1.ge... |
@Override
public ManageSnapshots replaceTag(String name, long snapshotId) {
updateSnapshotReferencesOperation().replaceTag(name, snapshotId);
return this;
} | @TestTemplate
public void testReplaceTag() {
table.newAppend().appendFile(FILE_A).commit();
long snapshotId = table.currentSnapshot().snapshotId();
table.manageSnapshots().createTag("tag1", snapshotId).commit();
// Create a new snapshot and replace the tip of branch1 to be the new snapshot
table.n... |
@Override
public <U> ParSeqBasedCompletionStage<U> thenApply(Function<? super T, ? extends U> fn)
{
return nextStageByComposingTask(_task.map("thenApply", fn::apply));
} | @Test
public void testThenApply_unFinish() throws Exception
{
CountDownLatch waitLatch = new CountDownLatch(1);
CompletionStage<String> stage2 = createTestStage(TESTVALUE1, 200).thenApply(v -> {
waitLatch.countDown();
return TESTVALUE2;
});
assertFalse(waitLatch.await(100, TimeUnit.MILLI... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testCallSingle() {
run(
"def first = karate.callSingle('uuid.js')",
"def second = karate.callSingle('uuid.js')"
);
matchVar("first", get("second"));
} |
public String decrypt(String encryptedText) {
Matcher matcher = ENCRYPTED_PATTERN.matcher(encryptedText);
if (matcher.matches()) {
Cipher cipher = ciphers.get(matcher.group(1).toLowerCase(Locale.ENGLISH));
if (cipher != null) {
return cipher.decrypt(matcher.group(2));
}
}
retur... | @Test
public void should_notDecryptText_whenBadBraceSyntax(){
Encryption encryption = new Encryption(null);
assertThat(encryption.decrypt("}xxx{Zm9v")).isEqualTo("}xxx{Zm9v");
assertThat(encryption.decrypt("}dcd}59LK")).isEqualTo("}dcd}59LK");
assertThat(encryption.decrypt("}rrrRg6")).isEqualTo("}rrrR... |
public static IndicesBlockStatus parseBlockSettings(final GetSettingsResponse settingsResponse) {
IndicesBlockStatus result = new IndicesBlockStatus();
final ImmutableOpenMap<String, Settings> indexToSettingsMap = settingsResponse.getIndexToSettings();
final String[] indicesInResponse = indexToS... | @Test
public void noBlockedIndicesIdentifiedIfEmptyResponseParsed() {
GetSettingsResponse emptyResponse = new GetSettingsResponse(ImmutableOpenMap.of(), ImmutableOpenMap.of());
final IndicesBlockStatus indicesBlockStatus = BlockSettingsParser.parseBlockSettings(emptyResponse);
assertNotNull(... |
@NonNull
@Override
public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException {
return Stapler.lookupConverter(target)
.convert(
target,
context.getSecretSourceResolver()
... | @Test
public void _int_env_default() throws Exception {
Configurator c = registry.lookupOrFail(Integer.class);
final Object value = c.configure(new Scalar("${ENV_FOR_TEST:-123}"), context);
assertEquals(123, value);
} |
@SuppressWarnings("unchecked")
public String uploadFile(
String parentPath,
String name,
InputStream inputStream,
String mediaType,
Date modified,
String description)
throws IOException, InvalidTokenException, DestinationMemoryFullException {
String url;
try {
U... | @Test
public void testUploadFileTokenExpired() throws Exception {
when(credentialFactory.refreshCredential(credential))
.then(
(InvocationOnMock invocation) -> {
final Credential cred = invocation.getArgument(0);
cred.setAccessToken("acc1");
return cre... |
public static boolean canDrop(
FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) {
Objects.requireNonNull(pred, "pred cannnot be null");
Objects.requireNonNull(columns, "columns cannnot be null");
return pred.accept(new DictionaryFilter(columns, dictionarie... | @Test
public void testNotEqBinary() throws Exception {
BinaryColumn sharp = binaryColumn("single_value_field");
BinaryColumn sharpAndNull = binaryColumn("optional_single_value_field");
BinaryColumn b = binaryColumn("binary_field");
assertTrue(
"Should drop block with only the excluded value",... |
public static String downloadString(String url, String customCharsetName) {
return downloadString(url, CharsetUtil.charset(customCharsetName), null);
} | @Test
@Disabled
public void downloadStringTest() {
final String url = "https://www.baidu.com";
// 从远程直接读取字符串,需要自定义编码,直接调用JDK方法
final String content2 = HttpUtil.downloadString(url, CharsetUtil.UTF_8);
Console.log(content2);
} |
@Override
public Map<Errors, Integer> errorCounts() {
Map<Errors, Integer> errorCounts = new HashMap<>();
data.results().forEach(topicResult ->
topicResult.partitions().forEach(partitionResult ->
updateErrorCounts(errorCounts, Errors.forCode(partitionResult.errorCode())))... | @Test
public void testErrorCounts() {
AlterReplicaLogDirsResponseData data = new AlterReplicaLogDirsResponseData()
.setResults(asList(
new AlterReplicaLogDirTopicResult()
.setTopicName("t0")
.setPartition... |
public static HiveColumnHandle rowIdColumnHandle()
{
return new HiveColumnHandle(ROW_ID_COLUMN_NAME, ROW_ID_TYPE, ROW_ID_TYPE_SIGNATURE, ROW_ID_COLUMN_INDEX, SYNTHESIZED, Optional.empty(), ImmutableList.of(), Optional.empty());
} | @Test
public void testRowIdIsSynthesized()
{
HiveColumnHandle rowIdColumn = HiveColumnHandle.rowIdColumnHandle();
assertEquals(rowIdColumn.getColumnType(), SYNTHESIZED);
} |
public abstract ResponseType getResponseType(); | @Test(dataProvider = "provideDynamicallyDeterminedResponseTypeData")
public void testEnvelopeDynamicallyDeterminedResponseType(RestLiResponseEnvelope responseEnvelope, ResponseType expectedResponseType)
{
Assert.assertEquals(responseEnvelope.getResponseType(), expectedResponseType);
} |
protected final void safeRegister(final Class type, final Serializer serializer) {
safeRegister(type, createSerializerAdapter(serializer));
} | @Test(expected = IllegalStateException.class)
public void testSafeRegister_alreadyRegisteredType() {
abstractSerializationService.safeRegister(StringBuffer.class, new StringBufferSerializer(true));
abstractSerializationService.safeRegister(StringBuffer.class, new TheOtherGlobalSerializer(true));
... |
public void load(ScannerReport.Metadata metadata) {
if (delegate != null) {
delegate.load(metadata);
} else if (hasBranchProperties(metadata)) {
throw MessageException.of("Current edition does not support branch feature");
} else {
metadataHolder.setBranch(new DefaultBranchImpl(defaultBran... | @Test
public void regular_analysis_of_project_is_enabled_if_delegate_is_absent() {
ScannerReport.Metadata metadata = ScannerReport.Metadata.newBuilder()
.build();
DefaultBranchNameResolver branchNameResolver = mock(DefaultBranchNameResolver.class);
when(branchNameResolver.getEffectiveMainBranchName(... |
public static Map<String, Object> compare(byte[] baselineImg, byte[] latestImg, Map<String, Object> options,
Map<String, Object> defaultOptions) throws MismatchException {
boolean allowScaling = toBool(defaultOptions.get("allowScaling"));
ImageComparison im... | @Test
void testScale() {
Map<String, Object> result = ImageComparison.compare(R_1x1_IMG, R_2x2_IMG, opts(), opts("allowScaling", true));
assertEquals(0.0, result.get("mismatchPercentage"));
} |
public String msg(String msg, Object... args) {
LogMessage l = new LogMessage();
l.kvs = this.kvs;
return l.setMsgString(msg, args);
} | @Test
public void testMsgShouldContainsMessageAndThrowableMessage() {
final String message = logMessage.msg(MESSAGE, new Throwable(THROWABLE_MESSAGE));
assertNotNull(message);
assertTrue(message.contains(MESSAGE));
assertTrue(message.contains(THROWABLE_MESSAGE));
} |
public static double minimize(DifferentiableMultivariateFunction func, double[] x, double gtol, int maxIter) {
if (gtol <= 0.0) {
throw new IllegalArgumentException("Invalid gradient tolerance: " + gtol);
}
if (maxIter <= 0) {
throw new IllegalArgumentException("Invalid ... | @Test
public void testLBFGS() {
System.out.println("L-BFGS");
double[] x = new double[100];
for (int j = 1; j <= x.length; j += 2) {
x[j - 1] = -1.2;
x[j] = 1.2;
}
double result = BFGS.minimize(func, 5, x, 1E-5, 500);
System.out.println(Array... |
public static String toJsonString(Pipeline pipeline, ConfigContext ctx) {
final PipelineJsonRenderer visitor = new PipelineJsonRenderer(ctx);
pipeline.traverseTopologically(visitor);
return visitor.jsonBuilder.toString();
} | @Test
public void testEmptyPipeline() {
SamzaPipelineOptions options = PipelineOptionsFactory.create().as(SamzaPipelineOptions.class);
options.setRunner(SamzaRunner.class);
Pipeline p = Pipeline.create(options);
final Map<PValue, String> idMap = PViewToIdMapper.buildIdMap(p);
final Set<String> no... |
@Udf
public <T> boolean contains(
@UdfParameter final List<T> array,
@UdfParameter final T val
) {
return array != null && array.contains(val);
} | @Test
public void shouldFindStringInList() {
assertTrue(udf.contains(Arrays.asList("abc", "bd", "DC"), "DC"));
assertFalse(udf.contains(Arrays.asList("abc", "bd", "DC"), "dc"));
assertFalse(udf.contains(Arrays.asList("abc", "bd", "1"), 1));
} |
@Override
public int read(final byte[] b) throws IOException {
return this.read(b, 0, b.length);
} | @Test
public void testEncryptDecryptWithContentSizeMultipleOfEncryptingBufferSize() throws Exception {
final byte[] content = RandomUtils.nextBytes(1024 * 1024);
final ByteArrayInputStream plain = new ByteArrayInputStream(content);
final PlainFileKey key = Crypto.generateFileKey(PlainFileKey... |
protected boolean closeFile( String filename ) {
try {
data.getFileStreamsCollection().closeFile( filename );
} catch ( Exception e ) {
logError( "Exception trying to close file: " + e.toString() );
setErrors( 1 );
return false;
}
return true;
} | @Test
public void testCloseFileDataOutIsNotNullCase() {
textFileOutput =
new TextFileOutput( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta,
stepMockHelper.trans );
textFileOutput.data = mock( TextFileOutputData.class );
textFileOutput.data.out =... |
@Description("compute xxhash64 hash")
@ScalarFunction
@SqlType(StandardTypes.VARBINARY)
public static Slice xxhash64(@SqlType(StandardTypes.VARBINARY) Slice slice)
{
Slice hash = Slices.allocate(Long.BYTES);
hash.setLong(0, Long.reverseBytes(XxHash64.hash(slice)));
return hash;
... | @Test
public void testXxhash64()
{
assertFunction("xxhash64(CAST('' AS VARBINARY))", VARBINARY, sqlVarbinaryHex("EF46DB3751D8E999"));
assertFunction("xxhash64(CAST('hashme' AS VARBINARY))", VARBINARY, sqlVarbinaryHex("F9D96E0E1165E892"));
} |
StreamsProducer streamsProducerForTask(final TaskId taskId) {
return activeTaskCreator.streamsProducerForTask(taskId);
} | @Test
public void shouldCloseActiveTasksAndPropagateExceptionsOnCleanShutdownWithExactlyOnceV1() {
when(activeTaskCreator.streamsProducerForTask(any())).thenReturn(mock(StreamsProducer.class));
shouldCloseActiveTasksAndPropagateExceptionsOnCleanShutdown(ProcessingMode.EXACTLY_ONCE_ALPHA);
} |
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI.
public long parse(final String text) {
final String date;
final String time;
final String timezone;
if (text.contains("T")) {
date = text.substring(0, text.indexOf('T'));
final String withTimezone = text.substring(text.i... | @Test
public void shouldParseYearMonth() {
// When:
assertThat(parser.parse("2020-02"), is(fullParse("2020-02-01T00:00:00.000+0000")));
} |
@Override
public Configuration toConfiguration(CommandLine commandLine) throws FlinkException {
final Configuration resultingConfiguration = super.toConfiguration(commandLine);
if (commandLine.hasOption(addressOption.getOpt())) {
String addressWithPort = commandLine.getOptionValue(addre... | @Test
void testCommandLineMaterialization() throws Exception {
final String hostname = "home-sweet-home";
final String urlPath = "/some/other/path/index.html";
final int port = 1234;
final String[] args = {"-m", hostname + ':' + port + urlPath};
final AbstractCustomCommandLi... |
@Override
protected SchemaTransform from(BigQueryFileLoadsWriteSchemaTransformConfiguration configuration) {
return new BigQueryWriteSchemaTransform(configuration);
} | @Test
public void testToWrite() {
List<
Pair<
BigQueryFileLoadsWriteSchemaTransformConfiguration.Builder,
BigQueryIO.Write<TableRow>>>
cases =
Arrays.asList(
Pair.of(
BigQueryFileLoadsWriteSchemaTransformConfigurat... |
@Override
public YamlShardingAutoTableRuleConfiguration swapToYamlConfiguration(final ShardingAutoTableRuleConfiguration data) {
YamlShardingAutoTableRuleConfiguration result = new YamlShardingAutoTableRuleConfiguration();
result.setLogicTable(data.getLogicTable());
result.setActualDataSourc... | @Test
void assertSwapToYamlConfiguration() {
YamlShardingAutoTableRuleConfigurationSwapper swapper = new YamlShardingAutoTableRuleConfigurationSwapper();
YamlShardingAutoTableRuleConfiguration actual = swapper.swapToYamlConfiguration(createShardingAutoTableRuleConfiguration());
assertThat(ac... |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testEntrySetByPatternTTL() {
RMapCacheNative<String, String> map = redisson.getMapCacheNative("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200", Duration.ofMinutes(1));
map.put("30", "300");
assertThat(map.entrySet("?0")).containsEx... |
public static boolean isEditionBundled(Plugin plugin) {
return SONARSOURCE_ORGANIZATION.equalsIgnoreCase(plugin.getOrganization())
&& Arrays.stream(SONARSOURCE_COMMERCIAL_LICENSES).anyMatch(s -> s.equalsIgnoreCase(plugin.getLicense()));
} | @Test
public void isEditionBundled_on_Plugin_returns_false_for_license_Commercial_and_non_SonarSource_organization() {
Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("Commercial"));
assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse();
} |
@Override
public List<Feature> get() {
List<URI> featurePaths = featureOptions.getFeaturePaths();
List<Feature> features = loadFeatures(featurePaths);
if (features.isEmpty()) {
if (featurePaths.isEmpty()) {
log.warn(() -> "Got no path to feature directory or featu... | @Test
void logs_message_if_no_feature_paths_are_given(LogRecordListener logRecordListener) {
Options featureOptions = Collections::emptyList;
FeaturePathFeatureSupplier supplier = new FeaturePathFeatureSupplier(classLoader, featureOptions, parser);
supplier.get();
assertThat(logReco... |
@Override
public void add(String field, String value, Map<String, String[]> data) {
if (! include(field, value)) {
return;
}
if (ALWAYS_SET_FIELDS.contains(field)) {
setAlwaysInclude(field, value, data);
return;
} else if (ALWAYS_ADD_FIELDS.contain... | @Test
public void testMaxFieldValues() throws Exception {
Metadata metadata = filter(100, 10000, 10000, 3, null, true);
for (int i = 0; i < 10; i++) {
metadata.add(TikaCoreProperties.SUBJECT, "ab");
}
assertEquals(3, metadata.getValues(TikaCoreProperties.SUBJECT).length);... |
@Override
public String toString() {
return String.format("Request [%s %s: %s headers and %s]", method, url,
headers == null ? "without" : "with " + headers,
charset == null ? "no charset" : "charset " + charset);
} | @Test
void testToString() throws Exception {
assertThat(requestKey.toString()).startsWith("Request [GET a: ");
assertThat(requestKey.toString()).contains(" with my-header=[val] ", " UTF-16]");
} |
@Udf
public <T extends Comparable<? super T>> T arrayMin(@UdfParameter(
description = "Array of values from which to find the minimum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldReturnNullForListOfNullInput() {
final List<Integer> input = Arrays.asList(null, null, null);
assertThat(udf.arrayMin(input), is(nullValue()));
} |
static Object parseValue( String key, String value, Class<?> valueType )
throws IllegalArgumentException
{
return parseValue( key, value, valueType, null, v -> v, Collections.emptyList() );
} | @Test
void parseValue() {
assertEquals( null, UIDefaultsLoader.parseValue( "dummy", "null", null ) );
assertEquals( false, UIDefaultsLoader.parseValue( "dummy", "false", null ) );
assertEquals( true, UIDefaultsLoader.parseValue( "dummy", "true", null ) );
assertEquals( "hello", UIDefaultsLoader.parseValue( "d... |
@Override
public void refreshAll() {
// refresh all configs here
getApplication().ifPresent(ApplicationConfig::refresh);
getMonitor().ifPresent(MonitorConfig::refresh);
getMetrics().ifPresent(MetricsConfig::refresh);
getTracing().ifPresent(TracingConfig::refresh);
get... | @Test
void testRefreshAll() {
configManager.refreshAll();
moduleConfigManager.refreshAll();
} |
@VisibleForTesting
static String formatTimestamp(Long timestampMicro) {
// timestampMicro is in "microseconds since epoch" format,
// e.g., 1452062291123456L means "2016-01-06 06:38:11.123456 UTC".
// Separate into seconds and microseconds.
long timestampSec = timestampMicro / 1_000_000;
long micr... | @Test
public void testFormatTimestampLeadingZeroesOnMicros() {
assertThat(
BigQueryAvroUtils.formatTimestamp(1452062291000456L),
equalTo("2016-01-06 06:38:11.000456 UTC"));
} |
@Override
public int getHoldability() {
return 0;
} | @Test
void assertGetHoldability() {
assertThat(connection.getHoldability(), is(0));
} |
@Override
public void write(int b) {
ensureAvailable(1);
buffer[pos++] = (byte) (b);
} | @Test(expected = IndexOutOfBoundsException.class)
public void testWriteForBOffLen_negativeOff() {
out.write(TEST_DATA, -1, 3);
} |
public static Uuid fromString(String str) {
if (str.length() > 24) {
throw new IllegalArgumentException("Input string with prefix `"
+ str.substring(0, 24) + "` is too long to be decoded as a base64 UUID");
}
ByteBuffer uuidBytes = ByteBuffer.wrap(Base64.getUrlDecode... | @Test
public void testFromStringWithInvalidInput() {
String oversizeString = Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[32]);
assertThrows(IllegalArgumentException.class, () -> Uuid.fromString(oversizeString));
String undersizeString = Base64.getUrlEncoder().withoutPadd... |
public static String getPrettyStringMs(long timestampMs) {
StringBuilder builder = new StringBuilder();
printTimeMs(timestampMs, builder);
return builder.toString();
} | @Test
public void testGetPrettyStringMs() {
// 6hour1min
Assert.assertEquals(DebugUtil.getPrettyStringMs(21660222), "6h1m");
// 1min222ms
Assert.assertEquals(DebugUtil.getPrettyStringMs(60222), "1m");
// 2s222ms
Assert.assertEquals(DebugUtil.getPrettyStringMs(2222),... |
@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 constant_function() {
int constant = 2;
issue.setGap(null);
rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, constant + "min"));
assertThat(underTest.calculate(issue).toMinutes()).isEqualTo(2);
} |
public static Read<Solace.Record> read() {
return new Read<Solace.Record>(
Read.Configuration.<Solace.Record>builder()
.setTypeDescriptor(TypeDescriptor.of(Solace.Record.class))
.setParseFn(SolaceRecordMapper::map)
.setTimestampFn(SENDER_TIMESTAMP_FUNCTION)
.s... | @Test
public void testNoQueueAndTopicSet() {
Read<Record> spec = SolaceIO.read();
assertThrows(IllegalStateException.class, () -> spec.validate(pipeline.getOptions()));
} |
static BytecodeExpression greaterThan(BytecodeExpression left, BytecodeExpression right)
{
checkArgumentTypes(left, right);
OpCode comparisonInstruction;
OpCode noMatchJumpInstruction;
Class<?> type = left.getType().getPrimitiveType();
if (type == int.class) {
c... | @Test
public void testGreaterThan()
throws Exception
{
assertBytecodeExpression(greaterThan(constantInt(3), constantInt(7)), 3 > 7, "(3 > 7)");
assertBytecodeExpression(greaterThan(constantInt(7), constantInt(3)), 7 > 3, "(7 > 3)");
assertBytecodeExpression(greaterThan(consta... |
public static List<String> resolveCompsDependency(Service service) {
List<String> components = new ArrayList<String>();
for (Component component : service.getComponents()) {
int depSize = component.getDependencies().size();
if (!components.contains(component.getName())) {
components.add(comp... | @Test
public void testResolveCompsCircularDependency() {
Service service = createExampleApplication();
List<String> dependencies = new ArrayList<String>();
List<String> dependencies2 = new ArrayList<String>();
dependencies.add("compb");
dependencies2.add("compa");
Component compa = createCompo... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertFloat() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("float")
.dataType("float")
.build();
Column column = XuguTy... |
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener nacosConfigListener = ConcurrentHashMapUtils.computeIfAbsent(
watchListenerMap, listenerKey, k -> createTargetListener(... | @Test
void testAddListener() throws Exception {
CountDownLatch latch = new CountDownLatch(4);
TestListener listener1 = new TestListener(latch);
TestListener listener2 = new TestListener(latch);
TestListener listener3 = new TestListener(latch);
TestListener listener4 = new Tes... |
public ResT receive(long timeoutMs) throws IOException {
if (mCompleted) {
return null;
}
if (mCanceled) {
throw new CancelledException(formatErrorMessage("Stream is already canceled."));
}
long startMs = System.currentTimeMillis();
while (true) {
long waitedForMs = System.cur... | @Test
public void receiveAfterResponseArrives() throws Exception {
WriteResponse response = WriteResponse.newBuilder().build();
EXECUTOR.submit(() -> {
try {
// push response after a short period of time
Thread.sleep(SHORT_TIMEOUT);
mResponseObserver.onNext(response);
} cat... |
public SchemaProvider getSchemaProvider() {
if (batch.isPresent() && schemaProvider == null) {
throw new HoodieException("Please provide a valid schema provider class!");
}
return Option.ofNullable(schemaProvider).orElseGet(NullSchemaProvider::getInstance);
} | @Test
public void getSchemaProviderShouldReturnGivenSchemaProvider() {
SchemaProvider schemaProvider = new RowBasedSchemaProvider(null);
final InputBatch<String> inputBatch = new InputBatch<>(Option.of("foo"), null, schemaProvider);
assertSame(schemaProvider, inputBatch.getSchemaProvider());
} |
@Override
public ImmutableSet<E> removed(E e) {
return new PCollectionsImmutableSet<>(underlying().minus(e));
} | @Test
public void testDelegationOfRemoved() {
new PCollectionsHashSetWrapperDelegationChecker<>()
.defineMockConfigurationForFunctionInvocation(mock -> mock.minus(eq(this)), SINGLETON_SET)
.defineWrapperFunctionInvocationAndMockReturnValueTransformation(wrapper -> wrapper.removed(thi... |
@Override
public void start() {
if (isStarted())
return;
try {
ServerSocket socket = getServerSocketFactory().createServerSocket(getPort(), getBacklog(),
getInetAddress());
ServerListener<RemoteReceiverClient> listener = createServerListener(so... | @Test
public void testStartWhenAlreadyStarted() throws Exception {
appender.start();
appender.start();
Assertions.assertEquals(1, runner.getStartCount());
} |
@Override
public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff)
throws IOException, InterruptedException {
IOException lastException = null;
do {
try {
Collection<Metadata> files = FileSystems.match(filePattern).metadata();
LOG.debug(
"Found file(s... | @Test
public void testReadEmpty() throws Exception {
File emptyFile = tmpFolder.newFile("result-000-of-001");
Files.asCharSink(emptyFile, StandardCharsets.UTF_8).write("");
FilePatternMatchingShardedFile shardedFile = new FilePatternMatchingShardedFile(filePattern);
assertThat(shardedFile.readFilesWi... |
public static CA readCA(final String pemFileContent, final String keyPassword) throws CACreationException {
try (var bundleReader = new StringReader(pemFileContent)) {
PEMParser pemParser = new PEMParser(bundleReader);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("... | @Test
void throwsExceptionIfPrivateKeyIsMissing() throws Exception {
assertThatThrownBy(() -> PemCaReader.readCA(PEM_CERT, null))
.isInstanceOf(CACreationException.class)
.hasMessage("No private key supplied in CA bundle!");
} |
public static Path getStagingDir(Cluster cluster, Configuration conf)
throws IOException, InterruptedException {
UserGroupInformation user = UserGroupInformation.getLoginUser();
return getStagingDir(cluster, conf, user);
} | @Test
public void testGetStagingDirWhenShortFileOwnerNameAndFullUserName()
throws IOException, InterruptedException {
Cluster cluster = mock(Cluster.class);
Configuration conf = new Configuration();
String stagingDirOwner = USER_1_SHORT_NAME;
Path stagingPath = mock(Path.class);
UserGroupInf... |
public static boolean isRestSSLAuthenticationEnabled(Configuration sslConfig) {
checkNotNull(sslConfig, "sslConfig");
return isRestSSLEnabled(sslConfig) && sslConfig.get(SSL_REST_AUTHENTICATION_ENABLED);
} | @Test
void checkEnableRestSSLAuthentication() {
// SSL has to be enabled
Configuration noSSLOptions = new Configuration();
noSSLOptions.set(SecurityOptions.SSL_REST_ENABLED, false);
noSSLOptions.set(SecurityOptions.SSL_REST_AUTHENTICATION_ENABLED, true);
assertThat(SecurityOp... |
public static long calculate(final float percentage) {
if (percentage <= 0 || percentage > 1) {
throw new IllegalArgumentException();
}
checkAndScheduleRefresh();
return (long) (maxAvailable() * percentage);
} | @Test
public void testCalculateWhenIllegalPercentage() {
float largerThanOne = 2;
float zero = 0;
float lessThanZero = -1;
assertThrows(IllegalArgumentException.class, () -> MemoryLimitCalculator.calculate(largerThanOne));
assertThrows(IllegalArgumentException.class, () -> Me... |
public Lease acquire() throws Exception {
String path = internals.attemptLock(-1, null, null);
return makeLease(path);
} | @Test
public void testRelease1AtATime() throws Exception {
final Timing timing = new Timing();
final int CLIENT_QTY = 10;
final int MAX = CLIENT_QTY / 2;
final AtomicInteger maxLeases = new AtomicInteger(0);
final AtomicInteger activeQty = new AtomicInteger(0);
final ... |
void placeOrder(Order order) {
sendShippingRequest(order);
} | @Test
void testPlaceOrderShortDuration() throws Exception {
long paymentTime = timeLimits.paymentTime();
long queueTaskTime = timeLimits.queueTaskTime();
long messageTime = timeLimits.messageTime();
long employeeTime = timeLimits.employeeTime();
long queueTime = timeLimits.queueTime();... |
@Nullable
static NotificationTemplate lookupTemplateByLocale(Locale locale,
Map<String, Optional<NotificationTemplate>> map) {
return LanguageUtils.computeLangFromLocale(locale).stream()
// reverse order to ensure that the variant is the first element and the default
// is th... | @Test
void lookupTemplateByLocaleTest() {
Map<String, Optional<NotificationTemplate>> map = new HashMap<>();
map.put("zh_CN", Optional.of(createNotificationTemplate("zh_CN-template")));
map.put("zh", Optional.of(createNotificationTemplate("zh-template")));
map.put("default", Optional... |
@Udf
public <T> List<T> remove(
@UdfParameter(description = "Array of values") final List<T> array,
@UdfParameter(description = "Value to remove") final T victim) {
if (array == null) {
return null;
}
return array.stream()
.filter(el -> !Objects.equals(el, victim))
.coll... | @Test
public void shouldRetainNulls() {
final List<String> input1 = Arrays.asList(null, "foo");
final String input2 = "foo";
final List<String> result = udf.remove(input1, input2);
assertThat(result, contains((String) null));
} |
@Override
public MediaType detect(ZipFile zipFile, TikaInputStream tis) throws IOException {
MediaType mt = detectIWork18(zipFile);
if (mt != null) {
return mt;
}
mt = detectIWork13(zipFile);
if (mt != null) {
return mt;
}
return detect... | @Test
public void testDetectKeynote13() throws Exception {
String testFile = "/test-documents/testKeynote2013.detect";
IWorkDetector detector = new IWorkDetector();
try (TikaInputStream tis = TikaInputStream.get(getResourceAsStream(testFile));
ZipFile zipFile = ZipFile.build... |
@Udf
public Integer length(@UdfParameter final String jsonArray) {
if (jsonArray == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonArray);
if (node.isMissingNode() || !node.isArray()) {
return null;
}
return node.size();
} | @Test(expected = KsqlFunctionException.class)
public void shouldThrowForInvalidJson() {
udf.length("abc");
} |
public static FindAll findAll(String regex) {
return findAll(Pattern.compile(regex));
} | @Test
@Category(NeedsRunner.class)
public void testFindAllGroups() {
PCollection<List<String>> output =
p.apply(Create.of("aj", "xjx", "yjy", "zjz")).apply(Regex.findAll("([xyz])j([xyz])"));
PAssert.that(output)
.containsInAnyOrder(
Arrays.asList("xjx", "x", "x"),
Ar... |
void commitClusterState(ClusterStateChange newState, Address initiator, UUID txnId) {
commitClusterState(newState, initiator, txnId, false);
} | @Test(expected = NullPointerException.class)
public void test_changeLocalClusterState_nullState() throws Exception {
clusterStateManager.commitClusterState(null, newAddress(), TXN);
} |
@Override
public void close() {
} | @Test
public void shouldSucceed_gapDetectedLocal_noRetry()
throws ExecutionException, InterruptedException {
// Given:
final AtomicReference<Set<KsqlNode>> nodes = new AtomicReference<>(
ImmutableSet.of(ksqlNodeLocal, ksqlNodeRemote));
final PushRouting routing = new PushRouting(sqr -> nodes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.