focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void refreshAdminAcls() throws IOException {
UserGroupInformation user = checkAcls("refreshAdminAcls");
Configuration conf = createConf();
adminAcl = new AccessControlList(conf.get(JHAdminConfig.JHS_ADMIN_ACL,
JHAdminConfig.DEFAULT_JHS_ADMIN_ACL));
HSAuditLogger.logSuccess(us... | @Test
public void testRefreshAdminAcls() throws Exception {
// Setting current user to admin acl
conf.set(JHAdminConfig.JHS_ADMIN_ACL, UserGroupInformation.getCurrentUser()
.getUserName());
String[] args = new String[1];
args[0] = "-refreshAdminAcls";
hsAdminClient.run(args);
// Now I... |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterministicUnorderedMap() {
assertNonDeterministic(
AvroCoder.of(UnorderedMapClass.class),
reasonField(
UnorderedMapClass.class,
"mapField",
"java.util.Map<java.lang.String, java.lang.String> "
+ "may not be deterministica... |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void testMetadataVersionMatchesKafkaVersionWithDefaultKafkaVersion() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withMetadataVersion(KafkaVersionTestUtils.LATEST_METADATA_VERSION)
.endKafka()
... |
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
if (notificationExtension.canHandlePlugin(pluginDescriptor.id())) {
try {
notificationPluginRegistry.registerPlugin(pluginDescriptor.id());
List<String> notificationsInterestedIn = notificat... | @Test
public void shouldRegisterPluginInterestsOnPluginLoad() {
NotificationPluginRegistrar notificationPluginRegistrar = new NotificationPluginRegistrar(pluginManager, notificationExtension, notificationPluginRegistry);
notificationPluginRegistrar.pluginLoaded(GoPluginDescriptor.builder().id(PLUGI... |
public static Field[] getAllFields(final Class<?> targetClazz) {
if (targetClazz == Object.class || targetClazz.isInterface()) {
return EMPTY_FIELD_ARRAY;
}
// get from the cache
Field[] fields = CLASS_FIELDS_CACHE.get(targetClazz);
if (fields != null) {
... | @Test
public void testGetAllFields() {
// TestClass
this.testGetAllFieldsInternal(TestClass.class, "f1", "f2");
// TestSuperClass
this.testGetAllFieldsInternal(TestSuperClass.class, "f2");
// EmptyClass
this.testGetAllFieldsInternal(EmptyClass.class);
// TestI... |
public byte[] remove() throws Exception {
byte[] bytes = internalElement(true, null);
if (bytes == null) {
throw new NoSuchElementException();
}
return bytes;
} | @Test
public void testRemova1() throws Exception {
CuratorFramework clients[] = null;
try {
String dir = "/testRemove1";
final int num_clients = 1;
clients = new CuratorFramework[num_clients];
SimpleDistributedQueue queueHandles[] = new SimpleDistribut... |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void parseAEqB() {
String query = "a = b";
List<String> list = parser.toPrefix(query);
assertEquals(Arrays.asList("a", "b", "="), list);
} |
static double atan2(double y, double x) {
// kludge to prevent 0/0 condition
double absY = Math.abs(y) + 1e-10;
double r, angle;
if (x < 0.0) {
r = (x + absY) / (absY - x);
angle = PI3_4;
} else {
r = (x - absY) / (x + absY);
angle ... | @Test
public void testAtan2() {
// assertEquals(0, AngleCalc.atan2(0, 0), 1e-4);
// assertEquals(0, AngleCalc.atan2(-0.002, 0), 1e-4);
assertEquals(45, AngleCalc.atan2(5, 5) * 180 / Math.PI, 1e-2);
assertEquals(-45, AngleCalc.atan2(-5, 5) * 180 / Math.PI, 1e-2);
assertEquals(... |
@Override
public void run(Runnable task) {
long startNanos = System.nanoTime();
boolean publishCurrentTask = publishCurrentTask();
if (publishCurrentTask) {
currentTask = task;
}
try {
task.run();
} finally {
if (publishCurrentTa... | @Test
public void runTask() {
final AtomicLong counter = new AtomicLong();
operationRunner.run(() -> counter.incrementAndGet());
assertEquals(1, counter.get());
} |
public Resource getMinimumCapacityInInterval(ReservationInterval interval) {
Resource minCapacity =
Resource.newInstance(Integer.MAX_VALUE, Integer.MAX_VALUE);
long start = interval.getStartTime();
long end = interval.getEndTime();
NavigableMap<Long, Resource> capacityRange =
getRangeOve... | @Test
public void testGetMinimumCapacityInInterval() {
long[] timeSteps = { 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L };
int[] alloc = { 2, 5, 7, 10, 3, 4, 0, 8 };
RLESparseResourceAllocation rleSparseVector = ReservationSystemTestUtil
.generateRLESparseResourceAllocation(alloc, timeSteps);
LOG.info(rleS... |
ObjectFactory loadObjectFactory() {
Class<? extends ObjectFactory> objectFactoryClass = options.getObjectFactoryClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class, classLoader);
if (objectFactoryClass... | @Test
void test_case_4() {
io.cucumber.core.backend.Options options = () -> null;
ObjectFactoryServiceLoader loader = new ObjectFactoryServiceLoader(
() -> new ServiceLoaderTestClassLoader(ObjectFactory.class,
DefaultObjectFactory.class,
OtherFactory.class... |
@Override
public void write(T record) {
recordConsumer.startMessage();
try {
messageWriter.writeTopLevelMessage(record);
} catch (RuntimeException e) {
Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record;
LOG.error("Cannot write message... | @Test
public void testProto3WrappedMessageUnwrappedRoundTrip() throws Exception {
TestProto3.WrappedMessage.Builder msg = TestProto3.WrappedMessage.newBuilder();
msg.setWrappedDouble(DoubleValue.of(0.577));
msg.setWrappedFloat(FloatValue.of(3.1415f));
msg.setWrappedInt64(Int64Value.of(1_000_000_000L *... |
public ChannelFuture handshake(Channel channel, FullHttpRequest req) {
return handshake(channel, req, null, channel.newPromise());
} | @Test
public void testWebSocketServerHandshakeException() {
WebSocketServerHandshaker serverHandshaker = newHandshaker("ws://example.com/chat",
"chat", WebSocketDecoderConfig.DEFAULT);
FullHttpRequest request = new DefaultFullHttpRe... |
public static BuildInfo getBuildInfo() {
if (Overrides.isEnabled()) {
// never use cache when override is enabled -> we need to re-parse everything
Overrides overrides = Overrides.fromProperties();
return getBuildInfoInternalVersion(overrides);
}
return BUILD... | @Test
public void testOverrideBuildVersion() {
System.setProperty(HAZELCAST_INTERNAL_OVERRIDE_VERSION, "99.99.99");
BuildInfo buildInfo = BuildInfoProvider.getBuildInfo();
assertEquals("99.99.99", buildInfo.getVersion());
System.clearProperty(HAZELCAST_INTERNAL_OVERRIDE_VERSION);
... |
@Override
public ByteBuf slice() {
return newSharedLeakAwareByteBuf(super.slice());
} | @Test
public void testWrapSlice2() {
assertWrapped(newBuffer(8).slice(0, 1));
} |
@Override
public double p(int k) {
if (k <= 0) {
return 0.0;
} else {
return Math.pow(1 - p, k - 1) * p;
}
} | @Test
public void testP() {
System.out.println("p");
ShiftedGeometricDistribution instance = new ShiftedGeometricDistribution(0.3);
instance.rand();
assertEquals(0.3, instance.p(1), 1E-6);
assertEquals(0.21, instance.p(2), 1E-6);
assertEquals(0.147, instance.p(3), 1E-... |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldThrowOnTimestampTimeLEQ() {
// Given:
final ComparisonExpression compExp = new ComparisonExpression(
Type.LESS_THAN_OR_EQUAL,
TIMESTAMPCOL,
TIMECOL
);
// Then:
final Exception e = assertThrows(KsqlException.class, () -> sqlToJavaVisitor.process(comp... |
public static Builder builder() {
return new Builder();
} | @Test
public void testRoundTripSerdeWithV2TableMetadata() throws Exception {
String tableMetadataJson = readTableMetadataInputFile("TableMetadataV2Valid.json");
TableMetadata v2Metadata =
TableMetadataParser.fromJson(TEST_METADATA_LOCATION, tableMetadataJson);
// Convert the TableMetadata JSON fro... |
@Override
public RestResponse<KsqlEntityList> makeKsqlRequest(
final URI serverEndPoint,
final String sql,
final Map<String, ?> requestProperties) {
final KsqlTarget target = sharedClient
.target(serverEndPoint);
return getTarget(target)
.postKsqlRequest(sql, requestProperti... | @Test
public void shouldSetAuthHeaderOnTarget() {
// When:
client.makeKsqlRequest(SERVER_ENDPOINT, "Sql", ImmutableMap.of());
// Then:
verify(target).authorizationHeader(AUTH_HEADER);
} |
void handleLine(final String line) {
final String trimmedLine = Optional.ofNullable(line).orElse("").trim();
if (trimmedLine.isEmpty()) {
return;
}
handleStatements(trimmedLine);
} | @Test
public void shouldDescribeVariadicObjectAggregateFunction() {
final String expectedSummary =
"Name : OBJ_COL_ARG\n"
+ "Author : Confluent\n"
+ "Overview : Returns an array of rows where all the given columns are non-null.\n"
... |
static void checkValidCollectionName(String databaseName, String collectionName) {
String fullCollectionName = databaseName + "." + collectionName;
if (collectionName.length() < MIN_COLLECTION_NAME_LENGTH) {
throw new IllegalArgumentException("Collection name cannot be empty.");
}
if (fullCollecti... | @Test
public void testCheckValidCollectionNameThrowsErrorWhenNameIsTooLong() {
assertThrows(
IllegalArgumentException.class,
() -> checkValidCollectionName(StringUtils.repeat("a", 1), StringUtils.repeat("b", 100)));
assertThrows(
IllegalArgumentException.class,
() -> checkValid... |
@Override
public void build(T instance) {
super.build(instance);
if (!StringUtils.isEmpty(version)) {
instance.setVersion(version);
}
if (!StringUtils.isEmpty(group)) {
instance.setGroup(group);
}
if (deprecated != null) {
instance... | @Test
void build() {
ProtocolConfig protocol = new ProtocolConfig();
ServiceBuilder builder = new ServiceBuilder();
builder.version("version")
.group("group")
.deprecated(true)
.delay(1000)
.export(false)
.weigh... |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
try {
return serializer.serialize(topic, value == null ? null : value.toString());
} catch (SerializationException e) {
throw new DataException("Failed to serialize to a string: ", e);
... | @Test
public void testNullToBytes() {
assertNull(converter.fromConnectData(TOPIC, Schema.OPTIONAL_STRING_SCHEMA, null));
} |
public static Builder builder(Credentials credentials) {
return new Builder(credentials);
} | @Test
public void testCreateWithCredentials() {
Credentials credentials = mock(Credentials.class);
ClassicTemplateClient.builder(credentials).build();
// Lack of exception is all we really can test
} |
@Override
public BackgroundException map(final GenericException e) {
final StringBuilder buffer = new StringBuilder();
this.append(buffer, e.getMessage());
final StatusLine status = e.getHttpStatusLine();
if(null != status) {
this.append(buffer, String.format("%d %s", sta... | @Test
public void testMap() {
assertEquals("Message. 500 reason. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(
new GenericException("message", null, new StatusLine() {
@Override
public ProtocolVersion ge... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_empty_collection() {
List<?> original = new ArrayList<>();
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
} |
public double[] shap(DataFrame data) {
// Binds the formula to the data frame's schema in case that
// it is different from that of training data.
formula.bind(data.schema());
return shap(data.stream().parallel());
} | @Test
public void testShap() {
MathEx.setSeed(19650218); // to get repeatable results.
GradientTreeBoost model = GradientTreeBoost.fit(Iris.formula, Iris.data, 100, 20, 6, 5, 0.05, 0.7);
String[] fields = model.schema().names();
double[] importance = model.importance();
doubl... |
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final SelectionParameters other = (SelectionParamet... | @Test
public void testEqualsSameInstance() {
List<String> qualifyingNames = Arrays.asList( "language", "german" );
TypeMirror resultType = new TestTypeMirror( "resultType" );
List<TypeMirror> qualifiers = new ArrayList<>();
qualifiers.add( new TestTypeMirror( "org.mapstruct.test.Some... |
public int size() {
return versionWindow.length;
} | @Test
public void testSize() {
VersionTally instance = new VersionTally(TESTNET);
assertEquals(TESTNET.getMajorityWindow(), instance.size());
} |
@Override
protected double maintain() {
List<Node> provisionedSnapshot;
try {
NodeList nodes;
// Host and child nodes are written in separate transactions, but both are written while holding the
// unallocated lock. Hold the unallocated lock while reading nodes to... | @Test
public void respects_exclusive_allocation() {
tester = new DynamicProvisioningTester(Cloud.builder().name(CloudName.AWS).dynamicProvisioning(true).allowHostSharing(false).build(), new MockNameResolver());
NodeResources resources1 = new NodeResources(24, 64, 100, 10);
setPreprovisionCap... |
@Override
protected void init() throws ServiceException {
LOG.info("Using FileSystemAccess JARs version [{}]", VersionInfo.getVersion());
String security = getServiceConfig().get(AUTHENTICATION_TYPE, "simple").trim();
if (security.equals("kerberos")) {
String defaultName = getServer().getName();
... | @Test
@TestDir
public void serviceHadoopConfCustomDir() throws Exception {
String dir = TestDirHelper.getTestDir().getAbsolutePath();
String hadoopConfDir = new File(dir, "confx").getAbsolutePath();
new File(hadoopConfDir).mkdirs();
String services = StringUtils.join(",",
Arrays.asList(Instrum... |
@ExecuteOn(TaskExecutors.IO)
@Get
@Operation(tags = {"KV"}, summary = "List all keys for a namespace")
public List<KVEntry> list(
@Parameter(description = "The namespace id") @PathVariable String namespace
) throws IOException, URISyntaxException {
return kvStore(namespace).list();
} | @SuppressWarnings("unchecked")
@Test
void list() throws IOException {
Instant before = Instant.now().minusMillis(100);
Instant myKeyExpirationDate = Instant.now().plus(Duration.ofMinutes(5)).truncatedTo(ChronoUnit.MILLIS);
Instant mySecondKeyExpirationDate = Instant.now().plus(Duration.o... |
public static ErrorProneOptions processArgs(Iterable<String> args) {
Preconditions.checkNotNull(args);
ImmutableList.Builder<String> remainingArgs = ImmutableList.builder();
/* By default, we throw an error when an unknown option is passed in, if for example you
* try to disable a check that doesn't m... | @Test
public void malformedOptionThrowsProperException() {
List<String> badArgs =
Arrays.asList(
"-Xep:Foo:WARN:jfkdlsdf", // too many parts
"-Xep:", // no check name
"-Xep:Foo:FJDKFJSD"); // nonexistent severity level
badArgs.forEach(
arg -> {
In... |
public final StringSubject hasMessageThat() {
StandardSubjectBuilder check = check("getMessage()");
if (actual instanceof ErrorWithFacts && ((ErrorWithFacts) actual).facts().size() > 1) {
check =
check.withMessage(
"(Note from Truth: When possible, instead of asserting on the full ... | @Test
public void hasMessageThat_null() {
assertThat(new NullPointerException()).hasMessageThat().isNull();
assertThat(new NullPointerException(null)).hasMessageThat().isNull();
} |
@Override
public String arguments() {
ArrayList<String> args = new ArrayList<>();
if (buildFile != null) {
args.add("-f \"" + FilenameUtils.separatorsToUnix(buildFile) + "\"");
}
if (target != null) {
args.add(target);
}
return StringUtils.jo... | @Test
public void shouldNotSetTargetOnBuilderWhenNotSet() {
assertThat(antTask.arguments(), is(""));
} |
@Override
public DeserializationHandlerResponse handle(
final ProcessorContext context,
final ConsumerRecord<byte[], byte[]> record,
final Exception exception
) {
log.debug(
String.format("Exception caught during Deserialization, "
+ "taskId: %s, topic: %s, partition: %d, o... | @Test
public void shouldReturnContinueForRegularExceptions() {
assertThat(exceptionHandler.handle(context, record, mock(Exception.class)),
equalTo(DeserializationHandlerResponse.CONTINUE));
} |
@Override
public void validate() throws TelegramApiValidationException {
if (inlineQueryId.isEmpty()) {
throw new TelegramApiValidationException("InlineQueryId can't be empty", this);
}
for (InlineQueryResult result : results) {
result.validate();
}
i... | @Test
void testResultsMustBePresent() {
answerInlineQuery.setInlineQueryId("RANDOMEID");
try {
answerInlineQuery.validate();
} catch (TelegramApiValidationException e) {
assertEquals("Results array can't be null", e.getMessage());
}
} |
public static <K, V extends OrderedSPI<?>> Map<K, V> getServices(final Class<V> serviceInterface, final Collection<K> types) {
return getServices(serviceInterface, types, Comparator.naturalOrder());
} | @Test
void assertGetServicesFromCache() {
OrderedInterfaceFixture key = new OrderedInterfaceFixtureImpl();
assertThat(OrderedSPILoader.getServices(OrderedSPIFixture.class, Collections.singleton(key)),
is(OrderedSPILoader.getServices(OrderedSPIFixture.class, Collections.singleton(key)... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(new DefaultPathContainerService().isContainer(file)) {
return PathAttributes.EMPTY;
}
... | @Test
public void testFindMyDrive() throws Exception {
final DriveAttributesFinderFeature f = new DriveAttributesFinderFeature(session, new DriveFileIdProvider(session));
assertEquals(PathAttributes.EMPTY, f.find(DriveHomeFinderService.MYDRIVE_FOLDER));
} |
@Override
public GetApplicationAttemptReportResponse getApplicationAttemptReport(
GetApplicationAttemptReportRequest request)
throws YarnException, IOException {
if (request == null || request.getApplicationAttemptId() == null
|| request.getApplicationAttemptId().getApplicationId() == nul... | @Test
public void testGetApplicationAttemptEmptyRequest()
throws Exception {
LOG.info("Test FederationClientInterceptor: Get ApplicationAttempt Report - Empty.");
// null request1
LambdaTestUtils.intercept(YarnException.class,
"Missing getApplicationAttemptReport request or applicationId " ... |
public CompletableFuture<Result> getTerminationFuture() {
return terminationFuture;
} | @Test
void testShouldShutdownIfRegistrationWithJobManagerFails() throws Exception {
Configuration configuration = createConfiguration();
configuration.set(
TaskManagerOptions.REGISTRATION_TIMEOUT, TimeUtils.parseDuration("10 ms"));
taskManagerRunner = createTaskManagerRunner(... |
public String getJsonPath() {
return getPropertyAsString(JSONPATH);
} | @Test
void testGetJsonPath() {
JSONPathAssertion instance = new JSONPathAssertion();
String expResult = "";
String result = instance.getJsonPath();
assertEquals(expResult, result);
} |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseSpecificOverVarArgsInMiddle() {
// Given:
givenFunctions(
function(EXPECTED, -1, INT, INT, STRING, STRING, STRING, STRING, INT),
function(OTHER, 2, INT, INT, STRING_VARARGS, STRING, STRING, STRING, INT)
);
// When:
final KsqlScalarFunction fun... |
@Override
public String toString() {
return partitionMaps.entrySet().stream()
.flatMap(this::toStrings)
.collect(Collectors.joining(", ", "{", "}"));
} | @Test
public void testToString() {
PartitionMap<String> map = PartitionMap.create(SPECS);
// empty map
assertThat(map.toString()).isEqualTo("{}");
// single entry
map.put(BY_DATA_SPEC.specId(), Row.of("aaa"), "v1");
assertThat(map.toString()).isEqualTo("{data=aaa -> v1}");
// multiple e... |
@VisibleForTesting
List<Image> getCachedBaseImages()
throws IOException, CacheCorruptedException, BadContainerConfigurationFormatException,
LayerCountMismatchException, UnlistedPlatformInManifestListException,
PlatformNotFoundInBaseImageException {
ImageReference baseImage = buildContext... | @Test
public void testGetCachedBaseImages_manifestListCached_partialMatches()
throws InvalidImageReferenceException, IOException, CacheCorruptedException,
UnlistedPlatformInManifestListException, BadContainerConfigurationFormatException,
LayerCountMismatchException, PlatformNotFoundInBaseIma... |
@Override
public int compare(String version1, String version2) {
if(ObjectUtil.equal(version1, version2)) {
return 0;
}
if (version1 == null && version2 == null) {
return 0;
} else if (version1 == null) {// null或""视为最小版本,排在前
return -1;
} else if (version2 == null) {
return 1;
}
return Compar... | @Test
public void versionComparatorTest4() {
int compare = VersionComparator.INSTANCE.compare("1.13.0", "1.12.1c");
assertTrue(compare > 0);
// 自反测试
compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.13.0");
assertTrue(compare < 0);
} |
public static Metric metric(String name) {
return MetricsImpl.metric(name, Unit.COUNT);
} | @Test
public void unusedMetrics() {
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.filter(l -> {
boolean pass = l % 2 == 0;
if (!pass) {
Metrics.metric("dropped"); //retrieve "dropped" counter, but never use it
... |
public static <T> SVM<T> fit(T[] x, MercerKernel<T> kernel) {
return fit(x, kernel, 0.5, 1E-3);
} | @Test
public void testSixClusters() throws Exception {
System.out.println("Six clusters");
CSVFormat format = CSVFormat.Builder.create().setDelimiter(' ').build();
double[][] data = Read.csv(Paths.getTestData("clustering/rem.txt"), format).toArray();
SVM<double[]> model = SVM.fit(da... |
public void addForwardedField(int input, int sourceField, int targetField) {
Map<Integer, FieldSet> fieldMapping;
if (input != 0 && input != 1) {
throw new IndexOutOfBoundsException();
} else if (input == 0) {
fieldMapping = this.fieldMapping1;
} else {
... | @Test
void testAddForwardedFieldsTargetTwice1() {
assertThatThrownBy(
() -> {
DualInputSemanticProperties sp = new DualInputSemanticProperties();
sp.addForwardedField(0, 0, 2);
sp.addForwardedField(0... |
public static GenericRecord rewriteRecord(GenericRecord oldRecord, Schema newSchema) {
GenericRecord newRecord = new GenericData.Record(newSchema);
boolean isSpecificRecord = oldRecord instanceof SpecificRecordBase;
for (Schema.Field f : newSchema.getFields()) {
if (!(isSpecificRecord && isMetadataFie... | @Test
public void testMetadataField() {
GenericRecord rec = new GenericData.Record(new Schema.Parser().parse(EXAMPLE_SCHEMA));
rec.put("_row_key", "key1");
rec.put("non_pii_col", "val1");
rec.put("pii_col", "val2");
rec.put("timestamp", 3.5);
GenericRecord rec1 = HoodieAvroUtils.rewriteRecord(... |
public static String cleanInvalid(String fileName) {
return StrUtil.isBlank(fileName) ? fileName : ReUtil.delAll(FILE_NAME_INVALID_PATTERN_WIN, fileName);
} | @Test
public void cleanInvalidTest(){
String name = FileNameUtil.cleanInvalid("1\n2\n");
assertEquals("12", name);
name = FileNameUtil.cleanInvalid("\r1\r\n2\n");
assertEquals("12", name);
} |
@Override
public String toString() {
return "Route{" +
"customId='" + customId + '\'' +
", exchangesTotal=" + exchangesTotal +
", id='" + id + '\'' +
", totalProcessingTime=" + totalProcessingTime +
", components=" + components +
... | @Test
public void testToString() {
String toString = getInstance().toString();
assertNotNull(toString);
assertTrue(toString.contains("Route"));
} |
@Override
public MastershipRole getRole(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_NULL);
// TODO hard coded to master for now.
return MastershipRole.MASTER;
} | @Test(expected = NullPointerException.class)
public void testGetRoleByNullId() {
manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
DeviceService deviceService = manager.get(virtualNetw... |
public static String stripTrailingSlash(String path) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "path must not be null or empty");
String result = path;
while (!result.endsWith("://") && result.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
return resul... | @Test
void testStripTrailingSlashForRootPathWithTrailingSlash() {
String rootPath = "blobstore://";
String rootPathWithTrailingSlash = rootPath + "/";
assertThat(LocationUtil.stripTrailingSlash(rootPathWithTrailingSlash))
.as("Should be root path")
.isEqualTo(rootPath);
} |
@Description("Returns the Geometry value that represents the point set difference of two geometries")
@ScalarFunction("ST_Difference")
@SqlType(GEOMETRY_TYPE_NAME)
public static Slice stDifference(@SqlType(GEOMETRY_TYPE_NAME) Slice left, @SqlType(GEOMETRY_TYPE_NAME) Slice right)
{
OGCGeometry le... | @Test
public void testSTDifference()
{
assertFunction("ST_AsText(ST_Difference(ST_GeometryFromText('POINT (50 100)'), ST_GeometryFromText('POINT (150 150)')))", VARCHAR, "POINT (50 100)");
assertFunction("ST_AsText(ST_Difference(ST_GeometryFromText('MULTIPOINT (50 100, 50 200)'), ST_GeometryFrom... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var msgDataAsJsonNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null;
processFieldsData(ctx, msg, msg.getOriginator(), msgDataAsJsonNode, config.isIgnoreN... | @Test
public void givenUnsupportedEntityType_whenOnMsg_thenShouldTellFailureWithSameMsg() throws TbNodeException, ExecutionException, InterruptedException {
// GIVEN
config.setDataMapping(Map.of(
"name", "originatorName",
"type", "originatorType",
"lab... |
@Override
public CloseableIterator<T> iterator() {
ParallelIterator<T> iter =
new ParallelIterator<>(iterables, workerPool, approximateMaxQueueSize);
addCloseable(iter);
return iter;
} | @Test
public void closeMoreDataParallelIteratorWithoutCompleteIteration() {
ExecutorService executor = Executors.newFixedThreadPool(1);
Iterator<Integer> integerIterator =
new Iterator<Integer>() {
private int number = 1;
@Override
public boolean hasNext() {
... |
@Nullable
public PasswordAlgorithm forPassword(String hashedPassword) {
for (PasswordAlgorithm passwordAlgorithm : passwordAlgorithms.values()) {
if (passwordAlgorithm.supports(hashedPassword))
return passwordAlgorithm;
}
return null;
} | @Test
public void testForPasswordShouldReturnFirstAlgorithm() throws Exception {
when(passwordAlgorithm1.supports(anyString())).thenReturn(true);
final PasswordAlgorithmFactory passwordAlgorithmFactory = new PasswordAlgorithmFactory(passwordAlgorithms, passwordAlgorithm2);
assertThat(passw... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_NotEqual() {
expectFailureWhenTestingThat(array(2.2d)).isEqualTo(array(OVER_2POINT2));
assertFailureValue("expected", "[2.2000000000000006]");
assertFailureValue("but was", "[2.2]");
assertFailureValue("differs at index", "[0]");
} |
public String getDashboardUrl() {
verifyInitialized();
return dashboardUrl;
} | @Test
public void getDashboardUrl_should_fail_if_not_initialized() {
assertThatThrownBy(() -> underTest.getDashboardUrl())
.isInstanceOf(IllegalStateException.class);
} |
public static String delAll(String regex, CharSequence content) {
if (StrUtil.hasEmpty(regex, content)) {
return StrUtil.str(content);
}
final Pattern pattern = PatternPool.get(regex, Pattern.DOTALL);
return delAll(pattern, content);
} | @Test
public void issueI6GIMTTest(){
assertEquals(StrUtil.EMPTY, ReUtil.delAll("[\\s]*", " "));
} |
public static FeeFilterMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException {
Coin feeRate = Coin.read(payload);
check(feeRate.signum() >= 0, () -> new ProtocolException("fee rate out of range: " + feeRate));
return new FeeFilterMessage(feeRate);
} | @Test(expected = ProtocolException.class)
@Parameters(method = "invalidFeeRates")
public void invalid(Coin feeRate) {
byte[] buf = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(feeRate.getValue()).array();
FeeFilterMessage ffm = FeeFilterMessage.read(ByteBuffer.wrap(buf)... |
public TolerantIntegerComparison isNotWithin(int tolerance) {
return new TolerantIntegerComparison() {
@Override
public void of(int expected) {
Integer actual = IntegerSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", toleranc... | @Test
public void isNotWithinOf() {
assertThatIsNotWithinFails(20000, 0, 20000);
assertThatIsNotWithinFails(20000, 1, 20000);
assertThatIsNotWithinFails(20000, 10000, 20000);
assertThatIsNotWithinFails(20000, 10000, 30000);
assertThatIsNotWithinFails(Integer.MIN_VALUE, 1, Integer.MIN_VALUE + 1);
... |
@Override
public void destroy() {
if (evictionScheduler != null) {
evictionScheduler.remove(getRawName());
}
removeListeners();
} | @Test
public void testDestroy() {
RSetCache<String> cache = redisson.getSetCache("test");
EvictionScheduler evictionScheduler = ((Redisson)redisson).getEvictionScheduler();
Map<?, ?> map = Reflect.on(evictionScheduler).get("tasks");
assertThat(map.isEmpty()).isFalse();
... |
public static boolean isKafkaInvokeBySermant(StackTraceElement[] stackTrace) {
return isInvokeBySermant(KAFKA_CONSUMER_CLASS_NAME, KAFKA_CONSUMER_CONTROLLER_CLASS_NAME, stackTrace);
} | @Test
public void testNotInvokeBySermantWithNestedInvoke() {
StackTraceElement[] stackTrace = new StackTraceElement[5];
stackTrace[0] = new StackTraceElement("testClass0", "testMethod0", "testFileName0", 0);
stackTrace[1] = new StackTraceElement("testClass1", "testMethod1", "testFileName1", ... |
private String format(double score) {
int NUM_DECIMAL_PLACES = 3;
return String.format("%." + NUM_DECIMAL_PLACES + "f", score);
} | @Test
public void durationFormatOnShortTimesWorks() {
Duration oneMinfiveSec = Duration.ofMillis(5_123).plusMinutes(1);
assertThat(format(oneMinfiveSec), equalTo("1m 5.123 sec"));
} |
public static <T> Inner<T> fields(String... fields) {
return fields(FieldAccessDescriptor.withFieldNames(fields));
} | @Test
@Category(NeedsRunner.class)
public void testDropNestedField() {
Schema expectedSchema =
Schema.builder().addStringField("string").addStringField("field2").build();
PCollection<Row> result =
pipeline
.apply(
Create.of(
nestedRow(simp... |
Future<Boolean> canRollController(int nodeId) {
LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId);
return describeMetadataQuorum().map(info -> {
boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info);
if (!canRoll) {
... | @Test
public void shouldHandlePartiallyIncompleteQuorumData(VertxTestContext context) {
Map<Integer, OptionalLong> controllers = new HashMap<>();
controllers.put(1, OptionalLong.of(10000L));
controllers.put(2, OptionalLong.empty()); // Simulating incomplete data
controllers.put(3, Op... |
public SalesforceInsertMeta() {
super(); // allocate BaseStepMeta
} | @Test
public void testSalesforceInsertMeta() throws KettleException {
List<String> attributes = new ArrayList<String>();
attributes.addAll( SalesforceMetaTest.getDefaultAttributes() );
attributes.addAll( Arrays.asList( "batchSize", "salesforceIDFieldName", "updateLookup", "updateStream",
"useExterna... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertDate() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(LocalTimeType.LOCAL_DATE_TYPE)
.build();
BasicTypeDefine typeDefine = RedshiftTypeConverter.INSTANCE.recon... |
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "/export/by-ids", produces = MediaType.APPLICATION_OCTET_STREAM)
@Operation(
tags = {"Templates"},
summary = "Export templates as a ZIP archive of yaml sources."
)
public HttpResponse<byte[]> exportByIds(
@Parameter(description = "A list o... | @Test
void exportByIds() throws IOException {
// create 3 templates, so we can retrieve them by id
var template1 = client.toBlocking().retrieve(POST("/api/v1/templates", createTemplate()), Template.class);
var template2 = client.toBlocking().retrieve(POST("/api/v1/templates", createTemplate(... |
public Future<CaReconciliationResult> reconcile(Clock clock) {
return reconcileCas(clock)
.compose(i -> verifyClusterCaFullyTrustedAndUsed())
.compose(i -> reconcileClusterOperatorSecret(clock))
.compose(i -> rollingUpdateForNewCaKey())
.compose... | @Test
public void testRollingReasonsWithClusterCAKeyNotTrusted(Vertx vertx, VertxTestContext context) {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.withNewEntityOperator()
.endEntityOperator()
.withNewCruiseControl()
... |
private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder) {
if (jsonElement.isJsonObject()) {
parseObject(systemTs, result, builder, jsonElement.getAsJsonObject());
} else if (jsonElement.isJsonArray()) {... | @Test
public void testParseAsDouble() {
var result = JsonConverter.convertToTelemetry(JsonParser.parseString("{\"meterReadingDelta\": 1.1}"), 0L);
Assertions.assertEquals(1.1, result.get(0L).get(0).getDoubleValue().get(), 0.0);
} |
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) {
if (null == source) {
return null;
}
T target = ReflectUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
} | @Test
public void copyBeanPropertiesFilterTest() {
final Food info = new Food();
info.setBookID("0");
info.setCode("");
final Food newFood = new Food();
final CopyOptions copyOptions = CopyOptions.create().setPropertiesFilter((f, v) -> !(v instanceof CharSequence) || StrUtil.isNotBlank(v.toString()));
Bean... |
@Override
public Object remove(String key) {
return threadLocal.get().remove(key);
} | @Test
public void testRemove() {
// Test putting and removing a value
contextCore.put("key", "value");
assertEquals("value", contextCore.remove("key"));
assertNull(contextCore.get("key"));
} |
@Override
public Set<MaintenanceEvent> readEvents(Duration timeout) throws SamplingException {
LOG.debug("Reading maintenance events.");
long eventReadPeriodEndMs = _kafkaCruiseControl.timeMs();
if (refreshPartitionAssignment()) {
_lastEventReadPeriodEndTimeMs = eventReadPeriodEndMs;
return Co... | @Test
public void testMaintenanceEventTopicCreationUpdateAndRead()
throws ExecutionException, InterruptedException, SamplingException {
// Verify that the maintenance event topic has been created with the desired properties.
verify(TEST_TOPIC_PARTITION_COUNT, TEST_TOPIC_REPLICATION_FACTOR, TEST_TOPIC_RE... |
public String abbreviate(String fqClassName) {
StringBuilder buf = new StringBuilder(targetLength);
if (fqClassName == null) {
throw new IllegalArgumentException("Class name may not be null");
}
int inLen = fqClassName.length();
if (inLen < targetLength) {
return fqClassName;
}
... | @Test
public void testNoDot() {
TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1);
String name = "hello";
assertEquals(name, abbreviator.abbreviate(name));
} |
@Override
public WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(Integer userType, String phoneCode) {
WxMaService service = getWxMaService(userType);
try {
return service.getUserService().getPhoneNoInfo(phoneCode);
} catch (WxErrorException e) {
log.error("[getPhoneNoInfo... | @Test
public void testGetWxMaPhoneNumberInfo_success() throws WxErrorException {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
String phoneCode = randomString();
// mock 方法
WxMaUserService userService = mock(WxMaUserService.class);
when(wxMaSer... |
public static ByteArrayClassLoader compile(
ClassLoader parentClassLoader, CompileUnit... compileUnits) {
final Map<String, byte[]> classes = toBytecode(parentClassLoader, compileUnits);
// Set up a class loader that finds and defined the generated classes.
return new ByteArrayClassLoader(classes, par... | @Test
public void compile() throws Exception {
CompileUnit unit1 =
new CompileUnit(
"demo.pkg1",
"A",
(""
+ "package demo.pkg1;\n"
+ "import demo.pkg2.*;\n"
+ "public class A {\n"
+ " public static String ... |
public static void close(AutoCloseable... closeables) {
if (CollectionUtils.isNotEmpty(closeables)) {
for (AutoCloseable closeable : closeables) {
close(closeable);
}
}
} | @Test
public void testIgnoreExceptionOnClose() {
FakeResource resource = new FakeResource() {
@Override
public void close() throws Exception {
super.close();
throw new Exception("Ops!");
}
};
IOUtil.close(resource);
... |
@GET
@Path("version")
@Produces({MediaType.APPLICATION_JSON})
public Map<String, Object> version() {
return SUPPORTED_VERSIONS;
} | @Test
public void testVersions() {
assertEquals(server.version().get("version"), "v1");
} |
public static boolean matchInterface(String address, String interfaceMask) {
final AddressMatcher mask;
try {
mask = getAddressMatcher(interfaceMask);
} catch (Exception e) {
return false;
}
return mask.match(address);
} | @Test
public void testMatchInterface_whenInvalidInterface_thenReturnFalse() {
assertFalse(AddressUtil.matchInterface("10.235.194.23", "bar"));
} |
@Override public HashSlotCursor16byteKey cursor() {
return new CursorLongKey2();
} | @Test
@RequireAssertEnabled
public void testCursor_advance_afterAdvanceReturnsFalse() {
insert(randomKey(), randomKey());
HashSlotCursor16byteKey cursor = hsa.cursor();
cursor.advance();
cursor.advance();
assertThrows(AssertionError.class, cursor::advance);
} |
public static void init() {
initHandlers();
initChains();
initPaths();
initDefaultHandlers();
ModuleRegistry.registerModule(HandlerConfig.CONFIG_NAME, Handler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HandlerConfig.CONFIG_NAME), null);
} | @Test
public void validConfig_init_handlersCreated() {
Handler.init();
Map<String, List<HttpHandler>> handlers = Handler.handlerListById;
Assert.assertEquals(1, handlers.get("third").size());
Assert.assertEquals(2, handlers.get("secondBeforeFirst").size());
} |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testPerQueueDisablePreemption() {
int[][] qData = new int[][]{
// / A B C
{ 100, 55, 25, 20 }, // abs
{ 100, 100, 100, 100 }, // maxCap
{ 100, 0, 54, 46 }, // used
{ 10, 10, 0, 0 }, // pending
{ 0, 0, 0, 0 }, // ... |
public static HttpAction buildUnauthenticatedAction(final WebContext context) {
val hasHeader = context.getResponseHeader(HttpConstants.AUTHENTICATE_HEADER).isPresent();
if (alwaysUse401ForUnauthenticated) {
// add the WWW-Authenticate header to be compliant with the HTTP spec if it does not... | @Test
public void testBuildUnauthenticated401WithHeader() {
final WebContext context = MockWebContext.create();
context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, VALUE);
val action = HttpActionHelper.buildUnauthenticatedAction(context);
assertTrue(action instanceof Unautho... |
@Override
public Settings getSettings() {
return new Settings() {
@Override
@CheckForNull
public String getString(String key) {
return config.getConfiguration().get(key).orElse(null);
}
@Override
public String[] getStringArray(String key) {
return config.getCon... | @Test
public void get_string_settings() {
MapSettings serverSettings = new MapSettings();
serverSettings.setProperty("prop", "value");
when(settingsRepository.getConfiguration()).thenReturn(serverSettings.asConfig());
MeasureComputerContextImpl underTest = newContext(FILE_1_REF);
assertThat(under... |
@PublicEvolving
public static <IN1, IN2, OUT> TypeInformation<OUT> getJoinReturnTypes(
JoinFunction<IN1, IN2, OUT> joinInterface,
TypeInformation<IN1> in1Type,
TypeInformation<IN2> in2Type) {
return getJoinReturnTypes(joinInterface, in1Type, in2Type, null, false);
} | @Test
void testInputInferenceWithCustomTupleAndRichFunction() {
JoinFunction<
CustomTuple2WithArray<Long>,
CustomTuple2WithArray<Long>,
CustomTuple2WithArray<Long>>
function = new JoinWithCustomTuple2WithArray<>();
... |
SObjectNode addNode(final SObjectNode node) {
final String givenObjectType = node.getObjectType();
if (objectType != null && !objectType.equals(givenObjectType)) {
throw new IllegalArgumentException(
"SObjectTree can hold only records of the same type, previously given: ... | @Test
public void shouldSerializeToJson() throws JsonProcessingException {
final ObjectMapper mapper = JsonUtils.createObjectMapper();
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
final ObjectWriter writer = mapper.writerFor(SObjectTree.class);
final SObjec... |
@VisibleForTesting
static void validateUpsertAndDedupConfig(TableConfig tableConfig, Schema schema) {
if (tableConfig.getUpsertMode() == UpsertConfig.Mode.NONE && (tableConfig.getDedupConfig() == null
|| !tableConfig.getDedupConfig().isDedupEnabled())) {
return;
}
boolean isUpsertEnabled = ... | @Test
public void testValidateUpsertConfig() {
Schema schema =
new Schema.SchemaBuilder().setSchemaName(TABLE_NAME).addSingleValueDimension("myCol", FieldSpec.DataType.STRING)
.build();
UpsertConfig upsertConfig = new UpsertConfig(UpsertConfig.Mode.FULL);
TableConfig tableConfig =
... |
@Override
public String loadSecretKey() {
try {
SecreteKey secreteKey = mSecretKeyManager.loadSecretKey();
SAEncryptListener mEncryptListener = mSecretKeyManager.getEncryptListener(secreteKey);
if (mEncryptListener == null) {
return "";
}
... | @Test
public void loadSecretKey() {
SAHelper.initSensors(mApplication);
SAEncryptAPIImpl encryptAPIImpl = new SAEncryptAPIImpl(SensorsDataAPI.sharedInstance(mApplication).getSAContextManager());
encryptAPIImpl.loadSecretKey();
} |
@Override
public RestLiResponseData<BatchCreateResponseEnvelope> buildRestLiResponseData(Request request,
RoutingResult routingResult,
Object result,
Map<String, ... | @Test(dataProvider = "exceptionTestData")
public void testBuilderExceptions(Object result, String expectedErrorMessage) throws URISyntaxException
{
Map<String, String> headers = ResponseBuilderUtil.getHeaders();
ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(null);
ServerResou... |
@Nullable
DockerCredentialHelper getCredentialHelperFor(String registry) {
List<Predicate<String>> registryMatchers = getRegistryMatchersFor(registry);
Map.Entry<String, String> firstCredHelperMatch =
findFirstInMapByKey(dockerConfigTemplate.getCredHelpers(), registryMatchers);
if (firstCredHelpe... | @Test
public void testGetCredentialHelperFor_withHttps() throws URISyntaxException, IOException {
Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI());
DockerConfig dockerConfig =
new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerConfigTemplate.class));
... |
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
HttpHeaders inHeaders = in.headers();
final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
if (in instanceof HttpRequest) {
HttpRequest request = (HttpRequest) in;
... | @Test
public void handlesRequestWithDoubleSlashPath() throws Exception {
boolean validateHeaders = true;
HttpRequest msg = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "//path/to/something", validateHeaders);
HttpHeaders inHeaders = msg.headers();
inHeade... |
@VisibleForTesting
static Optional<String> checkSchemas(
final LogicalSchema schema,
final LogicalSchema other
) {
final Optional<String> keyError = checkSchemas(schema.key(), other.key(), "key ")
.map(msg -> "Key columns must be identical. " + msg);
if (keyError.isPresent()) {
ret... | @Test
public void shouldEnforceNoRemovedKeyColumns() {
// Given:
final LogicalSchema someSchema = LogicalSchema.builder()
.keyColumn(ColumnName.of("k0"), SqlTypes.INTEGER)
.keyColumn(ColumnName.of("k1"), SqlTypes.INTEGER)
.valueColumn(ColumnName.of("f0"), SqlTypes.BIGINT)
.buil... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void testParseWithUuidGeneratorArgument() {
RuntimeOptionsBuilder optionsBuilder = parser.parse("--uuid-generator",
IncrementingUuidGenerator.class.getName());
assertNotNull(optionsBuilder);
RuntimeOptions options = optionsBuilder.build();
assertNotNull(options);
... |
@SuppressWarnings("unchecked")
public final void isLessThan(@Nullable T other) {
if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) >= 0) {
failWithActual("expected to be less than", other);
}
} | @Test
public void rawComparableType() {
assertThat(new RawComparableType(3)).isLessThan(new RawComparableType(4));
} |
public Optional<Path> transactionIndex() {
return transactionIndex;
} | @Test
public void testOptionalTransactionIndex() {
File dir = TestUtils.tempDirectory();
LogSegmentData logSegmentDataWithTransactionIndex = new LogSegmentData(
new File(dir, "log-segment").toPath(),
new File(dir, "offset-index").toPath(),
new File(dir... |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @Test
void testFunctionDependingOnInputWithFunctionHierarchy2() {
IdentityMapper5<String> function = new IdentityMapper5<String>();
@SuppressWarnings({"rawtypes", "unchecked"})
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
function,
... |
public static String generateFileName(String string) {
string = StringUtils.stripAccents(string);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isSpaceChar(c)
&& (buf.lengt... | @Test
public void testInvalidInput() {
String result = FileNameGenerator.generateFileName("???");
assertFalse(TextUtils.isEmpty(result));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.