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 re... |
public static NetworkPolicyPeer createPeer(Map<String, String> podSelector, LabelSelector namespaceSelector) {
return new NetworkPolicyPeerBuilder()
.withNewPodSelector()
.withMatchLabels(podSelector)
.endPodSelector()
.withNamespaceSelector(na... | @Test
public void testCreatePeerWithPodLabelsAndNamespaceSelector() {
NetworkPolicyPeer peer = NetworkPolicyUtils.createPeer(Map.of("labelKey", "labelValue"), new LabelSelectorBuilder().withMatchLabels(Map.of("nsLabelKey", "nsLabelValue")).build());
assertThat(peer.getNamespaceSelector().getMatchL... |
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()) {
... | @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);
... |
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) {
... | @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 = ne... |
@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());
asser... |
@Override
public void initialize(Configuration configuration, Properties tableProperties, Properties partitionProperties)
throws SerDeException {
super.initialize(configuration, tableProperties, partitionProperties);
jsonSerde.initialize(configuration, tableProperties, partitionProperties, false);
... | @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()... |
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 wa... | @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.valida... |
@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)) {
... | @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();
S... |
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();
... | @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... |
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.processWa1... |
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.keep... |
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) {
IClientConfig clientConfig = getRequestClientConfig(request);
Long originTimeout = getOriginReadTimeout();
Long requestTimeout = getRequestReadTimeout(clientConfig);
long computedTimeout;
if (origin... | @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(lineRang... |
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.0000... |
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)
... | @Test
public void testMerge() {
assertMerged(
vectorClock(uuidParams[0], 1),
vectorClock(),
vectorClock(uuidParams[0], 1));
assertMerged(
vectorClock(uuidParams[0], 1),
vectorClock(uuidParams[0], 2),
vect... |
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();
... |
public Optional<ComputationState> get(String computationId) {
try {
return Optional.ofNullable(computationCache.get(computationId));
} catch (UncheckedExecutionException
| ExecutionException
| ComputationStateNotFoundException e) {
if (e.getCause() instanceof ComputationStateNotFound... | @Test
public void testGet_computationStateNotCachedOrFetchable() {
String computationId = "computationId";
when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
Optional<ComputationState> computationState = computationStateCache.get(computationId);
assertFalse(computationSta... |
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 Strin... | @Test
void testValidServiceConfig() {
String validServiceConfig = """
{
"loadBalancingConfig": [
{"round_robin": {}}
],
"methodConfig": [
{
"name": [{}],
... |
@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()));
... | @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));
... |
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)) {
r... | @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 (conve... | @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"));
... |
@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 Big... |
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException {
final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest);
if (samlRequest instanceof AuthenticationRequest) {
dcMetadataResponseMapper.dcMetadataToAuthent... | @Test
public void resolveDcMetadataNoFederationTest() throws DienstencatalogusException {
DcMetadataResponse dcMetadataResponse = dcClientStubGetMetadata(stubsCaMetadataFile, null, 1L);
when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(dcMetadataResponse);
... |
@Override
public CompletableFuture<JobManagerRunnerResult> getResultFuture() {
return resultFuture;
} | @Test
void testJobMasterTerminationIsHandled() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
CompletableFuture<Void> jobMasterTerminat... |
@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 {
c... |
@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();... |
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)... |
@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 Smil... | @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());
... |
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 va... | @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.... |
@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 = p... |
public void handleWatchTopicList(NamespaceName namespaceName, long watcherId, long requestId, Pattern topicsPattern,
String topicsHash, Semaphore lookupSemaphore) {
if (!enableSubscriptionPatternEvaluation || topicsPattern.pattern().length() > maxSubscriptionPatternLength) ... | @Test
public void testCommandWatchErrorResponse() {
topicListService.handleWatchTopicList(
NamespaceName.get("tenant/ns"),
13,
7,
Pattern.compile("persistent://tenant/ns/topic\\d"),
null,
lookupSemaphore);
... |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariablesStatement sqlStatement, final ContextManager contextManager) {
ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData();
Collection<LocalDataQueryResultRow> result = ConfigurationPropertyK... | @Test
void assertExecute() {
when(contextManager.getMetaDataContexts().getMetaData().getProps()).thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property("system-log-level", "INFO"))));
when(contextManager.getMetaDataContexts().getMetaData().getTemporaryProps())
.t... |
public static DeviceDescription parseJuniperDescription(DeviceId deviceId,
HierarchicalConfiguration sysInfoCfg,
String chassisMacAddresses) {
HierarchicalConfiguration info = sysInfoCfg.confi... | @Test
public void testDeviceDescriptionParsedFromJunos19() throws IOException {
HierarchicalConfiguration getSystemInfoResp = XmlConfigParser.loadXml(
getClass().getResourceAsStream("/Junos_get-system-information_response_19.2.xml"));
String chassisText = CharStreams.toString(
... |
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) {
br... | @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> o... |
@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)
... |
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... |
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)... |
@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\"," +
" ... |
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(ur... | @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()
.setNa... |
@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 = Cla... | @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";
... | @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));
assertEq... |
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);
... | @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) {
... |
@Override
public CompletableFuture<Void> deleteSubscriptionGroup(String address, DeleteSubscriptionGroupRequestHeader requestHeader,
long timeoutMillis) {
CompletableFuture<Void> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DE... | @Test
public void assertDeleteSubscriptionGroupWithError() {
setResponseError();
DeleteSubscriptionGroupRequestHeader requestHeader = mock(DeleteSubscriptionGroupRequestHeader.class);
CompletableFuture<Void> actual = mqClientAdminImpl.deleteSubscriptionGroup(defaultBrokerAddr, requestHeader,... |
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... | @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);
... |
@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.Canonical... |
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},
... |
@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
pro... |
@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()));
}
... | @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 FinderLoca... |
@VisibleForTesting
static AbsoluteUnixPath getAppRootChecked(
RawConfiguration rawConfiguration, ProjectProperties projectProperties)
throws InvalidAppRootException {
String appRoot = rawConfiguration.getAppRoot();
if (appRoot.isEmpty()) {
appRoot =
projectProperties.isWarProject()... | @Test
public void testGetAppRootChecked_defaultNonWarProject() throws InvalidAppRootException {
when(rawConfiguration.getAppRoot()).thenReturn("");
when(projectProperties.isWarProject()).thenReturn(false);
assertThat(PluginConfigurationProcessor.getAppRootChecked(rawConfiguration, projectProperties))
... |
@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 ... | @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, acces... |
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.allowing... |
@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) ? St... | @Test
void testRemoveConfigInfoTag() {
String dataId = "dataId1112222";
String group = "group22";
String tenant = "tenant2";
String tag = "tag123345";
String srcIp = "ip345678";
String srcUser = "user1234567";
embeddedConfigInfoTagPersistService.removeConfigIn... |
@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... | @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_TY... |
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");
assertT... |
@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) {
Active... | @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_KE... |
@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), w... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullValueJoinerOnJoinWithStreamJoined() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(
testStream,
(ValueJoiner<? super ... |
BrokerInterceptorWithClassLoader load(BrokerInterceptorMetadata metadata, String narExtractionDirectory)
throws IOException {
final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
NarClassLoader ncl = NarClassLoaderBuilder.builder()
.narFile(narFile)
... | @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/l... |
public DefaultThreadPoolPluginManager setPluginComparator(@NonNull Comparator<Object> comparator) {
mainLock.runWithWriteLock(() -> {
// the specified comparator has been set
if (Objects.equals(this.pluginComparator, comparator)) {
return;
}
this.p... | @Test
public void testSetPluginComparator() {
Assert.assertFalse(manager.isEnableSort());
manager.register(new TestExecuteAwarePlugin());
manager.register(new TestTaskAwarePlugin());
manager.setPluginComparator(AnnotationAwareOrderComparator.INSTANCE);
manager.register(new T... |
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()),
... |
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.substrin... | @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.getEr... | @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});
chan... |
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) {
... | @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... |
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... | @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 = mo... |
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_STAT... | @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.s... | @Test
public void testComputeEntrypoint() {
SpringBootExplodedProcessor bootProcessor =
new SpringBootExplodedProcessor(
Paths.get("ignored"), Paths.get("ignored"), JAR_JAVA_VERSION);
ImmutableList<String> actualEntrypoint = bootProcessor.computeEntrypoint(new ArrayList<>());
assertTha... |
@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 v... | @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(), EnumS... |
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.
*... |
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 ObjectOutputSt... |
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(Fi... |
@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.in... | @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.computeIfAbsen... | @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) {
... | @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:... |
@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[]... |
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;
}
retu... | @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... | @Test
public void testObjectToDataCollection_deserializeBack() {
SerializationService serializationService = new DefaultSerializationServiceBuilder().build();
Collection<Object> list = new ArrayList<>();
list.add(1);
list.add("foo");
Collection<Data> dataCollection = objectT... |
@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 s... |
@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);
NoticeD... |
@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()
... |
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", authenticationRequ... | @Test
public void createAuthenticationParametersSuccessful() throws AdException {
AdSession adSession = new AdSession();
adSession.setSessionId("sessionId");
when(adClientMock.startAppSession(anyString())).thenReturn(adResponse);
Map<String, Object> result = authenticationAppToAppSe... |
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) {
... | @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);
}... | @Test
public void structWithOptionalFieldToConnect() {
byte[] structJson = "{ \"schema\": { \"type\": \"struct\", \"fields\": [{ \"field\":\"optional\", \"type\": \"string\", \"optional\": true }, { \"field\": \"required\", \"type\": \"string\" }] }, \"payload\": { \"required\": \"required\" } }".getBytes(... |
@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.