focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
void handleStatement(final QueuedCommand queuedCommand) {
throwIfNotConfigured();
handleStatementWithTerminatedQueries(
queuedCommand.getAndDeserializeCommand(commandDeserializer),
queuedCommand.getAndDeserializeCommandId(),
queuedCommand.getStatus(),
Mode.EXECUTE,
queue... | @Test
public void shouldThrowOnUnexpectedException() {
// Given:
final String statementText = "mama said knock you out";
final RuntimeException exception = new RuntimeException("i'm gonna knock you out");
when(mockParser.parseSingleStatement(statementText)).thenThrow(exception);
final Command com... |
public Meter meter(String name) {
return getOrAdd(name, MetricBuilder.METERS);
} | @Test
public void accessingAMeterRegistersAndReusesIt() {
final Meter meter1 = registry.meter("thing");
final Meter meter2 = registry.meter("thing");
assertThat(meter1)
.isSameAs(meter2);
verify(listener).onMeterAdded("thing", meter1);
} |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertInt() {
Column column = PhysicalColumn.builder().name("test").dataType(BasicType.INT_TYPE).build();
BasicTypeDefine typeDefine = DB2TypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName());
Assertions.as... |
@Override
public Stream<FileSlice> getLatestFileSlicesBeforeOrOn(String partitionPath, String maxCommitTime,
boolean includeFileSlicesInPendingCompaction) {
return execute(partitionPath, maxCommitTime, includeFileSlicesInPendingCompaction,
preferredView::getLatestFileSlicesBeforeOrOn, (path, commitT... | @Test
public void testGetLatestFileSlicesBeforeOrOn() {
Stream<FileSlice> actual;
Stream<FileSlice> expected = testFileSliceStream;
String partitionPath = "/table2";
String maxCommitTime = "2020-01-01";
when(primary.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false))
.then... |
public static <K> KTableHolder<K> build(
final KTableHolder<K> left,
final KTableHolder<K> right,
final TableTableJoin<K> join
) {
final LogicalSchema leftSchema;
final LogicalSchema rightSchema;
if (join.getJoinType().equals(RIGHT)) {
leftSchema = right.getSchema();
rightSc... | @Test
public void shouldDoInnerJoinWithSytheticKey() {
// Given:
givenInnerJoin(SYNTH_KEY);
// When:
join.build(planBuilder, planInfo);
// Then:
verify(leftKTable).join(
same(rightKTable),
eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.value().size(), 1))
... |
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof MetricsContainerImpl) {
MetricsContainerImpl metricsContainerImpl = (MetricsContainerImpl) object;
return Objects.equals(stepName, metricsContainerImpl.stepName)
&& Objects.equals(counters, metricsContainerImpl.... | @Test
public void testEquals() {
MetricsContainerImpl metricsContainerImpl = new MetricsContainerImpl("stepName");
MetricsContainerImpl equal = new MetricsContainerImpl("stepName");
Assert.assertEquals(metricsContainerImpl, equal);
Assert.assertEquals(metricsContainerImpl.hashCode(), equal.hashCode())... |
public String getXML() {
StringBuilder retval = new StringBuilder( 300 );
retval
.append( " " ).append(
XMLHandler.addTagValue( "connection", databaseMeta == null ? "" : databaseMeta.getName() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "commit", commitSize ) );
retval... | @Test
public void testGetXML() {
OraBulkLoaderMeta oraBulkLoaderMeta = new OraBulkLoaderMeta();
oraBulkLoaderMeta.setFieldTable( new String[] { "fieldTable1", "fieldTable2" } );
oraBulkLoaderMeta.setFieldStream( new String[] { "fieldStreamValue1" } );
oraBulkLoaderMeta.setDateMask( new String[] {} );
... |
@Override
public Response onRequest(ReadRequest request) {
throw new UnsupportedOperationException("Temporary does not support");
} | @Test
void testOnRequest() {
assertThrows(UnsupportedOperationException.class, () -> {
persistentClientOperationServiceImpl.onRequest(ReadRequest.newBuilder().build());
});
} |
@Override
public void start() throws Exception {
LOG.info("Starting split enumerator for source {}.", operatorName);
// we mark this as started first, so that we can later distinguish the cases where
// 'start()' wasn't called and where 'start()' failed.
started = true;
// ... | @Test
public void testListeningEventsFromOtherCoordinators() throws Exception {
final String listeningID = "testListeningID";
CoordinatorStore store = new CoordinatorStoreImpl();
final SourceCoordinator<?, ?> coordinator =
new SourceCoordinator<>(
OPE... |
@Override
public byte convertToByte(CharSequence value) {
if (value instanceof AsciiString && value.length() == 1) {
return ((AsciiString) value).byteAt(0);
}
return Byte.parseByte(value.toString());
} | @Test
public void testByteFromAsciiString() {
assertEquals(127, converter.convertToByte(AsciiString.of("127")));
} |
@Override
public boolean isIndexed(QueryContext queryContext) {
Index index = queryContext.matchIndex(attributeName, QueryContext.IndexMatchHint.PREFER_ORDERED);
return index != null && index.isOrdered() && expressionCanBeUsedAsIndexPrefix();
} | @Test
public void likePredicateIsIndexed_whenPercentWildcardIsUsed_andIndexIsSorted() {
QueryContext queryContext = mock(QueryContext.class);
when(queryContext.matchIndex("this", QueryContext.IndexMatchHint.PREFER_ORDERED)).thenReturn(createIndex(IndexType.SORTED));
assertTrue(new LikePredi... |
@Override
public RedisClusterNode clusterGetNodeForSlot(int slot) {
Iterable<RedisClusterNode> res = clusterGetNodes();
for (RedisClusterNode redisClusterNode : res) {
if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) {
return redisCluster... | @Test
public void testClusterGetNodeForSlot() {
testInCluster(connection -> {
RedisClusterNode node1 = connection.clusterGetNodeForSlot(1);
RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000);
assertThat(node1.getId()).isNotEqualTo(node2.getId());
});... |
public Result combine(Result other) {
return new Result(this.isPass() && other.isPass(), this.isDescend()
&& other.isDescend());
} | @Test
public void equalsFail() {
Result one = Result.FAIL;
Result two = Result.FAIL.combine(Result.FAIL);
assertEquals(one, two);
} |
@Override
public void run() {
updateElasticSearchHealthStatus();
updateFileSystemMetrics();
} | @Test
public void when_no_es_status_null_status_is_updated_to_red() {
ClusterHealthResponse clusterHealthResponse = Mockito.mock(ClusterHealthResponse.class);
when(clusterHealthResponse.getStatus()).thenReturn(null);
when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse);
underTest.run... |
@Deprecated
@Override
public void init(final org.apache.kafka.streams.processor.ProcessorContext context, final StateStore root) {
store.init(context, root);
} | @Deprecated
@Test
public void shouldDeprecatedInitTimestampedStore() {
givenWrapperWithTimestampedStore();
final org.apache.kafka.streams.processor.ProcessorContext mockContext
= mock(org.apache.kafka.streams.processor.ProcessorContext.class);
wrapper.init(mockContext, wrapp... |
static String lookupKafkaClusterId(WorkerConfig config) {
log.info("Creating Kafka admin client");
try (Admin adminClient = Admin.create(config.originals())) {
return lookupKafkaClusterId(adminClient);
}
} | @Test
public void testLookupNullKafkaClusterId() {
final Node broker1 = new Node(0, "dummyHost-1", 1234);
final Node broker2 = new Node(1, "dummyHost-2", 1234);
List<Node> cluster = Arrays.asList(broker1, broker2);
MockAdminClient adminClient = new MockAdminClient.Builder().
... |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldReturnEmptyIfRangeNotPresent() {
// Given:
when(kafkaStreams.query(any())).thenReturn(getEmptyIteratorResult());
// When:
final Iterator<Row> rowIterator = table.get(PARTITION, A_KEY, null).rowIterator;
// Then:
assertThat(rowIterator.hasNext(), is(false));
} |
public static Schema create(Type type) {
switch (type) {
case STRING:
return new StringSchema();
case BYTES:
return new BytesSchema();
case INT:
return new IntSchema();
case LONG:
return new LongSchema();
case FLOAT:
return new FloatSchema();
case DOUBLE:
... | @Test
void intDefaultValue() {
Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.INT), "doc", 1);
assertTrue(field.hasDefaultValue());
assertEquals(1, field.defaultVal());
assertEquals(1, GenericData.get().getDefaultValue(field));
field = new Schema.Field("myField", Schem... |
@Override
protected double maintain() {
if ( ! nodeRepository().nodes().isWorking()) return 0.0;
if ( ! nodeRepository().zone().cloud().allowHostSharing()) return 1.0; // Re-balancing not necessary
if (nodeRepository().zone().environment().isTest()) return 1.0; // Short-lived deployments; n... | @Test
public void testNoRebalancingIfRecentlyDeployed() {
RebalancerTester tester = new RebalancerTester();
// --- Deploying a cpu heavy application - causing 1 of these nodes to be skewed
tester.deployApp(cpuApp);
Node cpuSkewedNode = tester.getNode(cpuApp);
tester.maintain... |
@Override
public RemoteData.Builder serialize() {
final RemoteData.Builder remoteBuilder = RemoteData.newBuilder();
remoteBuilder.addDataLongs(getTotal());
remoteBuilder.addDataLongs(getTimeBucket());
remoteBuilder.addDataStrings(getEntityId());
remoteBuilder.addDataStrings... | @Test
public void testSerialize() {
long time = 1597113447737L;
function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), time);
SumPerMinFunction function2 = Mockito.spy(SumPerMinFunction.class);
function2.deserialize(function.serialize().build());
assertThat(f... |
public String toJson() {
JsonObject details = new JsonObject();
details.addProperty(FIELD_LEVEL, level.toString());
JsonArray conditionResults = new JsonArray();
for (EvaluatedCondition condition : this.conditions) {
conditionResults.add(toJson(condition));
}
details.add("conditions", cond... | @Test
public void verify_json_for_small_leak() {
String actualJson = new QualityGateDetailsData(Measure.Level.OK, Collections.emptyList(), false).toJson();
JsonAssert.assertJson(actualJson).isSimilarTo("{\"ignoredConditions\": false}");
String actualJson2 = new QualityGateDetailsData(Measure.Level.OK, Co... |
public Map<String, Gauge<Long>> gauges() {
Map<String, Gauge<Long>> gauges = new HashMap<>();
final TrafficCounter tc = trafficCounter();
gauges.put(READ_BYTES_1_SEC, new Gauge<Long>() {
@Override
public Long getValue() {
return tc.lastReadBytes();
... | @Test
@Ignore("Flaky test")
public void counterReturnsWrittenBytes() throws InterruptedException {
final ByteBuf byteBuf = Unpooled.copiedBuffer("Test", StandardCharsets.US_ASCII);
channel.writeOutbound(byteBuf);
Thread.sleep(1000L);
channel.writeOutbound(byteBuf);
channe... |
public static CredentialService getInstance() {
return getInstance(null);
} | @Test
void testGetInstance2() {
CredentialService credentialService1 = CredentialService.getInstance(APP_NAME);
CredentialService credentialService2 = CredentialService.getInstance(APP_NAME);
assertEquals(credentialService1, credentialService2);
} |
public static String parsePath(String uri, Map<String, String> patterns) {
if (uri == null) {
return null;
} else if (StringUtils.isBlank(uri)) {
return String.valueOf(SLASH);
}
CharacterIterator ci = new StringCharacterIterator(uri);
StringBuilder pathBuf... | @Test(description = "parse path like /swagger.{json|yaml}")
public void test() {
final Map<String, String> regexMap = new HashMap<String, String>();
final String path = PathUtils.parsePath("/swagger.{json|yaml}", regexMap);
assertEquals(path, "/swagger.{json|yaml}");
assertEquals(reg... |
public static byte[] decryptAES(byte[] data, byte[] key) {
return desTemplate(data, key, AES_Algorithm, AES_Transformation, false);
} | @Test
public void decryptAES() throws Exception {
TestCase.assertTrue(
Arrays.equals(
bytesDataAES,
EncryptKit.decryptAES(bytesResAES, bytesKeyAES)
)
);
TestCase.assertTrue(
Arrays.equals(
... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void doNotCastNameExprLiterals() {
final TypedExpression left = expr(THIS_PLACEHOLDER + ".getAgeAsShort()", java.lang.Short.class);
final TypedExpression right = expr("$age", int.class);
final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, ... |
@VisibleForTesting
DatanodeDescriptor[] chooseSourceDatanodes(BlockInfo block,
List<DatanodeDescriptor> containingNodes,
List<DatanodeStorageInfo> nodesContainingLiveReplicas,
NumberReplicas numReplicas, List<Byte> liveBlockIndices,
List<Byte> liveBusyBlockIndices, List<Byte> excludeReconstruc... | @Test
public void testChooseSrcDNWithDupECInDecommissioningNode() throws Exception {
long blockId = -9223372036854775776L; // real ec block id
Block aBlock = new Block(blockId, 0, 0);
// RS-3-2 EC policy
ErasureCodingPolicy ecPolicy =
SystemErasureCodingPolicies.getPolicies().get(1);
// st... |
@Override
public boolean isTrusted(Address address) {
if (address == null) {
return false;
}
if (trustedInterfaces.isEmpty()) {
return true;
}
String host = address.getHost();
if (matchAnyInterface(host, trustedInterfaces)) {
retur... | @Test
public void givenInterfaceIsConfigured_whenMessageWithMatchingHost_thenTrust() throws UnknownHostException {
AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.0.1"), logger);
Address address = createAddress("127.0.0.1");
assertTrue(joinMessageTrustChe... |
public static Map<String, String> transStringMap(final Map<String, Object> map) {
return Optional.ofNullable(map)
.map(m -> m.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> Objects.toString(e.getValue(), null))))
.orElse(null);
} | @Test
public void testTransStringMap() {
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("a", 1);
jsonParams.put("b", 2);
Map<String, String> stringStringMap = MapUtils.transStringMap(jsonParams);
assertEquals(stringStringMap.get("a").getClass(), String.class... |
public static String getClassName(Object obj, boolean isSimple) {
if (null == obj) {
return null;
}
final Class<?> clazz = obj.getClass();
return getClassName(clazz, isSimple);
} | @Test
public void getClassNameTest() {
String className = ClassUtil.getClassName(ClassUtil.class, false);
assertEquals("cn.hutool.core.util.ClassUtil", className);
String simpleClassName = ClassUtil.getClassName(ClassUtil.class, true);
assertEquals("ClassUtil", simpleClassName);
} |
@Override
public void addPermission(String role, String resource, String action) {
String sql = "INSERT INTO permissions (role, resource, action) VALUES (?, ?, ?)";
try {
jt.update(sql, role, resource, action);
} catch (CannotGetJdbcConnectionException e) {
... | @Test
void testAddPermission() {
String sql = "INSERT INTO permissions (role, resource, action) VALUES (?, ?, ?)";
externalPermissionPersistService.addPermission("role", "resource", "action");
Mockito.verify(jdbcTemplate).update(sql, "role", "resource", "action");
} |
public RouteResult<T> route(HttpMethod method, String path) {
return route(method, path, Collections.emptyMap());
} | @Test
void testParams() {
RouteResult<String> routed = router.route(GET, "/articles/123");
assertThat(routed.target()).isEqualTo("show");
assertThat(routed.pathParams()).hasSize(1);
assertThat(routed.pathParams().get("id")).isEqualTo("123");
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @Test
void testFunctionDependingOnUnknownInput() {
IdentityMapper3<Boolean, String> function = new IdentityMapper3<Boolean, String>();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
function, BasicTypeInfo.BOOLEAN_TYPE_INFO, "name", true);
a... |
public static Double interpolateCourse(Double c1, Double c2, double fraction) {
if (c1 == null || c2 == null) {
return null;
}
checkArgument(VALID_COURSE_RANGE.contains(c1), "The 1st course: " + c1 + " is not in range");
checkArgument(VALID_COURSE_RANGE.contains(c2), "The 2... | @Test
public void testInterpolateCourseOnNullInput() {
assertNull(interpolateCourse(null, 10.0, .5));
assertNull(interpolateCourse(10.0, null, .5));
} |
public static Criterion matchIPProtocol(short proto) {
return new IPProtocolCriterion(proto);
} | @Test
public void testMatchIpProtocolMethod() {
Criterion matchIPProtocol = Criteria.matchIPProtocol(protocol1);
IPProtocolCriterion ipProtocolCriterion =
checkAndConvert(matchIPProtocol,
Criterion.Type.IP_PROTO,
IPProto... |
public static Collection<MdbValidityStatus> assertEjbClassValidity(final ClassInfo mdbClass) {
Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length);
final String className = mdbClass.name().toString();
verifyModifiers(className, mdbClass.flags... | @Test
public void mdbWithStaticOnMessageMethod() {
assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbOnMessageCantBeStatic.class.getName())).contains(
MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_STATIC));
} |
@Override
public void removeAttribute(String key) {
channel.removeAttribute(key);
} | @Test
void removeAttributeTest() {
header.setAttribute("test", "test");
Assertions.assertEquals(header.getAttribute("test"), "test");
header.removeAttribute("test");
Assertions.assertFalse(header.hasAttribute("test"));
} |
public Where getColumns() {
return new Where("Columns");
} | @Test
void queryFirstColumn() throws Exception {
queryableIndex.getColumns()
.where(Column.index()
.any())
.select()
.first(firstColumnQueryCallback);
verify(firstColumnQueryCallback).callback(firstColumnArgumentCaptor.capture... |
@Config("database-url")
public MySqlConnectionConfig setDatabaseUrl(String databaseUrl)
{
this.databaseUrl = databaseUrl;
return this;
} | @Test
public void testExplicitPropertyMappings()
{
Map<String, String> properties = new ImmutableMap.Builder<String, String>()
.put("database-url", "localhost:1080")
.build();
MySqlConnectionConfig expected = new MySqlConnectionConfig()
.setDatabas... |
static <T> @Nullable JdbcReadWithPartitionsHelper<T> getPartitionsHelper(TypeDescriptor<T> type) {
// This cast is unchecked, thus this is a small type-checking risk. We just need
// to make sure that all preset helpers in `JdbcUtil.PRESET_HELPERS` are matched
// in type from their Key and their Value.
... | @Test
public void testDatetimePartitioningWithSingleKey() {
JdbcReadWithPartitionsHelper<DateTime> helper =
JdbcUtil.getPartitionsHelper(TypeDescriptor.of(DateTime.class));
DateTime onlyPoint = DateTime.now();
List<KV<DateTime, DateTime>> expectedRanges =
Lists.newArrayList(KV.of(onlyPoint... |
public static SmartFilterTestExecutionResultDTO execSmartFilterTest(SmartFilterTestExecutionDTO execData) {
Predicate<TopicMessageDTO> predicate;
try {
predicate = MessageFilters.createMsgFilter(
execData.getFilterCode(),
MessageFilterTypeDTO.GROOVY_SCRIPT
);
} catch (Excepti... | @Test
void execSmartFilterTestReturnsExecutionResult() {
var params = new SmartFilterTestExecutionDTO()
.filterCode("key != null && value != null && headers != null && timestampMs != null && offset != null")
.key("1234")
.value("{ \"some\" : \"value\" } ")
.headers(Map.of("h1", "hv... |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldThrowWhenCreateAsSelectOnNewTopicWithoutValueSchemaWritePermissions() {
// Given:
givenSubjectAccessDenied("topic-value", AclOperation.WRITE);
final Statement statement = givenStatement(String.format(
"CREATE STREAM newStream WITH (kafka_topic='topic', value_format='AVRO') ... |
public static UriTemplate create(String template, Charset charset) {
return new UriTemplate(template, true, charset);
} | @Test
void substituteNullMap() {
assertThrows(IllegalArgumentException.class,
() -> UriTemplate.create("stuff", Util.UTF_8).expand(null));
} |
@Transactional
public void payInstallment(String identificationNumber, int creditId, int installmentId) {
Credit credit = creditRepository.findByIdAndIdentificationNumber(creditId, identificationNumber)
.orElseThrow(() -> createCreditNotFoundException(creditId));
Installment install... | @Test
void payInstallment_alreadyPaid() {
// Arrange
String identificationNumber = "1234567890";
int creditId = 1;
int installmentId = 1;
Credit credit = Credit.builder()
.id(creditId)
.amount(BigDecimal.valueOf(1000))
.status(C... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void noRetryForNoRouteToHostException() {
HttpGet request = new HttpGet("/");
assertThat(retryStrategy.retryRequest(request, new NoRouteToHostException(), 1, null))
.isFalse();
} |
@Override
public ObjectNode encode(Alarm alarm, CodecContext context) {
checkNotNull(alarm, "Alarm cannot be null");
return context.mapper().createObjectNode()
.put("id", alarm.id().toString())
.put("deviceId", alarm.deviceId().toString())
.put("descr... | @Test
public void alarmCodecTestWithOptionalField() {
JsonCodec<Alarm> codec = context.codec(Alarm.class);
assertThat(codec, is(notNullValue()));
ObjectNode alarmJson = codec.encode(alarmWithSource, context);
assertThat(alarmJson, notNullValue());
assertThat(alarmJson, match... |
@Override
public boolean putRow( RowMetaInterface rowMeta, Object[] rowData ) {
this.rowMeta = rowMeta;
buffer.add( rowData );
return true;
} | @Test
public void testPutRow() throws Exception {
rowSet.putRow( new RowMeta(), row );
assertSame( row, rowSet.getRow() );
} |
public String getPassword() {
return password;
} | @Test
public void testPassword() {
assertEquals("password", jt400Configuration.getPassword());
} |
@Udf
public <T extends Comparable<? super T>> T arrayMax(@UdfParameter(
description = "Array of values from which to find the maximum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldFindDecimalMax() {
final List<BigDecimal> input =
Arrays.asList(BigDecimal.valueOf(1.2), BigDecimal.valueOf(1.3), BigDecimal.valueOf(-1.2));
assertThat(udf.arrayMax(input), is(BigDecimal.valueOf(1.3)));
} |
public static String rpcTypeAdapter(final String rpcType) {
RpcTypeEnum rpcTypeEnum = RpcTypeEnum.acquireByName(rpcType);
switch (rpcTypeEnum) {
case GRPC:
return PluginEnum.GRPC.getName();
case SPRING_CLOUD:
return PluginEnum.SPRING_CLOUD.getName(... | @Test
public void testRpcTypeAdapter() {
Arrays.stream(RpcTypeEnum.values())
.filter(rpcTypeEnum -> !RpcTypeEnum.HTTP.getName().equals(rpcTypeEnum.getName()))
.forEach(rpcTypeEnum -> assertEquals(PluginNameAdapter.rpcTypeAdapter(rpcTypeEnum.getName()),
... |
public HollowHashIndexResult findMatches(Object... query) {
if (hashStateVolatile == null) {
throw new IllegalStateException(this + " wasn't initialized");
}
int hashCode = 0;
for(int i=0;i<query.length;i++) {
if(query[i] == null)
throw new Illega... | @Test
public void testIndexingBooleanTypeFieldWithNullValues() throws Exception {
mapper.add(new TypeBoolean(null));
mapper.add(new TypeBoolean(true));
mapper.add(new TypeBoolean(false));
roundTripSnapshot();
HollowHashIndex index = new HollowHashIndex(readStateEngine, "Type... |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testTableScanNoStats() throws Exception {
appendTwoSnapshots();
ScanContext scanContext =
ScanContext.builder()
.includeColumnStats(false)
.startingStrategy(StreamingStartingStrategy.TABLE_SCAN_THEN_INCREMENTAL)
.build();
ContinuousSplitPlanne... |
@VisibleForTesting
public int getAppsFailedSubmitted() {
return numAppsFailedSubmitted.value();
} | @Test
public void testAppsFailedSubmitted() {
long totalBadbefore = metrics.getAppsFailedSubmitted();
badSubCluster.submitApplication();
Assert.assertEquals(totalBadbefore + 1, metrics.getAppsFailedSubmitted());
} |
public TermsAggregationBuilder buildTermsAggregation(String name,
TopAggregationDefinition<?> topAggregation, @Nullable Integer numberOfTerms) {
TermsAggregationBuilder termsAggregation = AggregationBuilders.terms(name)
.field(topAggregation.getFilterScope().getFieldName())
.order(order)
.minD... | @Test
public void buildTermsAggregation_adds_custom_size_if_TermTopAggregation_specifies_one() {
String aggName = randomAlphabetic(10);
int customSize = 1 + new Random().nextInt(400);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of... |
@Override
@MethodNotAvailable
public void close() {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testClose() {
adapter.close();
} |
@VisibleForTesting
protected static long[] splitIp(String baseIp) throws UnknownHostException {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(baseIp);
} catch (UnknownHostException e) {
LOG.error("Base IP address is invalid");
throw e;
}
if (inetAddress insta... | @Test
public void testSplitIp() throws Exception {
long[] splitIp = ReverseZoneUtils.splitIp(NET);
assertEquals(172, splitIp[0]);
assertEquals(17, splitIp[1]);
assertEquals(4, splitIp[2]);
assertEquals(0, splitIp[3]);
} |
public static <K, V> Write<K, V> write() {
return new AutoValue_CdapIO_Write.Builder<K, V>().build();
} | @Test
public void testWriteObjectCreationFailsIfCdapPluginClassIsNull() {
assertThrows(
IllegalArgumentException.class,
() -> CdapIO.<String, String>write().withCdapPluginClass(null));
} |
protected String matchFilters(final Exchange exchange) {
return filterService.getMatchingEndpointsForExchangeByChannel(
exchange, channel, MODE_FIRST_MATCH.equals(recipientMode), warnDroppedMessage);
} | @Test
void testMatchFilters() {
when(filterService.getMatchingEndpointsForExchangeByChannel(exchange, TEST_CHANNEL, true, false))
.thenReturn(MOCK_ENDPOINT);
String result = processor.matchFilters(exchange);
assertEquals(MOCK_ENDPOINT, result);
} |
@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 longlivedCcPetstoreScope() throws Exception {
JwtClaims claims = ClaimsUtil.getTestCcClaimsScope("f7d42348-c647-4efb-a52d-4c5787421e73", "write:pets read:pets");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.des... |
@Override
public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
DeviceId deviceId,
List<PortDescription> portDescriptions) {
NodeId localNode = clusterService.getLocalNode().id();
... | @Test
public final void testUpdatePorts() {
putDevice(DID1, SW1);
List<PortDescription> pds = Arrays.asList(
DefaultPortDescription.builder().withPortNumber(P1).isEnabled(true).build(),
DefaultPortDescription.builder().withPortNumber(P2).isEnabled(true).build()
... |
@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 = "empty")
public void offer_whenEmpty(MpscGrowableArrayQueue<Integer> queue) {
assertThat(queue.offer(1)).isTrue();
assertThat(queue).hasSize(1);
} |
public static boolean hasSchemePattern( String path ) {
return hasSchemePattern( path, PROVIDER_PATTERN_SCHEME );
} | @Test
public void testHasScheme() {
String vfsFilename = "hdfs://hsbcmaster:8020/tmp/acltest/";
boolean testVfsFilename = KettleVFS.hasSchemePattern( vfsFilename, PROVIDER_PATTERN_SCHEME );
assertTrue( testVfsFilename );
} |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testSingleCounterUpdates() throws IOException {
AppliedPTransform<?, ?, ?> myStep = mock(AppliedPTransform.class);
when(myStep.getFullName()).thenReturn("myStepName");
BiMap<AppliedPTransform<?, ?, ?>, String> transformStepNames = HashBiMap.create();
transformStepNames.put(myStep, "s... |
public static String joinAndCamelize(Iterable<?> iterable) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for ( Object object : iterable ) {
if ( !isFirst ) {
sb.append( capitalize( object.toString() ) );
}
else {
... | @Test
public void testJoinAndCamelize() {
assertThat( Strings.joinAndCamelize( new ArrayList<String>() ) ).isEqualTo( "" );
assertThat( Strings.joinAndCamelize( Arrays.asList( "Hello", "World" ) ) ).isEqualTo( "HelloWorld" );
assertThat( Strings.joinAndCamelize( Arrays.asList( "Hello", "worl... |
static void parseServerIpAndPort(Connection connection, Span span) {
try {
URI url = URI.create(connection.getMetaData().getURL().substring(5)); // strip "jdbc:"
String remoteServiceName = connection.getProperties().getProperty("zipkinServiceName");
if (remoteServiceName == null || "".equals(remot... | @Test void parseServerIpAndPort_doesntCrash() throws SQLException {
when(connection.getMetaData()).thenThrow(new SQLException());
TracingStatementInterceptor.parseServerIpAndPort(connection, span);
verifyNoMoreInteractions(span);
} |
@Override
void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
// PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology)
// must be verified.
expectUtf8AsDefault(connection);
if (state == DatabaseCharse... | @Test
public void upgrade_fails_if_default_charset_is_not_utf8() throws Exception {
answerDefaultCharset("latin");
answerColumns(
List.<String[]>of(new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"}));
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE))
.... |
public static <NodeT, EdgeT> Set<NodeT> reachableNodes(
Network<NodeT, EdgeT> network, Set<NodeT> startNodes, Set<NodeT> endNodes) {
Set<NodeT> visitedNodes = new HashSet<>();
Queue<NodeT> queuedNodes = new ArrayDeque<>();
queuedNodes.addAll(startNodes);
// Perform a breadth-first traversal rooted... | @Test
public void testReachableNodesFromAllRoots() {
assertEquals(
createNetwork().nodes(),
Networks.reachableNodes(
createNetwork(), ImmutableSet.of("A", "D", "I", "M", "O"), Collections.emptySet()));
} |
@Override
public long getPosition() throws IOException
{
checkClosed();
return currentPosition;
} | @Test
void testPositionPeek() throws IOException
{
byte[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20 };
try (RandomAccessReadBuffer randomAccessSource =
new RandomAccessReadBuffer(new ByteArrayInputStream(values));
... |
public void build(@Nullable SegmentVersion segmentVersion, ServerMetrics serverMetrics)
throws Exception {
SegmentGeneratorConfig genConfig = new SegmentGeneratorConfig(_tableConfig, _dataSchema);
// The segment generation code in SegmentColumnarIndexCreator will throw
// exception if start and end t... | @Test
public void test10RecordsIndexedColumnMajorSegmentBuilder()
throws Exception {
File tmpDir = new File(TMP_DIR, "tmp_" + System.currentTimeMillis());
TableConfig tableConfig =
new TableConfigBuilder(TableType.REALTIME).setTableName("testTable")
.setTimeColumnName(DATE_TIME_COLUM... |
public static RandomForest fit(Formula formula, DataFrame data) {
return fit(formula, data, new Properties());
} | @Test
public void testPenDigits() {
System.out.println("Pen Digits");
MathEx.setSeed(19650218); // to get repeatable results for cross validation.
ClassificationValidations<RandomForest> result = CrossValidation.classification(10, PenDigits.formula, PenDigits.data,
(f, x) ->... |
public void addOrder(Order... orders) {
this.orders = ArrayUtil.append(this.orders, orders);
} | @Test
public void addOrderTest() {
Page page = new Page();
page.addOrder(new Order("aaa"));
assertEquals(page.getOrders().length, 1);
page.addOrder(new Order("aaa"));
assertEquals(page.getOrders().length, 2);
} |
@Override
protected void handleLookup(CommandLookupTopic lookup) {
checkArgument(state == State.Connected);
final long requestId = lookup.getRequestId();
final boolean authoritative = lookup.isAuthoritative();
// use the connection-specific listener name by default.
final St... | @Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailHandleLookup() throws Exception {
ServerCnx serverCnx = mock(ServerCnx.class, CALLS_REAL_METHODS);
Field stateUpdater = ServerCnx.class.getDeclaredField("state");
stateUpdater.setAccessible(true);
stateU... |
public static String toJson(UpdateRequirement updateRequirement) {
return toJson(updateRequirement, false);
} | @Test
public void testAssertUUIDToJson() {
String uuid = "2cc52516-5e73-41f2-b139-545d41a4e151";
String expected = String.format("{\"type\":\"assert-table-uuid\",\"uuid\":\"%s\"}", uuid);
UpdateRequirement actual = new UpdateRequirement.AssertTableUUID(uuid);
assertThat(UpdateRequirementParser.toJson(... |
@SuppressWarnings("deprecation")
public Object getSocketOpt(int option)
{
switch (option) {
case ZMQ.ZMQ_SNDHWM:
return sendHwm;
case ZMQ.ZMQ_RCVHWM:
return recvHwm;
case ZMQ.ZMQ_AFFINITY:
return affinity;
case ZMQ.ZMQ_IDENTITY:
... | @Test
public void testDefaultValue()
{
assertThat(options.getSocketOpt(ZMQ.ZMQ_GSSAPI_PRINCIPAL), is(options.gssPrincipal));
assertThat(options.getSocketOpt(ZMQ.ZMQ_GSSAPI_SERVICE_PRINCIPAL), is(options.gssServicePrincipal));
assertThat(options.getSocketOpt(ZMQ.ZMQ_HANDSHAKE_IVL), is(opt... |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_submit_server_cli_version_same_minor_patch_mismatch() {
String serverVersion = "5.0.0";
System.setProperty(HAZELCAST_INTERNAL_OVERRIDE_VERSION, serverVersion);
Config cfg = smallInstanceConfig();
cfg.getJetConfig().setResourceUploadEnabled(true);
Strin... |
public boolean isMatch(Map<String, Pattern> patterns) {
if (!patterns.isEmpty()) {
return matchPatterns(patterns);
}
// Empty pattern is still considered as a match.
return true;
} | @Test
public void testIsMatchMultiplePatternValid() throws UnknownHostException {
Uuid uuid = Uuid.randomUuid();
ClientMetricsInstanceMetadata instanceMetadata = new ClientMetricsInstanceMetadata(uuid,
ClientMetricsTestUtils.requestContext());
Map<String, Pattern> patternMap = n... |
public static Mode parse(String value) {
if (StringUtils.isBlank(value)) {
throw new IllegalArgumentException(ExceptionMessage.INVALID_MODE.getMessage(value));
}
try {
return parseNumeric(value);
} catch (NumberFormatException e) {
// Treat as symbolic
return parseSymbolic(value... | @Test
public void symbolicsBadTargets() {
mThrown.expect(IllegalArgumentException.class);
mThrown.expectMessage(ExceptionMessage.INVALID_MODE_SEGMENT.getMessage("f=r", "f=r", "f"));
ModeParser.parse("f=r");
} |
@Override
public void destroyChannel(String serverAddress, Channel channel) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("will destroy channel:{},address:{}", channel, serverAddress);
}
channel.disconnect();
channel.close();
} | @Test
public void testDestroyChannel() {
Channel channel = Mockito.mock(Channel.class);
nettyRemotingServer.destroyChannel("127.0.0.1:8091", channel);
Mockito.verify(channel).close();
} |
@Override
public long countKeys() {
return get(countKeysAsync());
} | @Test
public void testCountKeys() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
TestType t = new TestType();
t.setName("name1");
al.set(t);
assertThat(al.countKeys()).isEqualTo(1);
NestedType nt = new NestedType();
... |
public SerializableFunction<Row, T> getFromRowFunction() {
return fromRowFunction;
} | @Test
public void testPrimitiveRowToProto() {
ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(Primitive.getDescriptor());
SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction();
assertEquals(PRIMITIVE_PROTO.toString(), fromRow.apply(PRIMITIVE_ROW).toString(... |
@Override
public ConfigRepoPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
PluggableInstanceSettings pluggableInstanceSettings = getPluginSettingsAndView(descriptor, extension);
return new ConfigRepoPluginInfo(descriptor, image(descriptor.id()), pluggableInstanceSettings, capabilities(des... | @Test
public void shouldContinueWithBuildingPluginInfoIfPluginSettingsIsNotProvidedByPlugin() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
doThrow(new RuntimeException("foo")).when(extension).getPluginSettingsConfiguration("plugin1");
... |
@Override
public void getManagedLedgerInfo(String ledgerName, boolean createIfMissing, Map<String, String> properties,
MetaStoreCallback<ManagedLedgerInfo> callback) {
// Try to get the content or create an empty node
String path = PREFIX + ledgerName;
store.get(path)
... | @Test(timeOut = 20000)
void readMalformedML() throws Exception {
MetaStore store = new MetaStoreImpl(metadataStore, executor);
metadataStore.put("/managed-ledgers/my_test", "non-valid".getBytes(), Optional.empty()).join();
final CountDownLatch latch = new CountDownLatch(1);
store.g... |
public void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
K[] keyTable = this.keyTable;
V[] valueTable = this.valueTable;
int i = keyTable.length;
while (i-- > 0) {
K key = keyTable[i];
if (key == null) {
continue;
}
V value = valu... | @Test
public void testForEach() {
FuryObjectMap<String, String> map = new ObjectMap<>(4, 0.2f);
Map<String, String> hashMap = new HashMap<>();
for (int i = 0; i < 100; i++) {
map.put("k" + i, "v" + i);
hashMap.put("k" + i, "v" + i);
}
Map<String, String> hashMap2 = new HashMap<>();
... |
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
return partition(topic, key, keyBytes, value, valueBytes, cluster, cluster.partitionsForTopic(topic).size());
} | @Test
public void testKeyPartitionIsStable() {
@SuppressWarnings("deprecation")
final Partitioner partitioner = new DefaultPartitioner();
final Cluster cluster = new Cluster("clusterId", asList(NODES), PARTITIONS,
Collections.emptySet(), Collections.emptySet());
int parti... |
public Column getColumn(String value) {
Matcher m = PATTERN.matcher(value);
if (!m.matches()) {
throw new IllegalArgumentException("value " + value + " is not a valid column definition");
}
String name = m.group(1);
String type = m.group(6);
type = type == nu... | @Test
public void testGetDollarArrayTypedColumn() {
ColumnFactory f = new ColumnFactory();
Column column = f.getColumn("$column: Long[]");
assertThat(column instanceof ArrayColumn).isTrue();
assertThat(column.getName()).isEqualTo("$column");
assertThat(column.getCellType()).i... |
public Tracking<DefaultIssue, DefaultIssue> track(Component component, Input<DefaultIssue> rawInput) {
Input<DefaultIssue> openBaseIssuesInput = baseInputFactory.create(component);
NonClosedTracking<DefaultIssue, DefaultIssue> openIssueTracking = tracker.trackNonClosed(rawInput, openBaseIssuesInput);
if (op... | @Test
public void track_loadChanges_on_matched_closed_issues() {
ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).build();
when(baseInputFactory.create(component)).thenReturn(openIssuesInput);
when(closedIssuesInputFactory.create(component)).thenReturn(closedIssuesInput);
wh... |
@Asn1Property(order=0)
public Body getBody() {
return body;
} | @Test
public void shouldVerifyNikCvca() throws IOException {
byte[] data = Resources.toByteArray(Resources.getResource("nik/tv/cvca.cvcert"));
final CvCertificate cert = mapper.read(data, CvCertificate.class);
assertDoesNotThrow(() -> new SignatureService().verify(cert, cert.getBody().getPub... |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
if (isGrayImage(image))
{
return createFromGrayImage(image, document);
}
// We try to encode the image with predictor
if (USE_PREDICTOR_ENCODER... | @Test
void testCreateLosslessFromImage4BYTE_ABGR() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));
// create an ARGB image
int w = image.getWidth();
int h = image.getHeight()... |
protected List<ResourceRequest> packageRequests(
List<ContainerSimulator> csList, int priority) {
// create requests
Map<Long, Map<String, ResourceRequest>> rackLocalRequests =
new HashMap<>();
Map<Long, Map<String, ResourceRequest>> nodeLocalRequests =
new HashMap<>();
Map<Lon... | @Test
public void testPackageRequests() throws YarnException {
MockAMSimulator app = new MockAMSimulator();
List<ContainerSimulator> containerSimulators = new ArrayList<>();
Resource resource = Resources.createResource(1024);
int priority = 1;
ExecutionType execType = ExecutionType.GUARANTEED;
... |
public int size() {
return blocks.size();
} | @Test
public void shouldReturnSize() {
BlocksGroup group = newBlocksGroup(newBlock("a", 1), newBlock("b", 2));
assertThat(group.size(), is(2));
} |
@Override
@Deprecated
public <KR, VR> KStream<KR, VR> transform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, KeyValue<KR, VR>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(transformerSuppl... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNameOnTransformWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.transform(transformerSupplier, Named.as("transform"), (String) null));
... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Env env = (Env) o;
if (getName().equals(env.getName())) {
throw new RuntimeException(getName() + " is same environment name, but their En... | @Test
public void testEquals() {
assertEquals(Env.DEV, Env.valueOf("dEv"));
String name = "someEEEE";
Env.addEnvironment(name);
assertNotEquals(Env.valueOf(name), Env.DEV);
} |
public Schema addToSchema(Schema schema) {
validate(schema);
schema.addProp(LOGICAL_TYPE_PROP, name);
schema.setLogicalType(this);
return schema;
} | @Test
void fixedDecimalToFromJson() {
Schema schema = Schema.createFixed("aDecimal", null, null, 4);
LogicalTypes.decimal(9, 2).addToSchema(schema);
Schema parsed = new Schema.Parser().parse(schema.toString(true));
assertEquals(schema, parsed, "Constructed and parsed schemas should match");
} |
@Override
public void validTenant(Long id) {
TenantDO tenant = getTenant(id);
if (tenant == null) {
throw exception(TENANT_NOT_EXISTS);
}
if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
throw exception(TENANT_DISABLE, tenant.getName());
... | @Test
public void testValidTenant_disable() {
// mock 数据
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.DISABLE.getStatus()));
tenantMapper.insert(tenant);
// 调用,并断言业务异常
assertServiceException(() -> tenantService.validTenant(1L), TEN... |
public static int compareObVersion(String version1, String version2) {
if (version1 == null || version2 == null) {
throw new RuntimeException("can not compare null version");
}
ObVersion v1 = new ObVersion(version1);
ObVersion v2 = new ObVersion(version2);
return v1.c... | @Test
public void compareObVersionTest() {
assert ObReaderUtils.compareObVersion("2.2.70", "3.2.2") == -1;
assert ObReaderUtils.compareObVersion("2.2.70", "2.2.50") == 1;
assert ObReaderUtils.compareObVersion("2.2.70", "3.1.2") == -1;
assert ObReaderUtils.compareObVersion("3.1.2", "3... |
@Override
public Schema getSourceSchema() {
return sourceSchema;
} | @Test
public void renameBadlyFormattedSchemaWithAltCharMaskConfiguredTest() throws IOException {
TypedProperties props = Helpers.setupSchemaOnDFS("streamer-config", "file_schema_provider_invalid.avsc");
props.put(SANITIZE_SCHEMA_FIELD_NAMES.key(), "true");
props.put(SCHEMA_FIELD_NAME_INVALID_CHAR_MASK.key... |
public static KiePMMLMiningField getKiePMMLMiningField(final MiningField toConvert, final Field<?> field) {
String name = toConvert.getName() != null ?toConvert.getName() : "" + toConvert.hashCode();
final FIELD_USAGE_TYPE fieldUsageType = toConvert.getUsageType() != null ?
FIELD_USAGE_T... | @Test
void getKiePMMLMiningField() {
DataField dataField = getRandomDataField();
MiningField toConvert = getRandomMiningField(dataField);
KiePMMLMiningField toVerify = KiePMMLMiningFieldInstanceFactory.getKiePMMLMiningField(toConvert, dataField);
commonVerifyKiePMMLMiningField(toVeri... |
@ApiOperation(value = "Delete a comment on a historic process instance", tags = { "History Process" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the historic process instance and comment were found and the comment is deleted. Response body is left empty intentiona... | @Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testDeleteComment() throws Exception {
ProcessInstance pi = null;
try {
pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");
// Add a comment ... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
String surfaceTag = readerWay.getTag("surface");
Surface surface = Surface.find(surfaceTag);
if (surface == MISSING)
return;
surfaceEnc.setEnum(fals... | @Test
public void testSynonyms() {
IntsRef relFlags = new IntsRef(2);
ReaderWay readerWay = new ReaderWay(1);
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
readerWay.setTag("highway", "primary");
readerWay.setTag("surface", "metal");
... |
public static <T> Fields<T> create() {
return fieldAccess(FieldAccessDescriptor.create());
} | @Test
@Category(NeedsRunner.class)
public void testSimpleSelectRename() {
PCollection<Schema1SelectedRenamed> rows =
pipeline
.apply(Create.of(Schema1.create()))
.apply(
Select.<Schema1>create()
.withFieldNameAs("field1", "fieldOne")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.