focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public static <T, R> Supplier<R> andThen(Supplier<T> supplier, Function<T, R> resultHandler) {
return () -> resultHandler.apply(supplier.get());
} | @Test
public void shouldChainSupplierAndRecoverWithErrorHandler() {
Supplier<String> supplier = () -> {
throw new RuntimeException("BAM!");
};
Supplier<String> supplierWithRecovery = SupplierUtils
.andThen(supplier, (result) -> result, ex -> "Bla");
String result = supplierWithRecovery.get();
assertThat(result).isEqualTo("Bla");
} |
public static NetworkPolicyPeer createPeer(Map<String, String> podSelector, LabelSelector namespaceSelector) {
return new NetworkPolicyPeerBuilder()
.withNewPodSelector()
.withMatchLabels(podSelector)
.endPodSelector()
.withNamespaceSelector(namespaceSelector)
.build();
} | @Test
public void testCreatePeerWithPodLabelsAndNamespaceSelector() {
NetworkPolicyPeer peer = NetworkPolicyUtils.createPeer(Map.of("labelKey", "labelValue"), new LabelSelectorBuilder().withMatchLabels(Map.of("nsLabelKey", "nsLabelValue")).build());
assertThat(peer.getNamespaceSelector().getMatchLabels(), is(Map.of("nsLabelKey", "nsLabelValue")));
assertThat(peer.getPodSelector().getMatchLabels(), is(Map.of("labelKey", "labelValue")));
} |
public Object evaluate(final ProcessingDTO processingDTO,
final List<Object> paramValues) {
final List<KiePMMLNameValue> kiePMMLNameValues = new ArrayList<>();
if (parameterFields != null) {
if (paramValues == null || paramValues.size() < parameterFields.size()) {
throw new IllegalArgumentException("Expected at least " + parameterFields.size() + " arguments for " + name + " DefineFunction");
}
for (int i = 0; i < parameterFields.size(); i++) {
kiePMMLNameValues.add(new KiePMMLNameValue(parameterFields.get(i).getName(), paramValues.get(i)));
}
}
for (KiePMMLNameValue kiePMMLNameValue : kiePMMLNameValues) {
processingDTO.addKiePMMLNameValue(kiePMMLNameValue);
}
return commonEvaluate(kiePMMLExpression.evaluate(processingDTO), dataType);
} | @Test
void evaluateFromConstant() {
// <DefineFunction name="CUSTOM_FUNCTION" optype="continuous" dataType="double">
// <Constant>100.0</Constant>
// </DefineFunction>
final KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant(PARAM_1, Collections.emptyList(), value1, null);
final KiePMMLDefineFunction defineFunction = new KiePMMLDefineFunction(CUSTOM_FUNCTION, Collections.emptyList(),
null,
OP_TYPE.CONTINUOUS,
Collections.emptyList(),
kiePMMLConstant1);
ProcessingDTO processingDTO = getProcessingDTO(Collections.emptyList());
Object retrieved = defineFunction.evaluate(processingDTO, Collections.emptyList());
assertThat(retrieved).isEqualTo(value1);
} |
public void addHeader(String key, String value) {
headers.put(key, value);
} | @Test
public void testAddHeader() {
String headerName = "customized_header0";
String headerValue = "customized_value0";
httpService.addHeader(headerName, headerValue);
assertTrue(httpService.getHeaders().get(headerName).equals(headerValue));
} |
public LongAdder getSinglePutMessageTopicTimesTotal(String topic) {
LongAdder rs = putMessageTopicTimesTotal.get(topic);
if (null == rs) {
rs = new LongAdder();
LongAdder previous = putMessageTopicTimesTotal.putIfAbsent(topic, rs);
if (previous != null) {
rs = previous;
}
}
return rs;
} | @Test
public void getSinglePutMessageTopicTimesTotal() throws Exception {
final StoreStatsService storeStatsService = new StoreStatsService();
int num = Runtime.getRuntime().availableProcessors() * 2;
for (int j = 0; j < 100; j++) {
final AtomicReference<LongAdder> reference = new AtomicReference<>(null);
final CountDownLatch latch = new CountDownLatch(num);
final CyclicBarrier barrier = new CyclicBarrier(num);
for (int i = 0; i < num; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
barrier.await();
LongAdder longAdder = storeStatsService.getSinglePutMessageTopicTimesTotal("test");
if (reference.compareAndSet(null, longAdder)) {
} else if (reference.get() != longAdder) {
throw new RuntimeException("Reference should be same!");
}
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}).start();
}
latch.await();
}
} |
@JsonIgnore
public List<String> getAllStepIds() {
List<String> allStepIds = new ArrayList<>(steps.size());
getAllStepIds(steps, allStepIds);
return allStepIds;
} | @Test
public void testGetAllStepIds() {
TypedStep step = new TypedStep();
step.setId("foo");
Workflow workflow =
Workflow.builder().steps(Collections.nCopies(Constants.STEP_LIST_SIZE_LIMIT, step)).build();
assertEquals(Constants.STEP_LIST_SIZE_LIMIT, workflow.getAllStepIds().size());
assertEquals(
Collections.nCopies(Constants.STEP_LIST_SIZE_LIMIT, "foo"), workflow.getAllStepIds());
} |
@Override
public void initialize(Configuration configuration, Properties tableProperties, Properties partitionProperties)
throws SerDeException {
super.initialize(configuration, tableProperties, partitionProperties);
jsonSerde.initialize(configuration, tableProperties, partitionProperties, false);
StructTypeInfo rowTypeInfo = jsonSerde.getTypeInfo();
cachedObjectInspector = HCatRecordObjectInspectorFactory.getHCatRecordObjectInspector(rowTypeInfo);
try {
schema = HCatSchemaUtils.getHCatSchema(rowTypeInfo).get(0).getStructSubSchema();
LOG.debug("schema : {}", schema);
LOG.debug("fields : {}", schema.getFieldNames());
} catch (HCatException e) {
throw new SerDeException(e);
}
} | @Test
public void testLooseJsonReadability() throws Exception {
Configuration conf = new Configuration();
Properties props = new Properties();
props.put(serdeConstants.LIST_COLUMNS, "s,k");
props.put(serdeConstants.LIST_COLUMN_TYPES, "struct<a:int,b:string>,int");
JsonSerDe rjsd = new JsonSerDe();
rjsd.initialize(conf, props, null);
Text jsonText = new Text("{ \"x\" : \"abc\" , "
+ " \"t\" : { \"a\":\"1\", \"b\":\"2\", \"c\":[ { \"x\":2 , \"y\":3 } , { \"x\":3 , \"y\":2 }] } ,"
+"\"s\" : { \"a\" : 2 , \"b\" : \"blah\", \"c\": \"woo\" } }");
List<Object> expected = new ArrayList<Object>();
List<Object> inner = new ArrayList<Object>();
inner.add(2);
inner.add("blah");
expected.add(inner);
expected.add(null);
HCatRecord expectedRecord = new DefaultHCatRecord(expected);
HCatRecord r = (HCatRecord) rjsd.deserialize(jsonText);
System.err.println("record : " + r.toString());
assertTrue(HCatDataCheckUtil.recordsEqual(r, expectedRecord));
} |
private synchronized boolean validateClientAcknowledgement(long h) {
if (h < 0) {
throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h);
}
if (h > MASK) {
throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but was: " + h);
}
final long oldH = clientProcessedStanzas.get();
final Long lastUnackedX = unacknowledgedServerStanzas.isEmpty() ? null : unacknowledgedServerStanzas.getLast().x;
return validateClientAcknowledgement(h, oldH, lastUnackedX);
} | @Test
public void testValidateClientAcknowledgement_clientAcksUnsentStanza() throws Exception
{
// Setup test fixture.
final long h = 1;
final long oldH = 0;
final Long lastUnackedX = null;
// Execute system under test.
final boolean result = StreamManager.validateClientAcknowledgement(h, oldH, lastUnackedX);
// Verify results.
assertFalse(result);
} |
@Override
protected String transform(ILoggingEvent event, String in) {
AnsiElement element = ELEMENTS.get(getFirstOption());
List<Marker> markers = event.getMarkerList();
if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) {
return in;
}
String replacement = element == null ? "_" : toAnsiString("_", element);
return in.replaceAll("[\n\r\t]", replacement);
} | @Test
void transformShouldReturnInputStringWhenLoggerIsSafe() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
} |
public static ServerId of(@Nullable String databaseId, String datasetId) {
if (databaseId != null) {
int databaseIdLength = databaseId.length();
checkArgument(databaseIdLength == DATABASE_ID_LENGTH, "Illegal databaseId length (%s)", databaseIdLength);
}
int datasetIdLength = datasetId.length();
checkArgument(datasetIdLength == DEPRECATED_SERVER_ID_LENGTH
|| datasetIdLength == NOT_UUID_DATASET_ID_LENGTH
|| datasetIdLength == UUID_DATASET_ID_LENGTH, "Illegal datasetId length (%s)", datasetIdLength);
return new ServerId(databaseId, datasetId);
} | @Test
@UseDataProvider("illegalDatasetIdLengths")
public void of_throws_IAE_if_datasetId_length_is_not_8(int illegalDatasetIdLengths) {
String datasetId = randomAlphabetic(illegalDatasetIdLengths);
String databaseId = randomAlphabetic(DATABASE_ID_LENGTH);
assertThatThrownBy(() -> ServerId.of(databaseId, datasetId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal datasetId length (" + illegalDatasetIdLengths + ")");
} |
public void processWa11(Wa11 wa11){
String oldANummer = CategorieUtil.findANummer(wa11.getCategorie());
String newANummer = wa11.getANummer();
digidXClient.updateANummer(oldANummer, newANummer);
logger.info("Finished processing Wa11 message");
} | @Test
public void testProcessWa11() {
String testAnummer = "SSSSSSSSSS";
String testNieuwAnummer = "SSSSSSSSSS";
String datumGeldigheid = "SSSSSSSS";
Wa11 testWa11 = TestDglMessagesUtil.createTestWa11(testAnummer, testNieuwAnummer, datumGeldigheid);
classUnderTest.processWa11(testWa11);
verify(digidXClient, times(1)).updateANummer(testAnummer, testNieuwAnummer);
classUnderTest.processWa11(testWa11);
verify(digidXClient, times(2)).updateANummer(testAnummer, testNieuwAnummer);
} |
public static <S> S load(Class<S> service, ClassLoader loader) throws EnhancedServiceNotFoundException {
return InnerEnhancedServiceLoader.getServiceLoader(service).load(loader, true);
} | @Test
public void testLoadByClassAndClassLoaderAndActivateName() {
Hello englishHello = EnhancedServiceLoader
.load(Hello.class, "EnglishHello", EnhancedServiceLoaderTest.class.getClassLoader());
assertThat(englishHello.say()).isEqualTo("hello!");
} |
public Stream<Flow> keepLastVersion(Stream<Flow> stream) {
return keepLastVersionCollector(stream);
} | @Test
void sameRevisionWithDeletedUnordered() {
Stream<Flow> stream = Stream.of(
create("test", "test", 1),
create("test", "test2", 2),
create("test", "test2", 4),
create("test", "test2", 2).toDeleted()
);
List<Flow> collect = flowService.keepLastVersion(stream).toList();
assertThat(collect.size(), is(1));
assertThat(collect.getFirst().isDeleted(), is(false));
assertThat(collect.getFirst().getRevision(), is(4));
} |
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) {
IClientConfig clientConfig = getRequestClientConfig(request);
Long originTimeout = getOriginReadTimeout();
Long requestTimeout = getRequestReadTimeout(clientConfig);
long computedTimeout;
if (originTimeout == null && requestTimeout == null) {
computedTimeout = MAX_OUTBOUND_READ_TIMEOUT_MS.get();
} else if (originTimeout == null || requestTimeout == null) {
computedTimeout = originTimeout == null ? requestTimeout : originTimeout;
} else {
// return the stricter (i.e. lower) of the two timeouts
computedTimeout = Math.min(originTimeout, requestTimeout);
}
// enforce max timeout upperbound
return Duration.ofMillis(Math.min(computedTimeout, MAX_OUTBOUND_READ_TIMEOUT_MS.get()));
} | @Test
void computeReadTimeout_default() {
Duration timeout = originTimeoutManager.computeReadTimeout(request, 1);
assertEquals(OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS.get(), timeout.toMillis());
} |
@Override
public List<String> getLineHashesMatchingDBVersion(Component component) {
return cache.computeIfAbsent(component, this::createLineHashesMatchingDBVersion);
} | @Test
public void should_create_hash_with_significant_code() {
LineRange[] lineRanges = {new LineRange(0, 1), null, new LineRange(1, 5)};
when(dbLineHashVersion.hasLineHashesWithSignificantCode(file)).thenReturn(true);
when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(lineRanges));
List<String> lineHashes = underTest.getLineHashesMatchingDBVersion(file);
assertLineHashes(lineHashes, "l", "", "ine3");
verify(dbLineHashVersion).hasLineHashesWithoutSignificantCode(file);
verifyNoMoreInteractions(dbLineHashVersion);
verify(significantCodeRepository).getRangesPerLine(file);
verifyNoMoreInteractions(significantCodeRepository);
} |
public Coin parse(String str) throws NumberFormatException {
return Coin.valueOf(parseValue(str, Coin.SMALLEST_UNIT_EXPONENT));
} | @Test
public void parse() {
assertEquals(Coin.COIN, NO_CODE.parse("1"));
assertEquals(Coin.COIN, NO_CODE.parse("1."));
assertEquals(Coin.COIN, NO_CODE.parse("1.0"));
assertEquals(Coin.COIN, NO_CODE.decimalMark(',').parse("1,0"));
assertEquals(Coin.COIN, NO_CODE.parse("01.0000000000"));
assertEquals(Coin.COIN, NO_CODE.positiveSign('+').parse("+1.0"));
assertEquals(Coin.COIN.negate(), NO_CODE.parse("-1"));
assertEquals(Coin.COIN.negate(), NO_CODE.parse("-1.0"));
assertEquals(Coin.CENT, NO_CODE.parse(".01"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.parse("1"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.parse("1.0"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.parse("01.0000000000"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.positiveSign('+').parse("+1.0"));
assertEquals(Coin.MILLICOIN.negate(), MonetaryFormat.MBTC.parse("-1"));
assertEquals(Coin.MILLICOIN.negate(), MonetaryFormat.MBTC.parse("-1.0"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.parse("1"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.parse("1.0"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.parse("01.0000000000"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.positiveSign('+').parse("+1.0"));
assertEquals(Coin.MICROCOIN.negate(), MonetaryFormat.UBTC.parse("-1"));
assertEquals(Coin.MICROCOIN.negate(), MonetaryFormat.UBTC.parse("-1.0"));
assertEquals(Coin.SATOSHI, MonetaryFormat.SAT.parse("1"));
assertEquals(Coin.SATOSHI, MonetaryFormat.SAT.parse("01"));
assertEquals(Coin.SATOSHI, MonetaryFormat.SAT.positiveSign('+').parse("+1"));
assertEquals(Coin.SATOSHI.negate(), MonetaryFormat.SAT.parse("-1"));
assertEquals(Coin.CENT, NO_CODE.withLocale(new Locale("hi", "IN")).parse(".०१")); // Devanagari
} |
public void merge(VectorClock other) {
for (Entry<UUID, Long> entry : other.replicaTimestamps.entrySet()) {
final UUID replicaId = entry.getKey();
final long mergingTimestamp = entry.getValue();
final long localTimestamp = replicaTimestamps.containsKey(replicaId)
? replicaTimestamps.get(replicaId)
: Long.MIN_VALUE;
replicaTimestamps.put(replicaId, Math.max(localTimestamp, mergingTimestamp));
}
} | @Test
public void testMerge() {
assertMerged(
vectorClock(uuidParams[0], 1),
vectorClock(),
vectorClock(uuidParams[0], 1));
assertMerged(
vectorClock(uuidParams[0], 1),
vectorClock(uuidParams[0], 2),
vectorClock(uuidParams[0], 2));
assertMerged(
vectorClock(uuidParams[0], 2),
vectorClock(uuidParams[0], 1),
vectorClock(uuidParams[0], 2));
assertMerged(
vectorClock(uuidParams[0], 3, uuidParams[1], 1),
vectorClock(uuidParams[0], 1, uuidParams[1], 2, uuidParams[2], 3),
vectorClock(uuidParams[0], 3, uuidParams[1], 2, uuidParams[2], 3));
} |
public static Type getTypeArgument(Type type) {
return getTypeArgument(type, 0);
} | @Test
public void getTypeArgumentTest() {
// 测试不继承父类,而是实现泛型接口时是否可以获取成功。
final Type typeArgument = TypeUtil.getTypeArgument(IPService.class);
assertEquals(String.class, typeArgument);
} |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testIdempotentResetWithInFlightReset() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST);
// Send the ListOffsets request to reset the position
offsetFetcher.resetPositionsIfNeeded();
consumerClient.pollNoWakeup();
assertFalse(subscriptions.hasValidPosition(tp0));
assertTrue(client.hasInFlightRequests());
// Now we get a seek from the user
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST);
client.respond(listOffsetResponse(Errors.NONE, 1L, 5L));
consumerClient.pollNoWakeup();
assertFalse(client.hasInFlightRequests());
assertFalse(subscriptions.isOffsetResetNeeded(tp0));
assertEquals(5L, subscriptions.position(tp0).offset);
} |
public Optional<ComputationState> get(String computationId) {
try {
return Optional.ofNullable(computationCache.get(computationId));
} catch (UncheckedExecutionException
| ExecutionException
| ComputationStateNotFoundException e) {
if (e.getCause() instanceof ComputationStateNotFoundException
|| e instanceof ComputationStateNotFoundException) {
LOG.error(
"Trying to fetch unknown computation={}, known computations are {}.",
computationId,
ImmutableSet.copyOf(computationCache.asMap().keySet()));
} else {
LOG.warn("Error occurred fetching computation for computationId={}", computationId, e);
}
}
return Optional.empty();
} | @Test
public void testGet_computationStateNotCachedOrFetchable() {
String computationId = "computationId";
when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
Optional<ComputationState> computationState = computationStateCache.get(computationId);
assertFalse(computationState.isPresent());
// Fetch again to make sure we call configFetcher and nulls/empty are not cached.
Optional<ComputationState> computationState2 = computationStateCache.get(computationId);
assertFalse(computationState2.isPresent());
verify(configFetcher, times(2)).fetchConfig(eq(computationId));
} |
protected String getServiceConfig(final List<ServiceInstance> instances) {
for (final ServiceInstance inst : instances) {
final Map<String, String> metadata = inst.getMetadata();
if (metadata == null || metadata.isEmpty()) {
continue;
}
final String metaValue = metadata.get(CLOUD_DISCOVERY_METADATA_SERVICE_CONFIG);
if (metaValue != null && !metaValue.isEmpty()) {
return metaValue;
}
}
return null;
} | @Test
void testValidServiceConfig() {
String validServiceConfig = """
{
"loadBalancingConfig": [
{"round_robin": {}}
],
"methodConfig": [
{
"name": [{}],
"retryPolicy": {
"maxAttempts": 5,
"initialBackoff": "0.05s",
"maxBackoff": "1s",
"backoffMultiplier": 2,
"retryableStatusCodes": [
"UNAVAILABLE",
"ABORTED",
"DATA_LOSS",
"INTERNAL",
"DEADLINE_EXCEEDED"
]
},
"timeout": "5s"
}
]
}
""";
TestableListener listener = resolveServiceAndVerify("test1", validServiceConfig);
NameResolver.ConfigOrError serviceConf = listener.getResult().getServiceConfig();
assertThat(serviceConf).isNotNull();
assertThat(serviceConf.getConfig()).isNotNull();
assertThat(serviceConf.getError()).isNull();
} |
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
if(failure != null) {
if(log.isDebugEnabled()) {
log.debug(String.format("Skip setting timestamp for %s due to previous failure %s", file, failure.getMessage()));
}
throw new FTPExceptionMappingService().map("Cannot change timestamp of {0}", failure, file);
}
try {
if(null != status.getModified()) {
final MDTMSecondsDateFormatter formatter = new MDTMSecondsDateFormatter();
if(!session.getClient().setModificationTime(file.getAbsolute(),
formatter.format(status.getModified(), TimeZone.getTimeZone("UTC")))) {
throw failure = new FTPException(session.getClient().getReplyCode(),
session.getClient().getReplyString());
}
}
}
catch(IOException e) {
throw new FTPExceptionMappingService().map("Cannot change timestamp of {0}", e, file);
}
} | @Test
public void testSetTimestamp() throws Exception {
final Path home = new FTPWorkdirService(session).find();
final long modified = System.currentTimeMillis();
final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
new FTPTouchFeature(session).touch(test, new TransferStatus());
new FTPMFMTTimestampFeature(session).setTimestamp(test, modified);
assertEquals(modified / 1000 * 1000, new FTPListService(session, null, TimeZone.getDefault()).list(home, new DisabledListProgressListener()).get(test).attributes().getModificationDate());
new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(false);
}
boolean result = false;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not" +
" a Boolean"));
} else {
if (element != null) {
result |= (Boolean) element;
}
}
}
return FEELFnResult.ofResult(result);
} | @Test
void invokeArrayParamEmptyArray() {
FunctionTestUtil.assertResult(anyFunction.invoke(new Object[]{}), false);
} |
@Override
public RexNode visit(CallExpression call) {
boolean isBatchMode = unwrapContext(relBuilder).isBatchMode();
for (CallExpressionConvertRule rule : getFunctionConvertChain(isBatchMode)) {
Optional<RexNode> converted = rule.convert(call, newFunctionContext());
if (converted.isPresent()) {
return converted.get();
}
}
throw new RuntimeException("Unknown call expression: " + call);
} | @Test
void testDateLiteral() {
RexNode rex =
converter.visit(
valueLiteral(LocalDate.parse("2012-12-12"), DataTypes.DATE().notNull()));
assertThat(((RexLiteral) rex).getValueAs(DateString.class))
.isEqualTo(new DateString("2012-12-12"));
assertThat(rex.getType().getSqlTypeName()).isEqualTo(SqlTypeName.DATE);
} |
@Udf
public Integer least(@UdfParameter final Integer val, @UdfParameter final Integer... vals) {
return (vals == null) ? null : Stream.concat(Stream.of(val), Arrays.stream(vals))
.filter(Objects::nonNull)
.min(Integer::compareTo)
.orElse(null);
} | @Test
public void shouldWorkWithoutImplicitCasting() {
assertThat(leastUDF.least(0, 1, -1, 2, -2), is(-2));
assertThat(leastUDF.least(0L, 1L, -1L, 2L, -2L), is(-2L));
assertThat(leastUDF.least(0D, .1, -.1, .2, -.2), is(-.2));
assertThat(leastUDF.least(new BigDecimal("0"), new BigDecimal(".1"), new BigDecimal("-.1"), new BigDecimal(".2"), new BigDecimal("-.2")), is(new BigDecimal("-.2")));
assertThat(leastUDF.least("apple", "banana", "aardvark"), is("aardvark"));
assertThat(leastUDF.least(toBytes("apple"), toBytes("banana"), toBytes("aardvark")), is(toBytes("aardvark")));
assertThat(leastUDF.least(new Date(10), new Date(0), new Date(-5), new Date(100), new Date(2)), is(new Date(-5)));
assertThat(leastUDF.least(new Time(10), new Time(0), new Time(-5), new Time(100), new Time(2)), is(new Time(-5)));
assertThat(leastUDF.least(new Timestamp(10), new Timestamp(0), new Timestamp(-5), new Timestamp(100), new Timestamp(2)), is(new Timestamp(-5)));
} |
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException {
final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest);
if (samlRequest instanceof AuthenticationRequest) {
dcMetadataResponseMapper.dcMetadataToAuthenticationRequest((AuthenticationRequest) samlRequest, metadataFromDc, samlRequest.getServiceEntityId());
} else {
dcMetadataResponseMapper.dcMetadataToSamlRequest(samlRequest, metadataFromDc);
}
} | @Test
public void resolveDcMetadataNoFederationTest() throws DienstencatalogusException {
DcMetadataResponse dcMetadataResponse = dcClientStubGetMetadata(stubsCaMetadataFile, null, 1L);
when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(dcMetadataResponse);
SamlRequest request = new AuthenticationRequest();
request.setConnectionEntityId(CONNECTION_ENTITY_ID);
request.setServiceEntityId(SERVICE_ENTITY_ID);
assertDoesNotThrow(() -> dcMetadataService.resolveDcMetadata(request));
} |
@Override
public CompletableFuture<JobManagerRunnerResult> getResultFuture() {
return resultFuture;
} | @Test
void testJobMasterTerminationIsHandled() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
CompletableFuture<Void> jobMasterTerminationFuture = new CompletableFuture<>();
TestingJobMasterService testingJobMasterService =
new TestingJobMasterService("localhost", jobMasterTerminationFuture, null);
jobMasterServiceFuture.complete(testingJobMasterService);
RuntimeException testException = new RuntimeException("Fake exception from JobMaster");
jobMasterTerminationFuture.completeExceptionally(testException);
assertThatFuture(serviceProcess.getResultFuture())
.eventuallyFailsWith(ExecutionException.class)
.extracting(FlinkAssertions::chainOfCauses, FlinkAssertions.STREAM_THROWABLE)
.anySatisfy(t -> assertThat(t).isEqualTo(testException));
} |
@Override
public Endpoint<Http2LocalFlowController> local() {
return localEndpoint;
} | @Test
public void clientLocalCreateStreamExhaustedSpace() throws Http2Exception {
client.local().createStream(MAX_VALUE, true);
Http2Exception expected = assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
client.local().createStream(MAX_VALUE, true);
}
});
assertEquals(Http2Error.REFUSED_STREAM, expected.error());
assertEquals(Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN, expected.shutdownHint());
} |
@Override
public final boolean match(final Request request) {
Optional<Document> requestDocument = extractDocument(request, extractor);
return requestDocument.filter(actual -> tryToMatch(request, actual)).isPresent();
} | @Test
public void should_return_false_for_empty_content() {
XmlRequestMatcher unitUnderTest = new XmlContentRequestMatcher(text("<request><parameters><id>1</id></parameters></request>"), new ContentRequestExtractor());
HttpRequest request = DefaultHttpRequest.builder().withStringContent("").build();
assertThat(unitUnderTest.match(request), is(false));
} |
public static boolean isPower2(int x) {
return x > 0 && (x & (x - 1)) == 0;
} | @Test
public void testIsPower2() {
System.out.println("isPower2");
assertFalse(MathEx.isPower2(-1));
assertFalse(MathEx.isPower2(0));
assertTrue(MathEx.isPower2(1));
assertTrue(MathEx.isPower2(2));
assertFalse(MathEx.isPower2(3));
assertTrue(MathEx.isPower2(4));
assertTrue(MathEx.isPower2(8));
assertTrue(MathEx.isPower2(16));
assertTrue(MathEx.isPower2(32));
assertTrue(MathEx.isPower2(64));
assertTrue(MathEx.isPower2(128));
assertTrue(MathEx.isPower2(256));
assertTrue(MathEx.isPower2(512));
assertTrue(MathEx.isPower2(1024));
assertTrue(MathEx.isPower2(65536));
assertTrue(MathEx.isPower2(131072));
} |
@Override
public SmileResponse<T> handle(Request request, Response response)
{
byte[] bytes = readResponseBytes(response);
String contentType = response.getHeader(CONTENT_TYPE);
if ((contentType == null) || !MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) {
return new SmileResponse<>(response.getStatusCode(), response.getHeaders(), bytes);
}
return new SmileResponse<>(response.getStatusCode(), response.getHeaders(), smileCodec, bytes);
} | @Test
public void testSmileErrorResponse()
{
User user = new User("Joe", 25);
byte[] smileBytes = codec.toBytes(user);
SmileResponse<User> response = handler.handle(null, mockResponse(INTERNAL_SERVER_ERROR, MEDIA_TYPE_SMILE, smileBytes));
assertTrue(response.hasValue());
assertEquals(response.getStatusCode(), INTERNAL_SERVER_ERROR.code());
assertEquals(response.getResponseBytes(), response.getSmileBytes());
} |
static Map<String, Object> appendSerializerToConfig(Map<String, Object> configs,
Serializer<?> keySerializer,
Serializer<?> valueSerializer) {
// validate serializer configuration, if the passed serializer instance is null, the user must explicitly set a valid serializer configuration value
Map<String, Object> newConfigs = new HashMap<>(configs);
if (keySerializer != null)
newConfigs.put(KEY_SERIALIZER_CLASS_CONFIG, keySerializer.getClass());
else if (newConfigs.get(KEY_SERIALIZER_CLASS_CONFIG) == null)
throw new ConfigException(KEY_SERIALIZER_CLASS_CONFIG, null, "must be non-null.");
if (valueSerializer != null)
newConfigs.put(VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer.getClass());
else if (newConfigs.get(VALUE_SERIALIZER_CLASS_CONFIG) == null)
throw new ConfigException(VALUE_SERIALIZER_CLASS_CONFIG, null, "must be non-null.");
return newConfigs;
} | @Test
public void testAppendSerializerToConfigWithException() {
Map<String, Object> configs = new HashMap<>();
configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, null);
configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializerClass);
assertThrows(ConfigException.class, () -> ProducerConfig.appendSerializerToConfig(configs, null, valueSerializer));
configs.clear();
configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializerClass);
configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, null);
assertThrows(ConfigException.class, () -> ProducerConfig.appendSerializerToConfig(configs, keySerializer, null));
} |
@Override
public MongoPaginationHelper<T> perPage(int perPage) {
return new DefaultMongoPaginationHelper<>(collection, filter, sort, perPage, includeGrandTotal,
grandTotalFilter, collation);
} | @Test
void testPerPage() {
assertThat(paginationHelper.page(1))
.isEqualTo(paginationHelper.perPage(0).page(1))
.isEqualTo(paginationHelper.perPage(0).page(1, alwaysTrue()))
.containsExactlyElementsOf(DTOs);
final MongoPaginationHelper<DTO> helper = paginationHelper.perPage(8);
assertThat(helper.page(1)).containsExactlyElementsOf(DTOs.subList(0, 8));
assertThat(helper.page(1, alwaysTrue())).containsExactlyElementsOf(DTOs.subList(0, 8));
assertThat(helper.page(2)).containsExactlyElementsOf(DTOs.subList(8, 16));
assertThat(helper.page(2, alwaysTrue())).containsExactlyElementsOf(DTOs.subList(8, 16));
assertThat(helper.page(1).pagination()).satisfies(pagination -> {
assertThat(pagination.total()).isEqualTo(16);
assertThat(pagination.page()).isEqualTo(1);
assertThat(pagination.perPage()).isEqualTo(8);
});
} |
public void handleWatchTopicList(NamespaceName namespaceName, long watcherId, long requestId, Pattern topicsPattern,
String topicsHash, Semaphore lookupSemaphore) {
if (!enableSubscriptionPatternEvaluation || topicsPattern.pattern().length() > maxSubscriptionPatternLength) {
String msg = "Unable to create topic list watcher: ";
if (!enableSubscriptionPatternEvaluation) {
msg += "Evaluating subscription patterns is disabled.";
} else {
msg += "Pattern longer than maximum: " + maxSubscriptionPatternLength;
}
log.warn("[{}] {} on namespace {}", connection.toString(), msg, namespaceName);
connection.getCommandSender().sendErrorResponse(requestId, ServerError.NotAllowedError, msg);
lookupSemaphore.release();
return;
}
CompletableFuture<TopicListWatcher> watcherFuture = new CompletableFuture<>();
CompletableFuture<TopicListWatcher> existingWatcherFuture = watchers.putIfAbsent(watcherId, watcherFuture);
if (existingWatcherFuture != null) {
if (existingWatcherFuture.isDone() && !existingWatcherFuture.isCompletedExceptionally()) {
TopicListWatcher watcher = existingWatcherFuture.getNow(null);
log.info("[{}] Watcher with the same id is already created:"
+ " watcherId={}, watcher={}",
connection.toString(), watcherId, watcher);
watcherFuture = existingWatcherFuture;
} else {
// There was an early request to create a watcher with the same watcherId. This can happen when
// client timeout is lower the broker timeouts. We need to wait until the previous watcher
// creation request either completes or fails.
log.warn("[{}] Watcher with id is already present on the connection,"
+ " consumerId={}", connection.toString(), watcherId);
ServerError error;
if (!existingWatcherFuture.isDone()) {
error = ServerError.ServiceNotReady;
} else {
error = ServerError.UnknownError;
watchers.remove(watcherId, existingWatcherFuture);
}
connection.getCommandSender().sendErrorResponse(requestId, error,
"Topic list watcher is already present on the connection");
lookupSemaphore.release();
return;
}
} else {
initializeTopicsListWatcher(watcherFuture, namespaceName, watcherId, topicsPattern);
}
CompletableFuture<TopicListWatcher> finalWatcherFuture = watcherFuture;
finalWatcherFuture.thenAccept(watcher -> {
List<String> topicList = watcher.getMatchingTopics();
String hash = TopicList.calculateHash(topicList);
if (hash.equals(topicsHash)) {
topicList = Collections.emptyList();
}
if (log.isDebugEnabled()) {
log.debug(
"[{}] Received WatchTopicList for namespace [//{}] by {}",
connection.toString(), namespaceName, requestId);
}
connection.getCommandSender().sendWatchTopicListSuccess(requestId, watcherId, hash, topicList);
lookupSemaphore.release();
})
.exceptionally(ex -> {
log.warn("[{}] Error WatchTopicList for namespace [//{}] by {}",
connection.toString(), namespaceName, requestId);
connection.getCommandSender().sendErrorResponse(requestId,
BrokerServiceException.getClientErrorCode(
new BrokerServiceException.ServerMetadataException(ex)), ex.getMessage());
watchers.remove(watcherId, finalWatcherFuture);
lookupSemaphore.release();
return null;
});
} | @Test
public void testCommandWatchErrorResponse() {
topicListService.handleWatchTopicList(
NamespaceName.get("tenant/ns"),
13,
7,
Pattern.compile("persistent://tenant/ns/topic\\d"),
null,
lookupSemaphore);
topicListFuture.completeExceptionally(new PulsarServerException("Error"));
Assert.assertEquals(1, lookupSemaphore.availablePermits());
verifyNoInteractions(topicResources);
verify(connection.getCommandSender()).sendErrorResponse(eq(7L), any(ServerError.class),
eq(PulsarServerException.class.getCanonicalName() + ": Error"));
} |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariablesStatement sqlStatement, final ContextManager contextManager) {
ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData();
Collection<LocalDataQueryResultRow> result = ConfigurationPropertyKey.getKeyNames().stream()
.filter(each -> !ConfigurationPropertyKey.SQL_SHOW.name().equals(each) && !ConfigurationPropertyKey.SQL_SIMPLE.name().equals(each))
.map(each -> new LocalDataQueryResultRow(each.toLowerCase(), getStringResult(metaData.getProps().getValue(ConfigurationPropertyKey.valueOf(each))))).collect(Collectors.toList());
result.addAll(TemporaryConfigurationPropertyKey.getKeyNames().stream()
.map(each -> new LocalDataQueryResultRow(each.toLowerCase(), getStringResult(metaData.getTemporaryProps().getValue(TemporaryConfigurationPropertyKey.valueOf(each)))))
.collect(Collectors.toList()));
result.add(new LocalDataQueryResultRow(DistSQLVariable.CACHED_CONNECTIONS.name().toLowerCase(), connectionContext.getConnectionSize()));
addLoggingPropsRows(metaData, result);
if (sqlStatement.getLikePattern().isPresent()) {
String pattern = RegexUtils.convertLikePatternToRegex(sqlStatement.getLikePattern().get());
result = result.stream().filter(each -> Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher((String) each.getCell(1)).matches()).collect(Collectors.toList());
}
return result.stream().sorted(Comparator.comparing(each -> each.getCell(1).toString())).collect(Collectors.toList());
} | @Test
void assertExecute() {
when(contextManager.getMetaDataContexts().getMetaData().getProps()).thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property("system-log-level", "INFO"))));
when(contextManager.getMetaDataContexts().getMetaData().getTemporaryProps())
.thenReturn(new TemporaryConfigurationProperties(PropertiesBuilder.build(new Property("proxy-meta-data-collector-enabled", Boolean.FALSE.toString()))));
ShowDistVariablesExecutor executor = new ShowDistVariablesExecutor();
executor.setConnectionContext(new DistSQLConnectionContext(mock(QueryContext.class), 1,
mock(DatabaseType.class), mock(DatabaseConnectionManager.class), mock(ExecutorStatementManager.class)));
Collection<LocalDataQueryResultRow> actual = executor.getRows(mock(ShowDistVariablesStatement.class), contextManager);
assertThat(actual.size(), is(21));
LocalDataQueryResultRow row = actual.iterator().next();
assertThat(row.getCell(1), is("agent_plugins_enabled"));
assertThat(row.getCell(2), is("true"));
} |
public static DeviceDescription parseJuniperDescription(DeviceId deviceId,
HierarchicalConfiguration sysInfoCfg,
String chassisMacAddresses) {
HierarchicalConfiguration info = sysInfoCfg.configurationAt(SYS_INFO);
String hw = info.getString(HW_MODEL) == null ? UNKNOWN : info.getString(HW_MODEL);
String sw = UNKNOWN;
if (info.getString(OS_NAME) != null || info.getString(OS_VER) != null) {
sw = info.getString(OS_NAME) + " " + info.getString(OS_VER);
}
String serial = info.getString(SER_NUM) == null ? UNKNOWN : info.getString(SER_NUM);
return new DefaultDeviceDescription(deviceId.uri(), ROUTER,
JUNIPER, hw, sw, serial,
extractChassisId(chassisMacAddresses),
DefaultAnnotations.EMPTY);
} | @Test
public void testDeviceDescriptionParsedFromJunos19() throws IOException {
HierarchicalConfiguration getSystemInfoResp = XmlConfigParser.loadXml(
getClass().getResourceAsStream("/Junos_get-system-information_response_19.2.xml"));
String chassisText = CharStreams.toString(
new InputStreamReader(
getClass().getResourceAsStream("/Junos_get-chassis-mac-addresses_response_19.2.xml")));
DeviceDescription expected =
new DefaultDeviceDescription(URI.create(DEVICE_ID), ROUTER, "JUNIPER", "acx6360-or",
"junos 19.2I-20190228_dev_common.0.2316", "DX004", new ChassisId("f4b52f1f81c0"));
assertEquals(expected, JuniperUtils.parseJuniperDescription(deviceId, getSystemInfoResp, chassisText));
} |
public static String join(List<String> list, String splitter) {
if (list == null) {
return null;
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
str.append(list.get(i));
if (i == list.size() - 1) {
break;
}
str.append(splitter);
}
return str.toString();
} | @Test
public void testJoin() {
List<String> list = Arrays.asList("groupA=DENY", "groupB=PUB|SUB", "groupC=SUB");
String comma = ",";
assertEquals("groupA=DENY,groupB=PUB|SUB,groupC=SUB", UtilAll.join(list, comma));
assertEquals(null, UtilAll.join(null, comma));
List<String> objects = Collections.emptyList();
assertEquals("", UtilAll.join(objects, comma));
} |
@Override
public void setOriginalFile(Component file, OriginalFile originalFile) {
storeOriginalFileInCache(originalFiles, file, originalFile);
} | @Test
public void setOriginalFile_throws_ISE_if_settings_another_originalFile() {
underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE);
assertThatThrownBy(() -> underTest.setOriginalFile(SOME_FILE, new MovedFilesRepository.OriginalFile("uudi", "key")))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Original file OriginalFile{uuid='uuid for 100', key='key for 100'} " +
"already registered for file ReportComponent{ref=1, key='key_1', type=FILE}");
} |
public Optional<String> evaluate(Number toEvaluate) {
return interval.isIn(toEvaluate) ? Optional.of(binValue) : Optional.empty();
} | @Test
void evaluateClosedOpen() {
KiePMMLDiscretizeBin kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(null, 20,
CLOSURE.CLOSED_OPEN));
Optional<String> retrieved = kiePMMLDiscretizeBin.evaluate(10);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(20);
assertThat(retrieved).isNotPresent();
retrieved = kiePMMLDiscretizeBin.evaluate(30);
assertThat(retrieved).isNotPresent();
kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(20, null, CLOSURE.CLOSED_OPEN));
retrieved = kiePMMLDiscretizeBin.evaluate(30);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(20);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(10);
assertThat(retrieved).isNotPresent();
kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(20, 40, CLOSURE.CLOSED_OPEN));
retrieved = kiePMMLDiscretizeBin.evaluate(30);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(10);
assertThat(retrieved).isNotPresent();
retrieved = kiePMMLDiscretizeBin.evaluate(20);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(40);
assertThat(retrieved).isNotPresent();
retrieved = kiePMMLDiscretizeBin.evaluate(50);
assertThat(retrieved).isNotPresent();
} |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testNotNaN() {
boolean shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("all_nans")).eval(FILE);
assertThat(shouldRead).as("Should not match: all values are nan").isFalse();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("some_nans")).eval(FILE);
assertThat(shouldRead)
.as("Should not match: at least one nan value in some nan column")
.isFalse();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("no_nans")).eval(FILE);
assertThat(shouldRead).as("Should match: no value is nan").isTrue();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("all_nulls_double")).eval(FILE);
assertThat(shouldRead).as("Should match: no nan value in all null column").isTrue();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("no_nan_stats")).eval(FILE);
assertThat(shouldRead).as("Should not match: cannot determine without nan stats").isFalse();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("all_nans_v1_stats")).eval(FILE);
assertThat(shouldRead).as("Should not match: all values are nan").isFalse();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notNaN("nan_and_null_only")).eval(FILE);
assertThat(shouldRead).as("Should not match: null values are not nan").isFalse();
} |
@Override
public void foreach(final ForeachAction<? super K, ? super V> action) {
foreach(action, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullActionOnForEach() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.foreach(null));
assertThat(exception.getMessage(), equalTo("action can't be null"));
} |
public static GenericRecord dataMapToGenericRecord(DataMap map, RecordDataSchema dataSchema) throws DataTranslationException
{
Schema avroSchema = SchemaTranslator.dataToAvroSchema(dataSchema);
return dataMapToGenericRecord(map, dataSchema, avroSchema, null);
} | @Test
public void testMissingDefaultFieldsOnDataMap() throws IOException
{
final String SCHEMA =
"{" +
" \"type\":\"record\"," +
" \"name\":\"Foo\"," +
" \"fields\":[" +
" {" +
" \"name\":\"field1\"," +
" \"type\":\"string\"" +
" }," +
" {" +
" \"name\":\"field2\"," +
" \"type\":{" +
" \"type\":\"array\"," +
" \"items\":\"string\"" +
" }," +
" \"default\":[ ]" +
" }" +
" ]" +
"}";
RecordDataSchema pegasusSchema = (RecordDataSchema)TestUtil.dataSchemaFromString(SCHEMA);
Schema avroShema = Schema.parse(SCHEMA);
DataMap dataMap = new DataMap();
dataMap.put("field1", "test");
GenericRecord record = DataTranslator.dataMapToGenericRecord(dataMap, pegasusSchema, avroShema);
assertEquals(record.get("field2"), new GenericData.Array<>(0, Schema.createArray(
Schema.create(Schema.Type.STRING))));
} |
public static String prepareUrl(@NonNull String url) {
url = url.trim();
String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive
if (lowerCaseUrl.startsWith("feed://")) {
Log.d(TAG, "Replacing feed:// with http://");
return prepareUrl(url.substring("feed://".length()));
} else if (lowerCaseUrl.startsWith("pcast://")) {
Log.d(TAG, "Removing pcast://");
return prepareUrl(url.substring("pcast://".length()));
} else if (lowerCaseUrl.startsWith("pcast:")) {
Log.d(TAG, "Removing pcast:");
return prepareUrl(url.substring("pcast:".length()));
} else if (lowerCaseUrl.startsWith("itpc")) {
Log.d(TAG, "Replacing itpc:// with http://");
return prepareUrl(url.substring("itpc://".length()));
} else if (lowerCaseUrl.startsWith(AP_SUBSCRIBE)) {
Log.d(TAG, "Removing antennapod-subscribe://");
return prepareUrl(url.substring(AP_SUBSCRIBE.length()));
} else if (lowerCaseUrl.contains(AP_SUBSCRIBE_DEEPLINK)) {
Log.d(TAG, "Removing " + AP_SUBSCRIBE_DEEPLINK);
String query = Uri.parse(url).getQueryParameter("url");
try {
return prepareUrl(URLDecoder.decode(query, "UTF-8"));
} catch (UnsupportedEncodingException e) {
return prepareUrl(query);
}
} else if (!(lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://"))) {
Log.d(TAG, "Adding http:// at the beginning of the URL");
return "http://" + url;
} else {
return url;
}
} | @Test
public void testWhiteSpaceShouldAppend() {
final String in = "\n example.com \t";
final String out = UrlChecker.prepareUrl(in);
assertEquals("http://example.com", out);
} |
@ScalarOperator(LESS_THAN)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThan(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right)
{
return left < right;
} | @Test
public void testLessThan()
{
assertFunction("TINYINT'37' < TINYINT'37'", BOOLEAN, false);
assertFunction("TINYINT'37' < TINYINT'17'", BOOLEAN, false);
assertFunction("TINYINT'17' < TINYINT'37'", BOOLEAN, true);
assertFunction("TINYINT'17' < TINYINT'17'", BOOLEAN, false);
} |
@Override
public Schema getSchema(SchemaPath schemaPath) throws IOException {
GetSchemaRequest request = GetSchemaRequest.newBuilder().setName(schemaPath.getPath()).build();
return fromPubsubSchema(schemaServiceStub().getSchema(request));
} | @Test
public void getProtoSchema() throws IOException {
String schemaDefinition =
"syntax = \"proto3\"; message ProtocolBuffer { string string_field = 1; int32 int_field = 2; }";
initializeClient(null, null);
final Schema schema =
com.google.pubsub.v1.Schema.newBuilder()
.setName(SCHEMA.getPath())
.setType(Schema.Type.PROTOCOL_BUFFER)
.setDefinition(schemaDefinition)
.build();
SchemaServiceImplBase schemaImplBase =
new SchemaServiceImplBase() {
@Override
public void getSchema(GetSchemaRequest request, StreamObserver<Schema> responseObserver) {
if (request.getName().equals(SCHEMA.getPath())) {
responseObserver.onNext(schema);
responseObserver.onCompleted();
}
}
};
Server server =
InProcessServerBuilder.forName(channelName).addService(schemaImplBase).build().start();
try {
assertThrows(
"Pub/Sub Schema type PROTOCOL_BUFFER is not supported at this time",
IllegalArgumentException.class,
() -> client.getSchema(SCHEMA));
} finally {
server.shutdownNow();
}
} |
@Override
public void writeClass() throws IOException {
ClassName EVM_ANNOTATION = ClassName.get("org.web3j", "EVMTest");
AnnotationSpec.Builder annotationSpec = AnnotationSpec.builder(EVM_ANNOTATION);
if (JavaVersion.getJavaVersionAsDouble() < 11) {
ClassName GethContainer = ClassName.get("org.web3j", "NodeType");
annotationSpec.addMember("value", "type = $T.GETH", GethContainer);
}
TypeSpec testClass =
TypeSpec.classBuilder(theContract.getSimpleName() + "Test")
.addMethods(MethodFilter.generateMethodSpecsForEachTest(theContract))
.addAnnotation((annotationSpec).build())
.addField(
theContract,
toCamelCase(theContract),
Modifier.PRIVATE,
Modifier.STATIC)
.build();
JavaFile javaFile = JavaFile.builder(packageName, testClass).build();
javaFile.writeTo(new File(writePath));
} | @Test
public void testThatExceptionIsThrownWhenAClassIsNotWritten() {
assertThrows(
NullPointerException.class,
() -> new JavaClassGenerator(null, "org.com", temp.toString()).writeClass());
} |
@Override
public long getStateSize() {
return jobManagerOwnedSnapshot != null ? jobManagerOwnedSnapshot.getStateSize() : 0L;
} | @Test
void getStateSize() {
long size = 42L;
SnapshotResult<StateObject> result =
SnapshotResult.withLocalState(
new DummyStateObject(size), new DummyStateObject(size));
assertThat(result.getStateSize()).isEqualTo(size);
} |
@Nonnull
public static String getSortName(int sort) {
return switch (sort) {
case Type.VOID -> "void";
case Type.BOOLEAN -> "boolean";
case Type.CHAR -> "char";
case Type.BYTE -> "byte";
case Type.SHORT -> "short";
case Type.INT -> "int";
case Type.FLOAT -> "float";
case Type.LONG -> "long";
case Type.DOUBLE -> "double";
case Type.ARRAY -> "array";
case Type.OBJECT -> "object";
case Type.METHOD -> "method";
case -1 -> "<undefined>";
default -> "<unknown>";
};
} | @Test
void testGetSortName() {
assertEquals("void", Types.getSortName(Type.VOID));
assertEquals("boolean", Types.getSortName(Type.BOOLEAN));
assertEquals("char", Types.getSortName(Type.CHAR));
assertEquals("byte", Types.getSortName(Type.BYTE));
assertEquals("short", Types.getSortName(Type.SHORT));
assertEquals("int", Types.getSortName(Type.INT));
assertEquals("float", Types.getSortName(Type.FLOAT));
assertEquals("long", Types.getSortName(Type.LONG));
assertEquals("double", Types.getSortName(Type.DOUBLE));
assertEquals("array", Types.getSortName(Type.ARRAY));
assertEquals("object", Types.getSortName(Type.OBJECT));
assertEquals("method", Types.getSortName(Type.METHOD));
} |
public Set<Integer> voterIds() {
return voters.keySet();
} | @Test
void testVoterIds() {
VoterSet voterSet = VoterSet.fromMap(voterMap(IntStream.of(1, 2, 3), true));
assertEquals(new HashSet<>(Arrays.asList(1, 2, 3)), voterSet.voterIds());
} |
@Override
public Set<ConfigOption<?>> requiredOptions() {
Set<ConfigOption<?>> options = new HashSet<>();
options.add(HOSTNAME);
options.add(USERNAME);
options.add(PASSWORD);
options.add(DATABASE_NAME);
options.add(SCHEMA_NAME);
options.add(TABLE_NAME);
options.add(SLOT_NAME);
return options;
} | @Test
public void testValidation() {
// validate illegal port
try {
Map<String, String> properties = getAllOptions();
properties.put("port", "123b");
createTableSource(properties);
fail("exception expected");
} catch (Throwable t) {
assertTrue(
ExceptionUtils.findThrowableWithMessage(
t, "Could not parse value '123b' for key 'port'.")
.isPresent());
}
// validate missing required
Factory factory = new PostgreSQLTableFactory();
for (ConfigOption<?> requiredOption : factory.requiredOptions()) {
Map<String, String> properties = getAllOptions();
properties.remove(requiredOption.key());
try {
createTableSource(SCHEMA, properties);
fail("exception expected");
} catch (Throwable t) {
assertTrue(
ExceptionUtils.findThrowableWithMessage(
t,
"Missing required options are:\n\n" + requiredOption.key())
.isPresent());
}
}
// validate unsupported option
try {
Map<String, String> properties = getAllOptions();
properties.put("unknown", "abc");
createTableSource(properties);
fail("exception expected");
} catch (Throwable t) {
assertTrue(
ExceptionUtils.findThrowableWithMessage(t, "Unsupported options:\n\nunknown")
.isPresent());
}
} |
@Override
public CompletableFuture<Void> deleteSubscriptionGroup(String address, DeleteSubscriptionGroupRequestHeader requestHeader,
long timeoutMillis) {
CompletableFuture<Void> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_SUBSCRIPTIONGROUP, requestHeader);
remotingClient.invoke(address, request, timeoutMillis).thenAccept(response -> {
if (response.getCode() == ResponseCode.SUCCESS) {
future.complete(null);
} else {
log.warn("deleteSubscriptionGroup getResponseCommand failed, {} {}, header={}", response.getCode(), response.getRemark(), requestHeader);
future.completeExceptionally(new MQClientException(response.getCode(), response.getRemark()));
}
});
return future;
} | @Test
public void assertDeleteSubscriptionGroupWithError() {
setResponseError();
DeleteSubscriptionGroupRequestHeader requestHeader = mock(DeleteSubscriptionGroupRequestHeader.class);
CompletableFuture<Void> actual = mqClientAdminImpl.deleteSubscriptionGroup(defaultBrokerAddr, requestHeader, defaultTimeout);
Throwable thrown = assertThrows(ExecutionException.class, actual::get);
assertTrue(thrown.getCause() instanceof MQClientException);
MQClientException mqException = (MQClientException) thrown.getCause();
assertEquals(ResponseCode.SYSTEM_ERROR, mqException.getResponseCode());
assertTrue(mqException.getMessage().contains("CODE: 1 DESC: null"));
} |
public boolean decode(final String in) {
String[] strs = in.split(SEPARATOR);
if (strs.length >= 5) {
this.topicName = strs[0];
this.readQueueNums = Integer.parseInt(strs[1]);
this.writeQueueNums = Integer.parseInt(strs[2]);
this.perm = Integer.parseInt(strs[3]);
this.topicFilterType = TopicFilterType.valueOf(strs[4]);
if (strs.length >= 6) {
try {
this.attributes = JSON.parseObject(strs[5], ATTRIBUTES_TYPE_REFERENCE.getType());
} catch (Exception e) {
// ignore exception when parse failed, cause map's key/value can have ' ' char.
}
}
return true;
}
return false;
} | @Test
public void testDecode() {
String encode = "topic 8 8 6 SINGLE_TAG {\"message.type\":\"FIFO\"}";
TopicConfig decodeTopicConfig = new TopicConfig();
decodeTopicConfig.decode(encode);
TopicConfig topicConfig = new TopicConfig();
topicConfig.setTopicName(topicName);
topicConfig.setReadQueueNums(queueNums);
topicConfig.setWriteQueueNums(queueNums);
topicConfig.setPerm(perm);
topicConfig.setTopicFilterType(topicFilterType);
topicConfig.setTopicMessageType(TopicMessageType.FIFO);
assertThat(decodeTopicConfig).isEqualTo(topicConfig);
} |
@Override
public void preflight(Path file) throws BackgroundException {
assumeRole(file, READPERMISSION);
} | @Test
public void testPreflightFileAccessDeniedCustomProps() throws Exception {
final Path file = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
file.setAttributes(file.attributes().withAcl(new Acl(new Acl.CanonicalUser(), WRITEPERMISSION)));
assertThrows(AccessDeniedException.class, () -> new CteraReadFeature(session).preflight(file));
} |
public JetSqlRow project(Object key, Object value) {
return project(key, null, value, null);
} | @Test
public void test_project_onlyDataKeyAndValueIsProvided() {
InternalSerializationService serializationService = new DefaultSerializationServiceBuilder().build();
KvRowProjector projector = new KvRowProjector(
new QueryPath[]{QueryPath.KEY_PATH, QueryPath.VALUE_PATH},
new QueryDataType[]{INT, INT},
new GenericQueryTarget(serializationService, null, true),
new GenericQueryTarget(serializationService, null, false),
null,
asList(
MultiplyFunction.create(ColumnExpression.create(0, INT), ConstantExpression.create(2, INT), INT),
DivideFunction.create(ColumnExpression.create(1, INT), ConstantExpression.create(2, INT), INT)
),
SqlTestSupport.createExpressionEvalContext()
);
JetSqlRow row = projector.project(serializationService.toData(1), serializationService.toData(8));
assertThat(row).isEqualTo(jetRow(2, 4));
} |
@Override
public Map<String, String> getAllVariables() {
return internalGetAllVariables(0, Collections.emptySet());
} | @Test
void testGetAllVariablesWithExclusionsForReporters() {
MetricRegistry registry = TestingMetricRegistry.builder().setNumberReporters(2).build();
AbstractMetricGroup<?> group =
new GenericMetricGroup(registry, null, "test") {
@Override
protected void putVariables(Map<String, String> variables) {
variables.put("k1", "v1");
variables.put("k2", "v2");
}
};
group.getAllVariables(-1, Collections.emptySet());
assertThat(group.getAllVariables(0, Collections.singleton("k1"))).doesNotContainKey("k1");
assertThat(group.getAllVariables(0, Collections.singleton("k1"))).containsKey("k2");
assertThat(group.getAllVariables(1, Collections.singleton("k2"))).containsKey("k1");
assertThat(group.getAllVariables(1, Collections.singleton("k2"))).doesNotContainKey("k2");
} |
@Override
public boolean exists(final LinkOption... options) {
NSURL resolved = null;
try {
resolved = this.lock(false);
if(null == resolved) {
return super.exists(options);
}
return Files.exists(Paths.get(resolved.path()));
}
catch(AccessDeniedException e) {
return super.exists(options);
}
finally {
this.release(resolved);
}
} | @Test
public void testNoCaseSensitive() throws Exception {
final String name = UUID.randomUUID().toString();
FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), name);
new DefaultLocalTouchFeature().touch(l);
assertTrue(l.exists());
assertTrue(new FinderLocal(System.getProperty("java.io.tmpdir"), StringUtils.upperCase(name)).exists());
assertTrue(new FinderLocal(System.getProperty("java.io.tmpdir"), StringUtils.lowerCase(name)).exists());
l.delete();
} |
@VisibleForTesting
static AbsoluteUnixPath getAppRootChecked(
RawConfiguration rawConfiguration, ProjectProperties projectProperties)
throws InvalidAppRootException {
String appRoot = rawConfiguration.getAppRoot();
if (appRoot.isEmpty()) {
appRoot =
projectProperties.isWarProject()
? DEFAULT_JETTY_APP_ROOT
: JavaContainerBuilder.DEFAULT_APP_ROOT;
}
try {
return AbsoluteUnixPath.get(appRoot);
} catch (IllegalArgumentException ex) {
throw new InvalidAppRootException(appRoot, appRoot, ex);
}
} | @Test
public void testGetAppRootChecked_defaultNonWarProject() throws InvalidAppRootException {
when(rawConfiguration.getAppRoot()).thenReturn("");
when(projectProperties.isWarProject()).thenReturn(false);
assertThat(PluginConfigurationProcessor.getAppRootChecked(rawConfiguration, projectProperties))
.isEqualTo(AbsoluteUnixPath.get("/app"));
} |
@Override
public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getProcedures(getActualCatalog(catalog), getActualSchema(schemaPattern), procedureNamePattern));
} | @Test
void assertGetProcedures() throws SQLException {
when(databaseMetaData.getProcedures("test", null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getProcedures("test", null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
String highwayValue = way.getTag("highway");
if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service")))
return;
int firstIndex = way.getFirstIndex(restrictionKeys);
String firstValue = firstIndex < 0 ? "" : way.getTag(restrictionKeys.get(firstIndex), "");
if (restrictedValues.contains(firstValue) && !hasTemporalRestriction(way, firstIndex, restrictionKeys))
return;
if (way.hasTag("gh:barrier_edge") && way.hasTag("node_tags")) {
List<Map<String, Object>> nodeTags = way.getTag("node_tags", null);
Map<String, Object> firstNodeTags = nodeTags.get(0);
// a barrier edge has the restriction in both nodes and the tags are the same -> get(0)
firstValue = getFirstPriorityNodeTag(firstNodeTags, restrictionKeys);
String barrierValue = firstNodeTags.containsKey("barrier") ? (String) firstNodeTags.get("barrier") : "";
if (restrictedValues.contains(firstValue) || barriers.contains(barrierValue)
|| "yes".equals(firstNodeTags.get("locked")) && !INTENDED.contains(firstValue))
return;
}
if (FerrySpeedCalculator.isFerry(way)) {
boolean isCar = restrictionKeys.contains("motorcar");
if (INTENDED.contains(firstValue)
// implied default is allowed only if foot and bicycle is not specified:
|| isCar && firstValue.isEmpty() && !way.hasTag("foot") && !way.hasTag("bicycle")
// if hgv is allowed then smaller trucks and cars are allowed too even if not specified
|| isCar && way.hasTag("hgv", "yes")) {
accessEnc.setBool(false, edgeId, edgeIntAccess, true);
accessEnc.setBool(true, edgeId, edgeIntAccess, true);
}
} else {
boolean isRoundabout = roundaboutEnc.getBool(false, edgeId, edgeIntAccess);
boolean ignoreOneway = "no".equals(way.getFirstValue(ignoreOnewayKeys));
boolean isBwd = isBackwardOneway(way);
if (!ignoreOneway && (isBwd || isRoundabout || isForwardOneway(way))) {
accessEnc.setBool(isBwd, edgeId, edgeIntAccess, true);
} else {
accessEnc.setBool(false, edgeId, edgeIntAccess, true);
accessEnc.setBool(true, edgeId, edgeIntAccess, true);
}
}
} | @Test
public void testBusNo() {
EdgeIntAccess access = new ArrayEdgeIntAccess(1);
ReaderWay way = new ReaderWay(0);
way.setTag("highway", "tertiary");
int edgeId = 0;
parser.handleWayTags(edgeId, access, way, null);
assertTrue(busAccessEnc.getBool(false, edgeId, access));
access = new ArrayEdgeIntAccess(1);
way.setTag("bus", "no");
parser.handleWayTags(edgeId, access, way, null);
assertFalse(busAccessEnc.getBool(false, edgeId, access));
} |
public static FieldScope allowingFields(int firstFieldNumber, int... rest) {
return FieldScopeImpl.createAllowingFields(asList(firstFieldNumber, rest));
} | @Test
public void testIgnoringTopLevelField_fieldScopes_allowingFields() {
expectThat(ignoringFieldDiffMessage)
.withPartialScope(FieldScopes.allowingFields(goodFieldNumber))
.isEqualTo(ignoringFieldMessage);
expectThat(ignoringFieldDiffMessage)
.ignoringFieldScope(FieldScopes.allowingFields(goodFieldNumber))
.isNotEqualTo(ignoringFieldMessage);
expectThat(ignoringFieldDiffMessage)
.withPartialScope(FieldScopes.allowingFields(badFieldNumber))
.isNotEqualTo(ignoringFieldMessage);
expectThat(ignoringFieldDiffMessage)
.ignoringFieldScope(FieldScopes.allowingFields(badFieldNumber))
.isEqualTo(ignoringFieldMessage);
} |
@Override
public void removeConfigInfoTag(final String dataId, final String group, final String tenant, final String tag,
final String srcIp, final String srcUser) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
String tagTmp = StringUtils.isBlank(tag) ? StringUtils.EMPTY : tag;
ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_TAG);
final String sql = configInfoTagMapper.delete(Arrays.asList("data_id", "group_id", "tenant_id", "tag_id"));
final Object[] args = new Object[] {dataId, group, tenantTmp, tagTmp};
EmbeddedStorageContextUtils.onDeleteConfigTagInfo(tenantTmp, group, dataId, tagTmp, srcIp);
EmbeddedStorageContextHolder.addSqlContext(sql, args);
try {
databaseOperate.update(EmbeddedStorageContextHolder.getCurrentSqlContext());
} finally {
EmbeddedStorageContextHolder.cleanAllContext();
}
} | @Test
void testRemoveConfigInfoTag() {
String dataId = "dataId1112222";
String group = "group22";
String tenant = "tenant2";
String tag = "tag123345";
String srcIp = "ip345678";
String srcUser = "user1234567";
embeddedConfigInfoTagPersistService.removeConfigInfoTag(dataId, group, tenant, tag, srcIp, srcUser);
//verify delete sql invoked.
embeddedStorageContextHolderMockedStatic.verify(
() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag)), times(1));
} |
@Nonnull
WanAcknowledgeType getWanAcknowledgeType(int id) {
switch (id) {
case 0:
return WanAcknowledgeType.ACK_ON_RECEIPT;
case 1:
return WanAcknowledgeType.ACK_ON_OPERATION_COMPLETE;
default:
return WanBatchPublisherConfig.DEFAULT_ACKNOWLEDGE_TYPE;
}
} | @Test
public void testGetWanAcknowledgeType() {
assertEquals(WanAcknowledgeType.ACK_ON_RECEIPT, transformer.getWanAcknowledgeType(0));
assertEquals(WanAcknowledgeType.ACK_ON_OPERATION_COMPLETE, transformer.getWanAcknowledgeType(1));
assertEquals(WanBatchPublisherConfig.DEFAULT_ACKNOWLEDGE_TYPE, transformer.getWanAcknowledgeType(2));
} |
public static Optional<NoticeContents> parseNoticeFile(Path noticeFile) throws IOException {
// 1st line contains module name
final List<String> noticeContents = Files.readAllLines(noticeFile);
return parseNoticeFile(noticeContents);
} | @Test
void testParseNoticeFileMalformedDependencyIgnored() {
final String module = "some-module";
final Dependency dependency = Dependency.create("groupId", "artifactId", "version", null);
final List<String> noticeContents = Arrays.asList(module, "- " + dependency, "- a:b");
assertThat(NoticeParser.parseNoticeFile(noticeContents))
.hasValueSatisfying(
contents -> {
assertThat(contents.getNoticeModuleName()).isEqualTo(module);
assertThat(contents.getDeclaredDependencies())
.containsExactlyInAnyOrder(dependency);
});
} |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetAnalyzerName() {
assertEquals("Nugetconf Analyzer", instance.getName());
} |
public void set(Collection<ActiveRule> activeRules) {
requireNonNull(activeRules, "Active rules cannot be null");
checkState(activeRulesByKey == null, "Active rules have already been initialized");
Map<RuleKey, ActiveRule> temp = new HashMap<>();
for (ActiveRule activeRule : activeRules) {
ActiveRule previousValue = temp.put(activeRule.getRuleKey(), activeRule);
if (previousValue != null) {
throw new IllegalArgumentException("Active rule must not be declared multiple times: " + activeRule.getRuleKey());
}
}
activeRulesByKey = ImmutableMap.copyOf(temp);
} | @Test
public void can_not_set_duplicated_rules() {
assertThatThrownBy(() -> {
underTest.set(asList(
new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY),
new ActiveRule(RULE_KEY, Severity.MAJOR, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY)));
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Active rule must not be declared multiple times: java:S001");
} |
@Override
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return join(otherStream, toValueJoinerWithKey(joiner), windows);
} | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullValueJoinerOnJoinWithStreamJoined() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(
testStream,
(ValueJoiner<? super String, ? super String, ?>) null,
JoinWindows.of(ofMillis(10)),
StreamJoined.as("name")));
assertThat(exception.getMessage(), equalTo("joiner can't be null"));
} |
BrokerInterceptorWithClassLoader load(BrokerInterceptorMetadata metadata, String narExtractionDirectory)
throws IOException {
final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
NarClassLoader ncl = NarClassLoaderBuilder.builder()
.narFile(narFile)
.parentClassLoader(BrokerInterceptorUtils.class.getClassLoader())
.extractionDirectory(narExtractionDirectory)
.build();
BrokerInterceptorDefinition def = getBrokerInterceptorDefinition(ncl);
if (StringUtils.isBlank(def.getInterceptorClass())) {
throw new IOException("Broker interceptors `" + def.getName() + "` does NOT provide a broker"
+ " interceptors implementation");
}
try {
Class interceptorClass = ncl.loadClass(def.getInterceptorClass());
Object interceptor = interceptorClass.getDeclaredConstructor().newInstance();
if (!(interceptor instanceof BrokerInterceptor)) {
throw new IOException("Class " + def.getInterceptorClass()
+ " does not implement broker interceptor interface");
}
BrokerInterceptor pi = (BrokerInterceptor) interceptor;
return new BrokerInterceptorWithClassLoader(pi, ncl);
} catch (Throwable t) {
rethrowIOException(t);
return null;
}
} | @Test
public void testLoadBrokerEventListener() throws Exception {
BrokerInterceptorDefinition def = new BrokerInterceptorDefinition();
def.setInterceptorClass(MockBrokerInterceptor.class.getName());
def.setDescription("test-broker-listener");
String archivePath = "/path/to/broker/listener/nar";
BrokerInterceptorMetadata metadata = new BrokerInterceptorMetadata();
metadata.setDefinition(def);
metadata.setArchivePath(Paths.get(archivePath));
NarClassLoader mockLoader = mock(NarClassLoader.class);
when(mockLoader.getServiceDefinition(eq(BrokerInterceptorUtils.BROKER_INTERCEPTOR_DEFINITION_FILE)))
.thenReturn(ObjectMapperFactory.getYamlMapper().writer().writeValueAsString(def));
Class listenerClass = MockBrokerInterceptor.class;
when(mockLoader.loadClass(eq(MockBrokerInterceptor.class.getName())))
.thenReturn(listenerClass);
final NarClassLoaderBuilder mockedBuilder = mock(NarClassLoaderBuilder.class, RETURNS_SELF);
when(mockedBuilder.build()).thenReturn(mockLoader);
try (MockedStatic<NarClassLoaderBuilder> builder = Mockito.mockStatic(NarClassLoaderBuilder.class)) {
builder.when(() -> NarClassLoaderBuilder.builder()).thenReturn(mockedBuilder);
BrokerInterceptorWithClassLoader returnedPhWithCL = BrokerInterceptorUtils.load(metadata, "");
BrokerInterceptor returnedPh = returnedPhWithCL.getInterceptor();
assertSame(mockLoader, returnedPhWithCL.getNarClassLoader());
assertTrue(returnedPh instanceof MockBrokerInterceptor);
}
} |
public DefaultThreadPoolPluginManager setPluginComparator(@NonNull Comparator<Object> comparator) {
mainLock.runWithWriteLock(() -> {
// the specified comparator has been set
if (Objects.equals(this.pluginComparator, comparator)) {
return;
}
this.pluginComparator = comparator;
forQuickIndexes(QuickIndex::sort);
});
return this;
} | @Test
public void testSetPluginComparator() {
Assert.assertFalse(manager.isEnableSort());
manager.register(new TestExecuteAwarePlugin());
manager.register(new TestTaskAwarePlugin());
manager.setPluginComparator(AnnotationAwareOrderComparator.INSTANCE);
manager.register(new TestRejectedAwarePlugin());
manager.register(new TestShutdownAwarePlugin());
Assert.assertTrue(manager.isEnableSort());
Iterator<ThreadPoolPlugin> iterator = manager.getAllPlugins().iterator();
Assert.assertEquals(TestTaskAwarePlugin.class, iterator.next().getClass());
Assert.assertEquals(TestRejectedAwarePlugin.class, iterator.next().getClass());
Assert.assertEquals(TestExecuteAwarePlugin.class, iterator.next().getClass());
Assert.assertEquals(TestShutdownAwarePlugin.class, iterator.next().getClass());
} |
public void commitPartitions() throws Exception {
commitPartitions((subtaskIndex, attemptNumber) -> true);
} | @Test
void testNotPartition() throws Exception {
FileSystemCommitter committer =
new FileSystemCommitter(
fileSystemFactory,
metaStoreFactory,
true,
new Path(path.toString()),
0,
false,
identifier,
new LinkedHashMap<String, String>(),
policies);
createFile(path, "task-1-attempt-0/", "f1", "f2");
createFile(path, "task-2-attempt-0/", "f3");
committer.commitPartitions();
assertThat(new File(outputPath.toFile(), "f1")).exists();
assertThat(new File(outputPath.toFile(), "f2")).exists();
assertThat(new File(outputPath.toFile(), "f3")).exists();
assertThat(new File(outputPath.toFile(), SUCCESS_FILE_NAME)).exists();
createFile(path, "task-2-attempt-0/", "f4");
committer.commitPartitions();
assertThat(new File(outputPath.toFile(), "f4")).exists();
assertThat(new File(outputPath.toFile(), SUCCESS_FILE_NAME)).exists();
committer =
new FileSystemCommitter(
fileSystemFactory,
metaStoreFactory,
false,
new Path(path.toString()),
0,
false,
identifier,
new LinkedHashMap<String, String>(),
policies);
createFile(path, "task-2-attempt-0/", "f5");
committer.commitPartitions();
assertThat(new File(outputPath.toFile(), "f4")).exists();
assertThat(new File(outputPath.toFile(), "f5")).exists();
assertThat(new File(outputPath.toFile(), SUCCESS_FILE_NAME)).exists();
} |
public static List<String> computeNameParts(String loggerName) {
List<String> partList = new ArrayList<String>();
int fromIndex = 0;
while (true) {
int index = getSeparatorIndexOf(loggerName, fromIndex);
if (index == -1) {
partList.add(loggerName.substring(fromIndex));
break;
}
partList.add(loggerName.substring(fromIndex, index));
fromIndex = index + 1;
}
return partList;
} | @Test
public void emptyStringShouldReturnAListContainingOneEmptyString() {
List<String> witnessList = new ArrayList<String>();
witnessList.add("");
List<String> partList = LoggerNameUtil.computeNameParts("");
assertEquals(witnessList, partList);
} |
@Override
public <U> ParSeqBasedCompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn)
{
return nextStageByComposingTask(_task.transform("handle", prevTaskResult -> {
try {
return Success.of(fn.apply(prevTaskResult.isFailed() ? null : prevTaskResult.get(), prevTaskResult.getError()));
} catch (Throwable throwable) {
return Failure.of(throwable);
}
}));
} | @Test
public void testHandle() throws Exception
{
CompletionStage<String> completionStage = createTestStage(TESTVALUE1);
BiFunction<String, Throwable, Integer> consumer = mock(BiFunction.class);
finish(completionStage.handle(consumer));
verify(consumer).apply(TESTVALUE1, null);
} |
@Override
public AsynchronousByteChannel getAsynchronousChannel() {
return new RedissonAsynchronousByteChannel();
} | @Test
public void testAsyncReadWrite() throws ExecutionException, InterruptedException {
RBinaryStream stream = redisson.getBinaryStream("test");
AsynchronousByteChannel channel = stream.getAsynchronousChannel();
ByteBuffer bb = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7});
channel.write(bb).get();
AsynchronousByteChannel channel2 = stream.getAsynchronousChannel();
ByteBuffer b = ByteBuffer.allocate(7);
channel2.read(b).get();
b.flip();
assertThat(b).isEqualByComparingTo(bb);
} |
public static List<Criterion> parse(String filter) {
return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false)
.map(FilterParser::parseCriterion)
.toList();
} | @Test
public void parse_filter_having_only_key_ignores_white_spaces() {
List<Criterion> criterion = FilterParser.parse(" isFavorite ");
assertThat(criterion)
.extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue)
.containsOnly(
tuple("isFavorite", null, null));
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
handleFetchSuccess(fetchTarget, data, clientResponse);
}
},
(fetchTarget, data, error) -> {
synchronized (Fetcher.this) {
handleFetchFailure(fetchTarget, data, error);
}
});
return fetchRequests.size();
} | @Test
public void testCorruptMessageError() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
assertFalse(fetcher.hasCompletedFetches());
// Prepare a response with the CORRUPT_MESSAGE error.
client.prepareResponse(fullFetchResponse(
tidp0,
buildRecords(1L, 1, 1),
Errors.CORRUPT_MESSAGE,
100L, 0));
consumerClient.poll(time.timer(0));
assertTrue(fetcher.hasCompletedFetches());
// Trigger the exception.
assertThrows(KafkaException.class, this::fetchRecords);
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i = 0; i < ntrees; i++) {
base += shrinkage * trees[i].predict(xj);
prediction[i][j] = base;
}
}
return prediction;
} | @Test
public void testAileronsHuber() {
test(Loss.huber(0.9), "ailerons", Ailerons.formula, Ailerons.data, 0.0002);
} |
@Override
public void execute(final ConnectionSession connectionSession) {
queryResultMetaData = createQueryResultMetaData();
mergedResult = new TransparentMergedResult(getQueryResult(showCreateDatabaseStatement.getDatabaseName()));
} | @Test
void assertExecute() throws SQLException {
MySQLShowCreateDatabaseStatement statement = new MySQLShowCreateDatabaseStatement();
statement.setDatabaseName("db_0");
ShowCreateDatabaseExecutor executor = new ShowCreateDatabaseExecutor(statement);
ContextManager contextManager = mockContextManager();
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
when(ProxyContext.getInstance().databaseExists("db_0")).thenReturn(true);
executor.execute(mock(ConnectionSession.class));
assertThat(executor.getQueryResultMetaData().getColumnCount(), is(2));
int count = 0;
while (executor.getMergedResult().next()) {
assertThat(executor.getMergedResult().getValue(1, Object.class), is(String.format(DATABASE_PATTERN, count)));
count++;
}
} |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STATE:
handleLiteralState(c, tokenList, buf);
break;
case FORMAT_MODIFIER_STATE:
handleFormatModifierState(c, tokenList, buf);
break;
case OPTION_STATE:
processOption(c, tokenList, buf);
break;
case KEYWORD_STATE:
handleKeywordState(c, tokenList, buf);
break;
case RIGHT_PARENTHESIS_STATE:
handleRightParenthesisState(c, tokenList, buf);
break;
default:
}
}
// EOS
switch (state) {
case LITERAL_STATE:
addValuedToken(Token.LITERAL, buf, tokenList);
break;
case KEYWORD_STATE:
tokenList.add(new Token(Token.SIMPLE_KEYWORD, buf.toString()));
break;
case RIGHT_PARENTHESIS_STATE:
tokenList.add(Token.RIGHT_PARENTHESIS_TOKEN);
break;
case FORMAT_MODIFIER_STATE:
case OPTION_STATE:
throw new ScanException("Unexpected end of pattern string");
}
return tokenList;
} | @Test
public void testSingleLiteral() throws ScanException {
List<Token> tl = new TokenStream("hello").tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(new Token(Token.LITERAL, "hello"));
assertEquals(witness, tl);
} |
@Override
public ImmutableList<String> computeEntrypoint(List<String> jvmFlags) {
ImmutableList.Builder<String> entrypoint = ImmutableList.builder();
entrypoint.add("java");
entrypoint.addAll(jvmFlags);
entrypoint.add("-cp");
entrypoint.add(JarLayers.APP_ROOT.toString());
entrypoint.add("org.springframework.boot.loader.JarLauncher");
return entrypoint.build();
} | @Test
public void testComputeEntrypoint() {
SpringBootExplodedProcessor bootProcessor =
new SpringBootExplodedProcessor(
Paths.get("ignored"), Paths.get("ignored"), JAR_JAVA_VERSION);
ImmutableList<String> actualEntrypoint = bootProcessor.computeEntrypoint(new ArrayList<>());
assertThat(actualEntrypoint)
.isEqualTo(
ImmutableList.of("java", "-cp", "/app", "org.springframework.boot.loader.JarLauncher"));
} |
@Override
public void setMetadata(final Path file, final TransferStatus status) throws BackgroundException {
try {
if(containerService.isContainer(file)) {
for(Map.Entry<String, String> entry : file.attributes().getMetadata().entrySet()) {
// Choose metadata values to remove
if(!status.getMetadata().containsKey(entry.getKey())) {
log.debug(String.format("Remove metadata with key %s", entry.getKey()));
status.getMetadata().put(entry.getKey(), StringUtils.EMPTY);
}
}
if(log.isDebugEnabled()) {
log.debug(String.format("Write metadata %s for file %s", status, file));
}
session.getClient().updateContainerMetadata(regionService.lookup(file),
containerService.getContainer(file).getName(), status.getMetadata());
}
else {
if(log.isDebugEnabled()) {
log.debug(String.format("Write metadata %s for file %s", status, file));
}
session.getClient().updateObjectMetadata(regionService.lookup(file),
containerService.getContainer(file).getName(), containerService.getKey(file), status.getMetadata());
}
}
catch(GenericException e) {
throw new SwiftExceptionMappingService().map("Failure to write attributes of {0}", e, file);
}
catch(IOException e) {
throw new DefaultIOExceptionMappingService().map("Failure to write attributes of {0}", e, file);
}
} | @Test
public void testSetMetadata() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new SwiftTouchFeature(session, new SwiftRegionService(session)).touch(test, new TransferStatus().withMime("text/plain"));
final String v = UUID.randomUUID().toString();
new SwiftMetadataFeature(session).setMetadata(test, Collections.<String, String>singletonMap("Test", v));
final Map<String, String> metadata = new SwiftMetadataFeature(session).getMetadata(test);
assertFalse(metadata.isEmpty());
assertTrue(metadata.containsKey("X-Object-Meta-Test"));
assertEquals(v, metadata.get("X-Object-Meta-Test"));
assertEquals("text/plain", metadata.get("Content-Type"));
new SwiftDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
String getLockName(String namespace, String name) {
return "lock::" + namespace + "::" + kind() + "::" + name;
} | @Test
/*
* Verifies that lock is released by call to `releaseLockAndTimer`.
* The call is made through a chain of futures ending with `eventually` after a failed execution via an unhandled exception in the `Callable`,
* followed by an unhandled exception occurring in the `onFailure` handler.
*/
void testWithLockFailHandlerUnhandledExceptionReleasesLock(VertxTestContext context) {
var resourceOperator = new DefaultWatchableStatusedResourceOperator<>(vertx, null, "TestResource");
@SuppressWarnings({ "unchecked", "rawtypes" })
var target = new DefaultOperator(vertx, "Test", resourceOperator, new MicrometerMetricsProvider(BackendRegistries.getDefaultNow()), null);
Reconciliation reconciliation = new Reconciliation("test", "TestResource", "my-namespace", "my-resource");
String lockName = target.getLockName(reconciliation);
Promise<Void> handlersRegistered = Promise.promise();
Promise<Void> failHandlerCalled = Promise.promise();
@SuppressWarnings("unchecked")
Future<String> result = target.withLockTest(reconciliation,
// TEST SETUP: Do not throw the exception until all handlers registered
() -> handlersRegistered.future().compose(nothing -> {
throw new UnsupportedOperationException(EXPECTED_MESSAGE);
}));
Checkpoint callableFailed = context.checkpoint();
Checkpoint lockObtained = context.checkpoint();
result.onComplete(ar -> {
assertThat(ar.failed(), is(true));
Throwable e = ar.cause();
context.verify(() -> {
assertThat(e.getMessage(), is(EXPECTED_MESSAGE));
callableFailed.flag();
});
try {
throw new RuntimeException(e);
} finally {
// Enables the subsequent lock retrieval to verify it has been unlocked.
failHandlerCalled.complete();
}
});
failHandlerCalled.future()
.compose(nothing ->
vertx.sharedData().getLockWithTimeout(lockName, 10000L))
.onComplete(context.succeeding(lock -> context.verify(() -> {
assertThat(lock, instanceOf(Lock.class));
lock.release();
lockObtained.flag();
})));
handlersRegistered.complete();
} |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testTransientFieldInitialization() throws Exception {
Pojo value = new Pojo("Hello", 42, DATETIME_A);
AvroCoder<Pojo> coder = AvroCoder.of(Pojo.class);
// Serialization of object
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(coder);
// De-serialization of object
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
AvroCoder<Pojo> copied = (AvroCoder<Pojo>) in.readObject();
CoderProperties.coderDecodeEncodeEqual(copied, value);
} |
public String build( final String cellValue ) {
switch ( type ) {
case FORALL:
return buildForAll( cellValue );
case INDEXED:
return buildMulti( cellValue );
default:
return buildSingle( cellValue );
}
} | @Test
public void testMultiPlaceHolder() {
final String snippet = "something.getAnother($1,$2).equals($2, '$2');";
final SnippetBuilder snip = new SnippetBuilder(snippet);
final String result = snip.build("x, y");
assertThat(result).isEqualTo("something.getAnother(x,y).equals(y, 'y');");
} |
@Override
public boolean deletePluginPath(Path pluginPath) {
FileUtils.optimisticDelete(FileUtils.findWithEnding(pluginPath, ".zip", ".ZIP", ".Zip"));
return super.deletePluginPath(pluginPath);
} | @Test
public void testDeletePluginPath() {
PluginRepository repository = new DefaultPluginRepository(pluginsPath1, pluginsPath2);
assertTrue(Files.exists(pluginsPath1.resolve("plugin-1.zip")));
assertTrue(repository.deletePluginPath(pluginsPath1.resolve("plugin-1")));
assertFalse(Files.exists(pluginsPath1.resolve("plugin-1.zip")));
assertTrue(repository.deletePluginPath(pluginsPath2.resolve("plugin-3")));
assertFalse(repository.deletePluginPath(pluginsPath2.resolve("plugin-4")));
List<Path> pluginPaths = repository.getPluginPaths();
assertEquals(1, pluginPaths.size());
assertEquals(pluginsPath2.relativize(pluginPaths.get(0)).toString(), "plugin-2");
} |
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
} | @Test
public void testTime() {
RedisClusterNode master = getFirstMaster();
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
} |
public static Timestamp toTimestamp(BigDecimal bigDecimal) {
final BigDecimal nanos = bigDecimal.remainder(BigDecimal.ONE.scaleByPowerOfTen(9));
final BigDecimal seconds = bigDecimal.subtract(nanos).scaleByPowerOfTen(-9).add(MIN_SECONDS);
return Timestamp.ofTimeSecondsAndNanos(seconds.longValue(), nanos.intValue());
} | @Test
public void testToTimestampConvertNanosToTimestampMin() {
assertEquals(Timestamp.MIN_VALUE, TimestampUtils.toTimestamp(BigDecimal.valueOf(0L)));
} |
public static Wrapper getWrapper(Class<?> c) {
while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic class.
{
c = c.getSuperclass();
}
if (c == Object.class) {
return OBJECT_WRAPPER;
}
return ConcurrentHashMapUtils.computeIfAbsent(WRAPPER_MAP, c, Wrapper::makeWrapper);
} | @Test
void test_makeEmptyClass() throws Exception {
Wrapper.getWrapper(EmptyServiceImpl.class);
} |
@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) {
validateInsertInto(securityContext, metaStore, (InsertInto)statement);
} else if (statement instanceof CreateAsSelect) {
validateCreateAsSelect(securityContext, metaStore, (CreateAsSelect)statement);
} else if (statement instanceof PrintTopic) {
validatePrintTopic(securityContext, (PrintTopic)statement);
} else if (statement instanceof CreateSource) {
validateCreateSource(securityContext, (CreateSource)statement);
}
} | @Test
public void shouldThrowWhenInsertIntoWithOnlyWritePermissionsAllowed() {
// Given:
givenTopicAccessDenied(KAFKA_TOPIC, AclOperation.READ);
final Statement statement = givenStatement(String.format(
"INSERT INTO %s SELECT * FROM %s;", AVRO_STREAM_TOPIC, KAFKA_STREAM_TOPIC)
);
// When:
final Exception e = assertThrows(
KsqlTopicAuthorizationException.class,
() -> authorizationValidator.checkAuthorization(securityContext, metaStore, statement)
);
// Then:
assertThat(e.getMessage(), containsString(String.format(
"Authorization denied to Read on topic(s): [%s]", KAFKA_TOPIC
)));
} |
@Override
public Bytes cacheKey(final Bytes key) {
return cacheKey(key, segmentId(key));
} | @Test
public void cacheKey() {
final long segmentId = TIMESTAMP / SEGMENT_INTERVAL;
final Bytes actualCacheKey = cacheFunction.cacheKey(THE_KEY);
final ByteBuffer buffer = ByteBuffer.wrap(actualCacheKey.get());
assertThat(buffer.getLong(), equalTo(segmentId));
final byte[] actualKey = new byte[buffer.remaining()];
buffer.get(actualKey);
assertThat(Bytes.wrap(actualKey), equalTo(THE_KEY));
} |
public static String getGroupName(final String serviceNameWithGroup) {
if (StringUtils.isBlank(serviceNameWithGroup)) {
return StringUtils.EMPTY;
}
if (!serviceNameWithGroup.contains(Constants.SERVICE_INFO_SPLITER)) {
return Constants.DEFAULT_GROUP;
}
return serviceNameWithGroup.split(Constants.SERVICE_INFO_SPLITER)[0];
} | @Test
void testGetGroupNameWithoutGroup() {
String serviceName = "serviceName";
assertEquals(Constants.DEFAULT_GROUP, NamingUtils.getGroupName(serviceName));
} |
public Map<Integer, ReplicaPlacementInfo> replicasToMoveBetweenDisksByBroker() {
return Collections.unmodifiableMap(_replicasToMoveBetweenDisksByBroker);
} | @Test
public void testIntraBrokerReplicaMovements() {
ExecutionProposal p = new ExecutionProposal(TP, 0, _r0d0, Arrays.asList(_r0d0, _r1d1), Arrays.asList(_r0d1, _r1d1));
Assert.assertEquals(1, p.replicasToMoveBetweenDisksByBroker().size());
} |
public static <C> Collection<Data> objectToDataCollection(Collection<C> collection,
SerializationService serializationService) {
List<Data> dataCollection = new ArrayList<>(collection.size());
objectToDataCollection(collection, dataCollection, serializationService, null);
return dataCollection;
} | @Test
public void testObjectToDataCollection_deserializeBack() {
SerializationService serializationService = new DefaultSerializationServiceBuilder().build();
Collection<Object> list = new ArrayList<>();
list.add(1);
list.add("foo");
Collection<Data> dataCollection = objectToDataCollection(list, serializationService);
Iterator<Data> it1 = dataCollection.iterator();
Iterator<Object> it2 = list.iterator();
while (it1.hasNext() && it2.hasNext()) {
assertEquals(serializationService.toObject(it1.next()), it2.next());
}
} |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromLatestSnapshotWithEmptyTable() throws Exception {
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_LATEST_SNAPSHOT)
.splitSize(1L)
.build();
ContinuousSplitPlannerImpl splitPlanner =
new ContinuousSplitPlannerImpl(TABLE_RESOURCE.tableLoader().clone(), scanContext, null);
ContinuousEnumerationResult emptyTableInitialDiscoveryResult = splitPlanner.planSplits(null);
assertThat(emptyTableInitialDiscoveryResult.splits()).isEmpty();
assertThat(emptyTableInitialDiscoveryResult.fromPosition()).isNull();
assertThat(emptyTableInitialDiscoveryResult.toPosition().isEmpty()).isTrue();
assertThat(emptyTableInitialDiscoveryResult.toPosition().snapshotTimestampMs()).isNull();
ContinuousEnumerationResult emptyTableSecondDiscoveryResult =
splitPlanner.planSplits(emptyTableInitialDiscoveryResult.toPosition());
assertThat(emptyTableSecondDiscoveryResult.splits()).isEmpty();
assertThat(emptyTableSecondDiscoveryResult.fromPosition().isEmpty()).isTrue();
assertThat(emptyTableSecondDiscoveryResult.fromPosition().snapshotTimestampMs()).isNull();
assertThat(emptyTableSecondDiscoveryResult.toPosition().isEmpty()).isTrue();
assertThat(emptyTableSecondDiscoveryResult.toPosition().snapshotTimestampMs()).isNull();
// latest mode should discover both snapshots, as latest position is marked by when job starts
appendTwoSnapshots();
ContinuousEnumerationResult afterTwoSnapshotsAppended =
splitPlanner.planSplits(emptyTableSecondDiscoveryResult.toPosition());
assertThat(afterTwoSnapshotsAppended.splits()).hasSize(2);
// next 3 snapshots
IcebergEnumeratorPosition lastPosition = afterTwoSnapshotsAppended.toPosition();
for (int i = 0; i < 3; ++i) {
lastPosition = verifyOneCycle(splitPlanner, lastPosition).lastPosition;
}
} |
@Override
public Long createNotice(NoticeSaveReqVO createReqVO) {
NoticeDO notice = BeanUtils.toBean(createReqVO, NoticeDO.class);
noticeMapper.insert(notice);
return notice.getId();
} | @Test
public void testCreateNotice_success() {
// 准备参数
NoticeSaveReqVO reqVO = randomPojo(NoticeSaveReqVO.class)
.setId(null); // 避免 id 被赋值
// 调用
Long noticeId = noticeService.createNotice(reqVO);
// 校验插入属性是否正确
assertNotNull(noticeId);
NoticeDO notice = noticeMapper.selectById(noticeId);
assertPojoEquals(reqVO, notice, "id");
} |
@Override
public String getName()
{
return name.toLowerCase(ENGLISH);
} | @Test
public void testConversionWithoutConfigSwitchOn()
{
PinotConfig pinotConfig = new PinotConfig();
pinotConfig.setInferDateTypeInSchema(false);
pinotConfig.setInferTimestampTypeInSchema(false);
// Test Date
Schema testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.INT, TimeUnit.DAYS, "daysSinceEpoch"), new TimeGranularitySpec(FieldSpec.DataType.INT, TimeUnit.DAYS, "daysSinceEpoch"))
.build();
List<PinotColumn> pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
PinotColumn column = pinotColumns.get(0);
assertEquals(column.getName(), "daysSinceEpoch");
assertEquals(column.getType(), INTEGER);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.MILLISECONDS, "millisSinceEpoch"),
new TimeGranularitySpec(FieldSpec.DataType.INT, TimeUnit.DAYS, "daysSinceEpoch"))
.build();
pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
column = pinotColumns.get(0);
assertEquals(column.getName(), "daysSinceEpoch");
assertEquals(column.getType(), INTEGER);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
// Test Timestamp
testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.MILLISECONDS, "millisSinceEpoch"), new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.MILLISECONDS, "millisSinceEpoch"))
.build();
pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
column = pinotColumns.get(0);
assertEquals(column.getName(), "millisSinceEpoch");
assertEquals(column.getType(), BIGINT);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.INT, TimeUnit.DAYS, "daysSinceEpoch"),
new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.MILLISECONDS, "millisSinceEpoch"))
.build();
pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
column = pinotColumns.get(0);
assertEquals(column.getName(), "millisSinceEpoch");
assertEquals(column.getType(), BIGINT);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
// Test fallback to BIGINT
testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.SECONDS, "secondsSinceEpoch"), new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.SECONDS, "secondsSinceEpoch"))
.build();
pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
column = pinotColumns.get(0);
assertEquals(column.getName(), "secondsSinceEpoch");
assertEquals(column.getType(), BIGINT);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.MILLISECONDS, "millisSinceEpoch"),
new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.SECONDS, "secondsSinceEpoch"))
.build();
pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
column = pinotColumns.get(0);
assertEquals(column.getName(), "secondsSinceEpoch");
assertEquals(column.getType(), BIGINT);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
testSchema = new Schema.SchemaBuilder()
.addTime(new TimeGranularitySpec(FieldSpec.DataType.INT, TimeUnit.DAYS, "daysSinceEpoch"),
new TimeGranularitySpec(FieldSpec.DataType.LONG, TimeUnit.SECONDS, "secondsSinceEpoch"))
.build();
pinotColumns = PinotColumnUtils.getPinotColumnsForPinotSchema(testSchema, pinotConfig.isInferDateTypeInSchema(), pinotConfig.isInferTimestampTypeInSchema());
column = pinotColumns.get(0);
assertEquals(column.getName(), "secondsSinceEpoch");
assertEquals(column.getType(), BIGINT);
assertEquals(column.getComment(), FieldSpec.FieldType.TIME.name());
} |
public ApplicationBuilder startupProbe(String startupProbe) {
this.startupProbe = startupProbe;
return getThis();
} | @Test
void startupProbe() {
ApplicationBuilder builder = new ApplicationBuilder();
builder.startupProbe("TestProbe");
Assertions.assertEquals("TestProbe", builder.build().getStartupProbe());
} |
public Map<String, Object> createAuthenticationParameters(String relayState, AuthenticationRequest authenticationRequest) throws AdException {
HashMap<String, String> digidApp = new HashMap<>();
digidApp.put("name", authenticationRequest.getServiceName());
digidApp.put("url", authenticationRequest.getAppReturnUrl());
Map<String, Object> authenticationParameters = new HashMap<>();
authenticationParameters.put("app_session_id", retrieveAppSessionIdFromAd(authenticationRequest.getAppReturnUrl(), authenticationRequest));
authenticationParameters.put("SAMLart", authenticationRequest.getSamlSession().getArtifact());
authenticationParameters.put("apps", authenticationRequest.getAppActive() ? Arrays.asList(digidApp) : Collections.emptyList());
authenticationParameters.put("authentication_level", authenticationRequest.getSamlSession().getAuthenticationLevel());
authenticationParameters.put("image_domain", authenticationRequest.getAppReturnUrl());
authenticationParameters.put("RelayState", relayState);
return authenticationParameters;
} | @Test
public void createAuthenticationParametersSuccessful() throws AdException {
AdSession adSession = new AdSession();
adSession.setSessionId("sessionId");
when(adClientMock.startAppSession(anyString())).thenReturn(adResponse);
Map<String, Object> result = authenticationAppToAppService.createAuthenticationParameters("relayState", authenticationRequest);
assertNotNull(result);
assertEquals(6, result.size());
assertEquals("appSessionId", result.get("app_session_id"));
assertEquals("artifact", result.get("SAMLart"));
assertEquals(20, result.get("authentication_level"));
assertEquals("appReturnUrl", result.get("image_domain"));
assertEquals("relayState", result.get("RelayState"));
} |
public static int[] getCutIndices(String s, String splitChar, int index) {
int found = 0;
char target = splitChar.charAt(0);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == target) {
found++;
}
if (found == index) {
int begin = i;
if (begin != 0) {
begin += 1;
}
int end = s.indexOf(target, i + 1);
// End will be -1 if this is the last last token in the string and there is no other occurence.
if (end == -1) {
end = s.length();
}
return new int[]{begin, end};
}
}
return new int[]{0, 0};
} | @Test
public void testCutIndices() throws Exception {
int[] result = SplitAndIndexExtractor.getCutIndices("<10> 07 Aug 2013 somesubsystem: this is my message for username9001 id:9001", " ", 3);
assertEquals(12, result[0]);
assertEquals(16, result[1]);
} |
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
JsonNode jsonValue;
// This handles a tombstone message
if (value == null) {
return SchemaAndValue.NULL;
}
try {
jsonValue = deserializer.deserialize(topic, value);
} catch (SerializationException e) {
throw new DataException("Converting byte[] to Kafka Connect data failed due to serialization error: ", e);
}
if (config.schemasEnabled() && (!jsonValue.isObject() || jsonValue.size() != 2 || !jsonValue.has(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME) || !jsonValue.has(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME)))
throw new DataException("JsonConverter with schemas.enable requires \"schema\" and \"payload\" fields and may not contain additional fields." +
" If you are trying to deserialize plain JSON data, set schemas.enable=false in your converter configuration.");
// The deserialized data should either be an envelope object containing the schema and the payload or the schema
// was stripped during serialization and we need to fill in an all-encompassing schema.
if (!config.schemasEnabled()) {
ObjectNode envelope = JSON_NODE_FACTORY.objectNode();
envelope.set(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME, null);
envelope.set(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME, jsonValue);
jsonValue = envelope;
}
Schema schema = asConnectSchema(jsonValue.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
return new SchemaAndValue(
schema,
convertToConnect(schema, jsonValue.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME), config)
);
} | @Test
public void structWithOptionalFieldToConnect() {
byte[] structJson = "{ \"schema\": { \"type\": \"struct\", \"fields\": [{ \"field\":\"optional\", \"type\": \"string\", \"optional\": true }, { \"field\": \"required\", \"type\": \"string\" }] }, \"payload\": { \"required\": \"required\" } }".getBytes();
Schema expectedSchema = SchemaBuilder.struct().field("optional", Schema.OPTIONAL_STRING_SCHEMA).field("required", Schema.STRING_SCHEMA).build();
Struct expected = new Struct(expectedSchema).put("required", "required");
SchemaAndValue converted = converter.toConnectData(TOPIC, structJson);
assertEquals(new SchemaAndValue(expectedSchema, expected), converted);
} |
@Override
public ObjectNode encode(MappingAddress address, CodecContext context) {
EncodeMappingAddressCodecHelper encoder =
new EncodeMappingAddressCodecHelper(address, context);
return encoder.encode();
} | @Test
public void ethMappingAddressTest() {
MappingAddress address = MappingAddresses.ethMappingAddress(MAC);
ObjectNode result = addressCodec.encode(address, context);
assertThat(result, matchesMappingAddress(address));
} |
JChannel getResolvedChannel() {
return resolvedChannel;
} | @Test
public void shouldResolveDefaultChannel() {
// When
JGroupsEndpoint endpoint = getMandatoryEndpoint("jgroups:" + CLUSTER_NAME, JGroupsEndpoint.class);
// Then
assertNotNull(endpoint.getResolvedChannel());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.