focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String requestMessageForCheckConnectionToPackage(PackageConfiguration packageConfiguration, RepositoryConfiguration repositoryConfiguration) {
Map configuredValues = new LinkedHashMap();
configuredValues.put("repository-configuration", jsonResultMessageHandler.configurationToMap(rep... | @Test
public void shouldBuildRequestBodyForCheckPackageConnectionRequest() throws Exception {
String requestMessage = messageHandler.requestMessageForCheckConnectionToPackage(packageConfiguration, repositoryConfiguration);
assertThat(requestMessage, is("{\"repository-configuration\":{\"key-one\":{\"... |
@VisibleForTesting
void validateDictTypeUnique(Long id, String type) {
if (StrUtil.isEmpty(type)) {
return;
}
DictTypeDO dictType = dictTypeMapper.selectByType(type);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if... | @Test
public void testValidateDictTypeUnique_valueDuplicateForCreate() {
// 准备参数
String type = randomString();
// mock 数据
dictTypeMapper.insert(randomDictTypeDO(o -> o.setType(type)));
// 调用,校验异常
assertServiceException(() -> dictTypeService.validateDictTypeUnique(nul... |
@Override
public void subscribe(final Subscriber<? super Row> subscriber) {
if (polling) {
throw new IllegalStateException("Cannot set subscriber if polling");
}
synchronized (this) {
subscribing = true;
super.subscribe(subscriber);
}
} | @Test
public void shouldDeliverBufferedRowsOnError() throws Exception {
// Given
givenPublisherAcceptsOneRow();
subscribe();
handleQueryResultError();
// When
subscription.request(1);
// Then
assertThatEventually(() -> subscriberReceivedRow, is(true));
assertThatEventually(() -> ... |
public static Optional<ConnectorPageSource> createHivePageSource(
Set<HiveRecordCursorProvider> cursorProviders,
Set<HiveBatchPageSourceFactory> pageSourceFactories,
Configuration configuration,
ConnectorSession session,
HiveFileSplit fileSplit,
Op... | @Test
public void testUseRecordReaderWithInputFormatAnnotationAndCustomSplit()
{
StorageFormat storageFormat = StorageFormat.create(ParquetHiveSerDe.class.getName(), HoodieParquetInputFormat.class.getName(), "");
Storage storage = new Storage(storageFormat, "test", Optional.empty(), true, Immuta... |
public Service getService() {
return service;
} | @Test
void testGetService() {
TestService service = mock(TestService.class);
ServiceBean serviceBean = new ServiceBean(null, service);
Service beanService = serviceBean.getService();
MatcherAssert.assertThat(beanService, not(nullValue()));
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatCastToStruct() {
// Given:
final Cast cast = new Cast(
new StringLiteral("foo"),
new Type(SqlStruct.builder()
.field("field", SqlTypes.STRING).build())
);
// When:
final String result = ExpressionFormatter.formatExpression(cast, FormatOpti... |
public static long readUnsignedIntLittleEndian(byte[] data, int index) {
long result = (long) (data[index] & 0xFF) | (long) ((data[index + 1] & 0xFF) << 8)
| (long) ((data[index + 2] & 0xFF) << 16) | (long) ((data[index + 3] & 0xFF) << 24);
return result;
} | @Test
public void testReadUnsignedIntLittleEndian() {
Assert.assertEquals(0L,
ByteHelper.readUnsignedIntLittleEndian(new byte[] {0, 0, 0, 0}, 0));
} |
public static int markProtocolType(int source, SerializeType type) {
return (type.getCode() << 24) | (source & 0x00FFFFFF);
} | @Test
public void testMarkProtocolType_JSONProtocolType() {
int source = 261;
SerializeType type = SerializeType.JSON;
byte[] result = new byte[4];
int x = RemotingCommand.markProtocolType(source, type);
result[0] = (byte) (x >> 24);
result[1] = (byte) (x >> 16);
... |
@Override
public Object execute(String command, byte[]... args) {
for (Method method : this.getClass().getDeclaredMethods()) {
if (method.getName().equalsIgnoreCase(command)
&& Modifier.isPublic(method.getModifiers())
&& (method.getParameterTypes().len... | @Test
public void testExecute() {
Long s = (Long) connection.execute("ttl", "key".getBytes());
assertThat(s).isEqualTo(-2);
connection.execute("flushDb");
} |
void reload() throws IOException {
clear();
load();
} | @Test
public void testReload() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory1 = mapper.putIfAbsent(user1, true);
mapper.reload();
assertThat(mapper.isMapped(user1), is(true));
assertT... |
public static List<String> split(String path) {
//
String[] pathelements = path.split("/");
List<String> dirs = new ArrayList<String>(pathelements.length);
for (String pathelement : pathelements) {
if (!pathelement.isEmpty()) {
dirs.add(pathelement);
}
}
return dirs;
} | @Test
public void testSplittingEmpty() throws Throwable {
assertEquals(0, split("").size());
assertEquals(0, split("/").size());
assertEquals(0, split("///").size());
} |
public static SerdeFeatures buildValueFeatures(
final LogicalSchema schema,
final Format valueFormat,
final SerdeFeatures explicitFeatures,
final KsqlConfig ksqlConfig
) {
final boolean singleColumn = schema.value().size() == 1;
final ImmutableSet.Builder<SerdeFeature> builder = Immut... | @Test
public void shouldNotGetSingleValueWrappingFromConfigForMultiFields() {
// Given:
ksqlConfig = new KsqlConfig(ImmutableMap.of(
KsqlConfig.KSQL_WRAP_SINGLE_VALUES, false
));
// When:
final SerdeFeatures result = SerdeFeaturesFactory.buildValueFeatures(
MULTI_FIELD_SCHEMA,
... |
CodeEmitter<T> emit(final Parameter parameter) {
emitter.emit("param");
emit("name", parameter.getName());
final String parameterType = parameter.getIn();
if (ObjectHelper.isNotEmpty(parameterType)) {
emit("type", RestParamType.valueOf(parameterType));
}
if (... | @Test
public void shouldEmitCodeForOas3ParameterWithDefaultValue() {
final Builder method = MethodSpec.methodBuilder("configure");
final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method);
final OperationVisitor<?> visitor = new OperationVisitor<>(emitter, null, nu... |
public static Criterion matchInPort(PortNumber port) {
return new PortCriterion(port, Type.IN_PORT);
} | @Test
public void testMatchInPortMethod() {
PortNumber p1 = portNumber(1);
Criterion matchInPort = Criteria.matchInPort(p1);
PortCriterion portCriterion =
checkAndConvert(matchInPort,
Criterion.Type.IN_PORT,
Port... |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
public void testNewCombiningNoFetch() throws Exception {
GroupingState<Integer, Integer> value = underTestNewKey.state(NAMESPACE, COMBINING_ADDR);
assertThat(value.isEmpty().read(), Matchers.is(true));
assertThat(value.read(), Matchers.is(Sum.ofIntegers().identity()));
assertThat(value.isEmpty(... |
@VisibleForTesting
StreamingEngineConnectionState getCurrentConnections() {
return connections.get();
} | @Test
public void testStreamsStartCorrectly() throws InterruptedException {
long items = 10L;
long bytes = 10L;
int numBudgetDistributionsExpected = 1;
TestGetWorkBudgetDistributor getWorkBudgetDistributor =
spy(new TestGetWorkBudgetDistributor(numBudgetDistributionsExpected));
fanOutStr... |
public List<File> getFiles( File file, String filters, boolean useCache ) throws FileException {
try {
FileProvider<File> fileProvider = providerService.get( file.getProvider() );
List<File> files;
if ( fileCache.containsKey( file ) && useCache ) {
files = fileCache.getFiles( file ).stream... | @Test
public void testGetFilesCache() throws FileException {
TestDirectory testDirectory = new TestDirectory();
testDirectory.setPath( "/" );
List<File> files = fileController.getFiles( testDirectory, null, true );
Assert.assertEquals( 8, files.size() );
Assert.assertTrue( fileController.fileCach... |
@Override
public VersionedKeyValueStore<K, V> build() {
final KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof VersionedBytesStore)) {
throw new IllegalStateException("VersionedBytesStoreSupplier.get() must return an instance of VersionedBytesStore");
... | @Test
public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() {
setUp();
final VersionedKeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.build();
assertThat(store, instanceOf(MeteredVersionedKeyValueStore.class));
... |
public static ExecutableStage forGrpcPortRead(
QueryablePipeline pipeline,
PipelineNode.PCollectionNode inputPCollection,
Set<PipelineNode.PTransformNode> initialNodes) {
checkArgument(
!initialNodes.isEmpty(),
"%s must contain at least one %s.",
GreedyStageFuser.class.getS... | @Test
public void differentEnvironmentsThrows() {
// (impulse.out) -> read -> read.out --> go -> go.out
// \
// -> py -> py.out
// read.out can't be fused with both 'go' and 'py', so we should refuse to create this stage
Queryabl... |
@GetMapping("/list")
@TpsControl(pointName = "NamingServiceListQuery", name = "HttpNamingServiceListQuery")
@Secured(action = ActionTypes.READ)
public ObjectNode list(HttpServletRequest request) throws Exception {
final int pageNo = NumberUtils.toInt(WebUtils.required(request, "pageNo"));
fi... | @Test
void testList() throws Exception {
Mockito.when(serviceOperatorV2.listService(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
.thenReturn(Collections.singletonList("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:1"));
MockHttpServle... |
public ImmutableList<Replacement> format(
SnippetKind kind,
String source,
List<Range<Integer>> ranges,
int initialIndent,
boolean includeComments)
throws FormatterException {
RangeSet<Integer> rangeSet = TreeRangeSet.create();
for (Range<Integer> range : ranges) {
rang... | @Test
public void compilation() throws FormatterException {
String input = "/** a\nb*/\nclass Test {\n}";
List<Replacement> replacements =
new SnippetFormatter()
.format(
SnippetKind.COMPILATION_UNIT,
input,
ImmutableList.of(Range.closedOpen(... |
@Override
public List<String> validateText(String text, List<String> tags) {
Assert.isTrue(ENABLED, "敏感词功能未开启,请将 ENABLED 设置为 true");
// 无标签时,默认所有
if (CollUtil.isEmpty(tags)) {
return defaultSensitiveWordTrie.validate(text);
}
// 有标签的情况
Set<String> result ... | @Test
public void testValidateText_noTag() {
testInitLocalCache();
// 准备参数
String text = "你是傻瓜,你是笨蛋";
// 调用
List<String> result = sensitiveWordService.validateText(text, null);
// 断言
assertEquals(Arrays.asList("傻瓜", "笨蛋"), result);
// 准备参数
Str... |
public CompletableFuture<InetSocketAddress> resolveAndCheckTargetAddress(String hostAndPort) {
int pos = hostAndPort.lastIndexOf(':');
String host = hostAndPort.substring(0, pos);
int port = Integer.parseInt(hostAndPort.substring(pos + 1));
if (!isPortAllowed(port)) {
return ... | @Test
public void shouldSupportHostNamePattern() throws Exception {
BrokerProxyValidator brokerProxyValidator = new BrokerProxyValidator(
createMockedAddressResolver("1.2.3.4"),
"*.mydomain"
, "1.2.0.0/16"
, "6650");
brokerProxyValidato... |
@Override
protected String ruleHandler() {
return new WebSocketRuleHandle().toJson();
} | @Test
public void testRuleHandler() {
assertEquals(new WebSocketRuleHandle().toJson(), shenyuClientRegisterWebSocketService.ruleHandler());
} |
@Override
public RecordCursor cursor()
{
return new ExampleRecordCursor(columnHandles, byteSource);
} | @Test
public void testCursorSimple()
{
RecordSet recordSet = new ExampleRecordSet(new ExampleSplit("test", "schema", "table", dataUri), ImmutableList.of(
new ExampleColumnHandle("test", "text", createUnboundedVarcharType(), 0),
new ExampleColumnHandle("test", "value", BIG... |
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<CeActivityDto> recentSuccessfulTasks = getRecentSuccessfulTasks(dbSession);
Collection<String> entityUuids = recentSuccessfulTasks.stream()
.map(CeActivityDto::getEntityUuid)
.toList();
... | @Test
public void run_given5SuccessfulTasks_observeDurationFor5Tasks() {
RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system);
List<CeActivityDto> recentTasks = createTasks(5, 0);
when(entityDao.selectByUuids(any(), any())).thenReturn(createEntityDtos(5));
whe... |
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
final double pos = q... | @Test
public void smallQuantilesAreTheFirstValue() throws Exception {
assertThat(snapshot.getValue(0.0))
.isEqualTo(1, offset(0.1));
} |
public static FlinkPod loadPodFromTemplateFile(
FlinkKubeClient kubeClient, File podTemplateFile, String mainContainerName) {
final KubernetesPod pod = kubeClient.loadPodFromTemplateFile(podTemplateFile);
final List<Container> otherContainers = new ArrayList<>();
Container mainContai... | @Test
void testLoadPodFromTemplateWithNoMainContainerShouldReturnEmptyMainContainer() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
... |
public static int getRandomPort() {
return RND_PORT_START + ThreadLocalRandom.current().nextInt(RND_PORT_RANGE);
} | @Test
void testGetRandomPort() {
assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000));
assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000));
assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000));
} |
@Override
public String doLayout(ILoggingEvent event) {
StringWriter output = new StringWriter();
try (JsonWriter json = new JsonWriter(output)) {
json.beginObject();
if (!"".equals(nodeName)) {
json.name("nodename").value(nodeName);
}
json.name("process").value(processKey);
... | @Test
public void test_simple_log_with_hostname() {
LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]);
LogbackJsonLayout underTestWithNodeName = new LogbackJsonLayout("web", "my-nodename");
String... |
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'."
+ " The system default time zon... | @Test
public void testTimeZoneInLocalTime() {
// Given:
final long timestamp = 1534353043000L;
// When:
final String localTime = udf.timestampToString(timestamp, "yyyy-MM-dd HH:mm:ss zz");
// Then:
final String expected = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zz")
.format(new Dat... |
public String[] getCoderNames(String codecName) {
String[] coderNames = coderNameMap.get(codecName);
return coderNames;
} | @Test
public void testGetCoderNames() {
String[] coderNames = CodecRegistry.getInstance().
getCoderNames(ErasureCodeConstants.RS_CODEC_NAME);
assertEquals(2, coderNames.length);
assertEquals(NativeRSRawErasureCoderFactory.CODER_NAME, coderNames[0]);
assertEquals(RSRawErasureCoderFactory.CODER_... |
public URL getSignature(String base, Map<String, String> queryParams) {
// Add the RTM specific query params to the map for signing
Map<String, String> modifiedParams = new HashMap<>();
modifiedParams.putAll(queryParams);
modifiedParams.put("api_key", appCredentials.getKey());
modifiedParams.put("au... | @Test
public void signatureTest() throws Exception {
String base = "http://example.com";
Map<String, String> queryParams = ImmutableMap.of("yxz", "foo", "feg", "bar", "abc", "baz");
URL expected =
new URL(
base
+ "?abc=baz&api_key=BANANAS1&auth_token=BANANAS3&feg=bar&y... |
public abstract void filter(Metadata metadata) throws TikaException; | @Test
public void testCaptureGroupOverwrite() throws Exception {
TikaConfig config = getConfig("TIKA-4133-capture-group-overwrite.xml");
Metadata metadata = new Metadata();
metadata.set(TikaCoreProperties.TIKA_CONTENT, "quick brown fox");
metadata.set(Metadata.CONTENT_TYPE, "text/ht... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Target target = getTarget(request);
if (target == Target.Other) {
chain.doFilter(request, response);
return;
}
HttpServl... | @Test
public void testCustomClientShedding() throws Exception {
// Custom clients will go up to the window limit
whenRequest(FULL_FETCH, CUSTOM_CLIENT);
filter.doFilter(request, response, filterChain);
filter.doFilter(request, response, filterChain);
verify(filterChain, time... |
public void start() {
if (isPeriodicMaterializeEnabled) {
if (!started) {
started = true;
LOG.info("Task {} starts periodic materialization", subtaskName);
scheduleNextMaterialization(initialDelay);
}
} else {
LOG.inf... | @Test
void testInitialDelay() {
ManuallyTriggeredScheduledExecutorService scheduledExecutorService =
new ManuallyTriggeredScheduledExecutorService();
long periodicMaterializeDelay = 10_000L;
try (PeriodicMaterializationManager test =
new PeriodicMaterializati... |
@Override
public void resetConfigStats(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_RESETSTAT);
syncFuture(f);
} | @Test
public void testResetConfigStats() {
RedisClusterNode master = getFirstMaster();
connection.resetConfigStats(master);
} |
public boolean start(
WorkflowSummary workflowSummary, Step step, StepRuntimeSummary runtimeSummary) {
StepRuntime.Result result =
getStepRuntime(runtimeSummary.getType())
.start(workflowSummary, step, cloneSummary(runtimeSummary));
runtimeSummary.mergeRuntimeUpdate(result.getTimeline(... | @Test
public void testStart() {
StepRuntimeSummary summary =
StepRuntimeSummary.builder()
.type(StepType.NOOP)
.stepRetry(StepInstance.StepRetry.from(Defaults.DEFAULT_RETRY_POLICY))
.build();
boolean ret = runtimeManager.start(workflowSummary, null, summary);
as... |
public CatalogueTreeSortStrategy getStrategy(String strategyName) {
CatalogueTreeSortStrategy catalogueTreeSortStrategy =
Safes.of(catalogueTreeSortStrategyMap).get(strategyName);
if (Objects.isNull(catalogueTreeSortStrategy)) {
log.warn("Strategy {} is not defined. Use Defau... | @Test
public void getStrategyTest2() {
when(catalogueTreeSortStrategyMap.get(anyString())).thenAnswer(invocationOnMock -> {
String strategy = invocationOnMock.getArgument(0);
return mockCatalogueTreeSortStrategyMap.get(strategy);
});
CatalogueTreeSortStrategy strateg... |
@Override
public Long createJobLog(Long jobId, LocalDateTime beginTime,
String jobHandlerName, String jobHandlerParam, Integer executeIndex) {
JobLogDO log = JobLogDO.builder().jobId(jobId).handlerName(jobHandlerName)
.handlerParam(jobHandlerParam).executeIndex(e... | @Test
public void testCreateJobLog() {
// 准备参数
JobLogDO reqVO = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1));
// 调用
Long id = jobLogService.createJobLog(reqVO.getJobId(), reqVO.getBeginTime(),
reqVO.getHandlerName(), reqVO.getHandlerParam(), reqVO.getExecute... |
@Override
public long getMin() {
if (values.length == 0) {
return 0;
}
return values[0];
} | @Test
public void calculatesTheMinimumValue() {
assertThat(snapshot.getMin())
.isEqualTo(1);
} |
public static ObjectInputDecoder createDecoder(Type type, TypeManager typeManager)
{
String base = type.getTypeSignature().getBase();
switch (base) {
case UnknownType.NAME:
return o -> o;
case BIGINT:
return o -> (Long) o;
case INTE... | @Test
public void testSliceObjectDecoders()
{
ObjectInputDecoder decoder;
decoder = createDecoder(VARBINARY, typeManager);
assertTrue(decoder.decode(Slices.wrappedBuffer(new byte[] {12, 34, 56})) instanceof byte[]);
decoder = createDecoder(VARCHAR, typeManager);
assertT... |
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
initCacheConfig();
final String pluginName = named();
PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(pluginName);
// early exit
if (Objects.isNull(plug... | @Test
public void executeSelectorDataIsNullTest() {
BaseDataCache.getInstance().cachePluginData(pluginData);
BaseDataCache.getInstance().cacheSelectData(selectorData);
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).expectSubscription().verifyComplete();
ve... |
public static void d(String tag, String message, Object... args) {
sLogger.d(tag, message, args);
} | @Test
public void debug() {
String tag = "TestTag";
String message = "Test message";
LogManager.d(tag, message);
verify(logger).d(tag, message);
} |
@Override
public AppResponse process(Flow flow, AppRequest body) {
if (appSession.getRdaSessionStatus().equals("VERIFIED")) {
((ActivationFlow) flow).activateApp(appAuthenticator, appSession, RDA);
digidClient.remoteLog("1219", Map.of(lowerUnderscore(ACCOUNT_ID), appSession.getAccou... | @Test
void processAppSessionVerified(){
mockedAppSession.setRdaSessionStatus("VERIFIED");
AppResponse appResponse = finalizeRda.process(mockedFlow, mockedAbstractAppRequest);
verify(mockedFlow, times(1)).activateApp(mockedAppAuthenticator, mockedAppSession, "rda");
verify(digidClie... |
@Override
public RelativeRange apply(final Period period) {
if (period != null) {
return RelativeRange.Builder.builder()
.from(period.withYears(0).withMonths(0).plusDays(period.getYears() * 365).plusDays(period.getMonths() * 30).toStandardSeconds().getSeconds())
... | @Test
void testMinuteConversion() {
final RelativeRange result = converter.apply(Period.minutes(30));
verifyResult(result, 1800);
} |
public boolean parse(final String s) {
if (StringUtils.isEmpty(s) || StringUtils.isBlank(s)) {
return false;
}
final String[] tmps = Utils.parsePeerId(s);
if (tmps.length < 2 || tmps.length > 4) {
return false;
}
try {
final int port =... | @Test
public void testToStringPeerIdFalse() {
final PeerId serverId = new PeerId();
assertFalse(serverId.parse(null));
assertFalse(serverId.parse(""));
assertFalse(serverId.parse(" "));
} |
public static <T> RestResponse<T> toRestResponse(
final ResponseWithBody resp,
final String path,
final Function<ResponseWithBody, T> mapper
) {
final int statusCode = resp.getResponse().statusCode();
return statusCode == OK.code()
? RestResponse.successful(statusCode, mapper.apply(r... | @Test
public void shouldCreateRestResponseFromUnauthorizedResponse() {
// Given:
when(httpClientResponse.statusCode()).thenReturn(UNAUTHORIZED.code());
// When:
final RestResponse<KsqlEntityList> restResponse =
KsqlClientUtil.toRestResponse(response, PATH, mapper);
// Then:
assertTha... |
@SuppressWarnings("unchecked")
@Override
public OUT[] extract(Object in) {
OUT[] output = (OUT[]) Array.newInstance(clazz, order.length);
for (int i = 0; i < order.length; i++) {
output[i] = (OUT) Array.get(in, this.order[i]);
}
return output;
} | @Test
void testStringArray() {
// check single field extraction
for (int i = 0; i < testStringArray.length; i++) {
String[] tmp = {testStringArray[i]};
arrayEqualityCheck(
tmp, new FieldsFromArray<>(String.class, i).extract(testStringArray));
}
... |
static ValueExtractor instantiateExtractor(AttributeConfig config, ClassLoader classLoader) {
ValueExtractor extractor = null;
if (classLoader != null) {
try {
extractor = instantiateExtractorWithConfigClassLoader(config, classLoader);
} catch (IllegalArgumentExce... | @Test
public void instantiate_extractor() {
// GIVEN
AttributeConfig config
= new AttributeConfig("iq", "com.hazelcast.query.impl.getters.ExtractorHelperTest$IqExtractor");
// WHEN
ValueExtractor extractor = instantiateExtractor(config);
// THEN
asse... |
public static void onFail(final ServerMemberManager manager, final Member member) {
// To avoid null pointer judgments, pass in one NONE_EXCEPTION
onFail(manager, member, ExceptionUtil.NONE_EXCEPTION);
} | @Test
void testMemberOnFailWhenConnectRefused() {
final Member remote = buildMember();
mockMemberAddressInfos.add(remote.getAddress());
remote.setFailAccessCnt(1);
MemberUtil.onFail(memberManager, remote, new ConnectException(MemberUtil.TARGET_MEMBER_CONNECT_REFUSE_ERRMSG));
... |
@Override
public void setConfiguration(final Path file, final PasswordCallback prompt, final VersioningConfiguration configuration) throws BackgroundException {
final Path container = containerService.getContainer(file);
try {
final Storage.Buckets.Patch request = session.getClient().buc... | @Test
public void testSetConfiguration() throws Exception {
final Path container = new Path(new AsciiRandomStringService().random().toLowerCase(Locale.ROOT), EnumSet.of(Path.Type.directory, Path.Type.volume));
new GoogleStorageDirectoryFeature(session).mkdir(container, new TransferStatus());
... |
static boolean isReady(@Nullable CompletableFuture<?> future) {
return (future != null) && future.isDone()
&& !future.isCompletedExceptionally()
&& (future.join() != null);
} | @Test(dataProvider = "unsuccessful")
public void isReady_fails(CompletableFuture<Integer> future) {
assertThat(Async.isReady(future)).isFalse();
} |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherVal... | @Test
void assertCompareToWhenSecondValueIsNullForOrderByAscAndNullsLast() {
assertThat(CompareUtils.compareTo(1, null, OrderDirection.ASC, NullsOrderType.LAST, caseSensitive), is(-1));
} |
public static SkillChallengeClue forText(String text, String rawText)
{
for (SkillChallengeClue clue : CLUES)
{
if (rawText.equalsIgnoreCase(clue.returnText))
{
clue.setChallengeCompleted(true);
return clue;
}
else if (text.equals(clue.rawChallenge))
{
clue.setChallengeCompleted(false);
... | @Test
public void forTextEmptyString()
{
assertNull(SkillChallengeClue.forText("", ""));
} |
public PushConnection remove(final String clientId) {
final PushConnection pc = clientPushConnectionMap.remove(clientId);
return pc;
} | @Test
void testRemove() {
pushConnectionRegistry.put("clientId1", pushConnection);
assertEquals(pushConnection, pushConnectionRegistry.remove("clientId1"));
assertNull(pushConnectionRegistry.get("clientId1"));
} |
@Override
public String getName() {
return _name;
} | @Test
public void testBigDecimalSerDeTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("bigDecimalToBytes(%s)", BIG_DECIMAL_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
assertTrue(tra... |
@Override
public MapperResult findConfigInfo4PageFetchRows(MapperContext context) {
final String tenant = (String) context.getWhereParameter(FieldConstant.TENANT_ID);
final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID);
final String group = (String) context.getWhe... | @Test
void testFindConfigInfo4PageFetchRows() {
context.putWhereParameter(FieldConstant.DATA_ID, "dataID1");
context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1");
context.putWhereParameter(FieldConstant.APP_NAME, "AppName1");
context.putWhereParameter(FieldConstant.CONTENT, ... |
@Override
public byte[] retrieveSecret(SecretIdentifier identifier) {
if (identifier != null && identifier.getKey() != null && !identifier.getKey().isEmpty()) {
try {
lock.lock();
loadKeyStore();
SecretKeyFactory factory = SecretKeyFactory.getInsta... | @Test
public void retrieveMissingSecret() {
assertThat(keyStore.retrieveSecret(new SecretIdentifier("does-not-exist"))).isNull();
} |
public static File[] getPathFiles(String path) throws FileNotFoundException {
URL url = ResourceUtils.class.getClassLoader().getResource(path);
if (url == null) {
throw new FileNotFoundException("path not found: " + path);
}
return Arrays.stream(Objects.requireNonNull(new Fil... | @Test
public void testGetPathFilesNotFound() {
assertThrows(FileNotFoundException.class, () -> ResourceUtils.getPathFiles("doesn't exist"));
} |
@Override
public PageResult<OAuth2AccessTokenDO> getAccessTokenPage(OAuth2AccessTokenPageReqVO reqVO) {
return oauth2AccessTokenMapper.selectPage(reqVO);
} | @Test
public void testGetAccessTokenPage() {
// mock 数据
OAuth2AccessTokenDO dbAccessToken = randomPojo(OAuth2AccessTokenDO.class, o -> { // 等会查询到
o.setUserId(10L);
o.setUserType(1);
o.setClientId("test_client");
o.setExpiresTime(LocalDateTime.now().plu... |
void checkFlow(ResourceWrapper resource, Context context, DefaultNode node, int count, boolean prioritized)
throws BlockException {
checker.checkFlow(ruleProvider, resource, context, node, count, prioritized);
} | @Test
@SuppressWarnings("unchecked")
public void testCheckFlowPass() throws Exception {
FlowRuleChecker checker = mock(FlowRuleChecker.class);
FlowSlot flowSlot = new FlowSlot(checker);
Context context = mock(Context.class);
DefaultNode node = mock(DefaultNode.class);
doC... |
@Override
public Set<TopicAnomaly> topicAnomalies() {
LOG.info("Start to detect topic replication factor anomaly.");
Cluster cluster = _kafkaCruiseControl.kafkaCluster();
Set<String> topicsToCheck;
if (_topicExcludedFromCheck.pattern().isEmpty()) {
topicsToCheck = new HashSet<>(cluster.topics())... | @Test
public void testAnomalyDetection() throws InterruptedException, ExecutionException, TimeoutException {
KafkaCruiseControl mockKafkaCruiseControl = mockKafkaCruiseControl();
AdminClient mockAdminClient = mockAdminClient((short) 1);
TopicReplicationFactorAnomalyFinder anomalyFinder = new TopicReplicat... |
@SuppressWarnings("unchecked")
public static <T extends Throwable> T wrap(Throwable throwable, Class<T> wrapThrowable) {
if (wrapThrowable.isInstance(throwable)) {
return (T) throwable;
}
return ReflectUtil.newInstance(wrapThrowable, throwable);
} | @Test
public void wrapTest() {
IORuntimeException e = ExceptionUtil.wrap(new IOException(), IORuntimeException.class);
assertNotNull(e);
} |
@Override
public int compare(final List<String> o1, final List<String> o2) {
if (o1.size() < o2.size()) {
return -1;
} else if (o1.size() > o2.size()) {
return 1;
} else {
int index = 0;
while (index < o1.size()) {
String item1... | @Test
void testEmptyListIsSmallerThanListWithElements() {
assertTrue(toTest.compare(List.of(), List.of("mum")) < 0);
assertTrue(toTest.compare(List.of("mum", "Dad"), List.of()) > 0);
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchedRecordsRaisesOnSerializationErrors() {
// raise an exception from somewhere in the middle of the fetch response
// so that we can verify that our position does not advance after raising
ByteArrayDeserializer deserializer = new ByteArrayDeserializer() {
... |
public Optional<UpdateCenter> getUpdateCenter(boolean refreshUpdateCenter) {
Optional<UpdateCenter> updateCenter = centerClient.getUpdateCenter(refreshUpdateCenter);
if (updateCenter.isPresent()) {
org.sonar.api.utils.Version fullVersion = sonarQubeVersion.get();
org.sonar.api.utils.Version semantic... | @Test
public void return_absent_update_center() {
UpdateCenterClient updateCenterClient = mock(UpdateCenterClient.class);
when(updateCenterClient.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty());
underTest = new UpdateCenterMatrixFactory(updateCenterClient, mock(SonarQubeVersion.class), mock(I... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testEnumValue() throws Exception {
JmxCollector jc =
new JmxCollector(
"\n---\nrules:\n- pattern: `org.bean.enum<type=StateMetrics.*>State: RUNNING`\n name: bean_running\n value: 1"
.replace('`', '"')... |
@Udf
public Map<String, String> splitToMap(
@UdfParameter(
description = "Separator string and values to join") final String input,
@UdfParameter(
description = "Separator string and values to join") final String entryDelimiter,
@UdfParameter(
description = "Separator s... | @Test
public void shouldReturnNullOnNullInputString() {
Map<String, String> result = udf.splitToMap(null, "/", ":=");
assertThat(result, is(nullValue()));
} |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "{namespace}/files/directory")
@Operation(tags = {"Files"}, summary = "List directory content")
public List<FileAttributes> list(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The internal storag... | @Test
void list() throws IOException {
String hw = "Hello World";
storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test/test.txt")), new ByteArrayInputStream(hw.getBytes()));
storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test/test2.txt")),... |
public static Path fromString(String path) {
return fromString(path, "/");
} | @Test(expected = IllegalArgumentException.class)
public void testDoubleDot() {
Path.fromString("foo/../bar");
} |
@Override
public Set<K> keySet() {
return keySet(null);
} | @Test
public void testKeySet() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.keySet()).c... |
static boolean unprotectedSetTimes(
FSDirectory fsd, INodesInPath iip, long mtime, long atime, boolean force)
throws FileNotFoundException {
assert fsd.hasWriteLock();
boolean status = false;
INode inode = iip.getLastINode();
if (inode == null) {
throw new FileNotFoundException("File/D... | @Test(expected = FileNotFoundException.class)
public void testUnprotectedSetTimesFNFE()
throws FileNotFoundException {
FSDirectory fsd = Mockito.mock(FSDirectory.class);
INodesInPath iip = Mockito.mock(INodesInPath.class);
when(fsd.hasWriteLock()).thenReturn(Boolean.TRUE);
when(iip.getLastINode... |
public static Patch<String> diffInline(String original, String revised) {
List<String> origList = new ArrayList<>();
List<String> revList = new ArrayList<>();
for (Character character : original.toCharArray()) {
origList.add(character.toString());
}
for (Character cha... | @Test
public void testDiffInline() {
final Patch<String> patch = DiffUtils.diffInline("", "test");
assertEquals(1, patch.getDeltas().size());
assertTrue(patch.getDeltas().get(0) instanceof InsertDelta);
assertEquals(0, patch.getDeltas().get(0).getSource().getPosition());
asse... |
public SqlConfig setCatalogPersistenceEnabled(final boolean catalogPersistenceEnabled) {
this.catalogPersistenceEnabled = catalogPersistenceEnabled;
return this;
} | @Test
public void testSQLPersistenceEnabledWithoutEELicense() {
final Config config = new Config();
config.getSqlConfig().setCatalogPersistenceEnabled(true);
assertThatThrownBy(() -> Hazelcast.newHazelcastInstance(config))
.isInstanceOf(IllegalStateException.class)
... |
@Override
public <V1, R> KTable<K, R> outerJoin(final KTable<K, V1> other,
final ValueJoiner<? super V, ? super V1, ? extends R> joiner) {
return outerJoin(other, joiner, NamedInternal.empty());
} | @Test
public void shouldThrowNullPointerOnOuterJoinWhenMaterializedIsNull() {
assertThrows(NullPointerException.class, () -> table.outerJoin(table, MockValueJoiner.TOSTRING_JOINER, (Materialized) null));
} |
@Override
public int getColumnLength(final Object value) {
return 8;
} | @Test
void assertGetColumnLength() {
assertThat(new PostgreSQLDoubleBinaryProtocolValue().getColumnLength(""), is(8));
} |
public static List<String> withRemovedMetricAlias(Collection<String> metrics) {
if (metrics.contains(REMOVED_METRIC)) {
Set<String> newMetrics = new HashSet<>(metrics);
newMetrics.remove(REMOVED_METRIC);
newMetrics.add(DEPRECATED_METRIC_REPLACEMENT);
return newMetrics.stream().toList();
... | @Test
void withRemovedMetricAlias_whenListContainsAccepted_shouldReturnListWithAccepted() {
List<String> coreMetrics = List.of("accepted_issues", "blocker_violations", "critical_violations");
List<String> upToDateMetrics = RemovedMetricConverter.withRemovedMetricAlias(coreMetrics);
assertThat(upToDateMe... |
@Override
public boolean isAutoIncrement(final int column) {
Preconditions.checkArgument(1 == column);
return true;
} | @Test
void assertIsAutoIncrement() throws SQLException {
assertTrue(actualMetaData.isAutoIncrement(1));
} |
@Override
public HttpHeaders add(HttpHeaders headers) {
if (headers instanceof DefaultHttpHeaders) {
this.headers.add(((DefaultHttpHeaders) headers).headers);
return this;
} else {
return super.add(headers);
}
} | @Test
public void addObjects() {
final DefaultHttpHeaders headers = newDefaultDefaultHttpHeaders();
headers.add(HEADER_NAME, HeaderValue.THREE.asList());
assertDefaultValues(headers, HeaderValue.THREE);
} |
@Override
public void open(Map<String, Object> config, SinkContext sinkContext) throws Exception {
alluxioSinkConfig = AlluxioSinkConfig.load(config);
alluxioSinkConfig.validate();
// initialize FileSystem
String alluxioMasterHost = alluxioSinkConfig.getAlluxioMasterHost();
... | @Test
public void openTest() throws Exception {
map.put("filePrefix", "TopicA");
map.put("fileExtension", ".txt");
map.put("lineSeparator", "\n");
map.put("rotationRecords", "100");
String alluxioDir = "/pulsar";
sink = new AlluxioSink();
sink.open(map, mock... |
public boolean isEmpty() {
return value == null;
} | @Test
public void isEmptyTest() {
// 这是jdk11 Optional中的新函数,直接照搬了过来
// 判断包裹内元素是否为空,注意并没有判断空字符串的情况
boolean isEmpty = Opt.empty().isEmpty();
assertTrue(isEmpty);
} |
@Override
public void restRequest(RestRequest request, Callback<RestResponse> callback, String routeKey)
{
this.restRequest(request, new RequestContext(), callback, routeKey);
} | @Test
public void testRouteLookupClientCallback()
throws InterruptedException, ExecutionException, TimeoutException
{
RouteLookup routeLookup = new SimpleTestRouteLookup();
final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build();
d2Client.start(new FutureCallback<>());
... |
public void setRocketMQMessageListener(RocketMQMessageListener anno) {
this.rocketMQMessageListener = anno;
this.consumeMode = anno.consumeMode();
this.consumeThreadMax = anno.consumeThreadMax();
this.consumeThreadNumber = anno.consumeThreadNumber();
this.messageModel = anno.mes... | @Test
public void testSetRocketMQMessageListener() {
DefaultRocketMQListenerContainer container = new DefaultRocketMQListenerContainer();
RocketMQMessageListener anno = TestRocketMQMessageListener.class.getAnnotation(RocketMQMessageListener.class);
container.setRocketMQMessageListener(anno);... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
try {
session.sftp().rename(file.getAbsolute(), renamed.getAbsolute(),
status... | @Test
public void testMove() throws Exception {
final Path workdir = new SFTPHomeDirectoryService(session).find();
final Path test = new SFTPTouchFeature(session).touch(new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)), new TransferStatus());
assertEquals(TransferSt... |
public static TrustManager[] trustManager(boolean needAuth, String trustCertPath) {
if (needAuth) {
try {
return trustCertPath == null ? null : buildSecureTrustManager(trustCertPath);
} catch (SSLException e) {
LOGGER.warn("degrade trust manager as build f... | @Test
void testTrustManagerSuccess() throws CertificateException {
URL url = SelfTrustManagerTest.class.getClassLoader().getResource("test-tls-cert.pem");
String path = url.getPath();
TrustManager[] actual = SelfTrustManager.trustManager(true, path);
assertNotNull(actual);
as... |
public String getSlotInfo() {
StringBuilder sb = new StringBuilder();
int index = this.index + 1;
for (int i = 0; i < slotCount; i++) {
if (i > 0) {
sb.append(' ');
}
sb.append(this.data[(i + index) % slotCount].get());
... | @Test
void testGetSlotInfo() {
SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000);
simpleFlowData.incrementAndGet();
simpleFlowData.incrementAndGet();
simpleFlowData.incrementAndGet();
assertEquals("0 0 0 0 3", simpleFlowData.getSlotInfo());
} |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
@Category(ValidatesRunner.class)
public void testMapSideInputWithNullValuesCatchesDuplicates() {
final PCollectionView<Map<String, Integer>> view =
pipeline
.apply(
"CreateSideInput",
Create.of(KV.of("a", (Integer) null), KV.of("a", (Integer) null))
... |
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LinkParameter {\n");
sb.append("}");
return sb.toString();
} | @Test
public void testToString() {
LinkParameter linkParameter = new LinkParameter();
linkParameter.setValue("foo");
Assert.assertEquals(linkParameter.toString(),
"class LinkParameter {\n}");
} |
@Operation(summary = "registerUser", description = "REGISTER_USER_NOTES")
@Parameters({
@Parameter(name = "userName", description = "USER_NAME", required = true, schema = @Schema(implementation = String.class)),
@Parameter(name = "userPassword", description = "USER_PASSWORD", required = true... | @Test
public void testRegisterUser() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("userName", "user_test");
paramsMap.add("userPassword", "123456qwe?");
paramsMap.add("repeatPassword", "123456qwe?");
paramsMap.add("em... |
private void fail(final ChannelHandlerContext ctx, int length) {
fail(ctx, String.valueOf(length));
} | @Test
public void testTooLongLine2AndEmitLastLine() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new LenientLineBasedFrameDecoder(16, false, false, true));
assertFalse(ch.writeInbound(copiedBuffer("12345678901234567", CharsetUtil.US_ASCII)));
try {
ch.writeInbound... |
@Override
public TListTableStatusResult listTableStatus(TGetTablesParams params) throws TException {
LOG.debug("get list table request: {}", params);
TListTableStatusResult result = new TListTableStatusResult();
List<TTableStatus> tablesResult = Lists.newArrayList();
result.setTables... | @Test
public void testListTableStatus() throws TException {
FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv);
TListTableStatusResult result = impl.listTableStatus(buildListTableStatusParam());
Assert.assertEquals(7, result.tables.size());
} |
@Override
public void monitor(RedisServer master) {
connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(),
master.getPort().intValue(), master.getQuorum().intValue());
} | @Test
public void testMonitor() {
Collection<RedisServer> masters = connection.masters();
RedisServer master = masters.iterator().next();
master.setName(master.getName() + ":");
connection.monitor(master);
} |
public static boolean isCarVin(CharSequence value) {
return isMatchRegex(CAR_VIN, value);
} | @Test
public void isCarVinTest() {
assertTrue(Validator.isCarVin("LSJA24U62JG269225"));
assertTrue(Validator.isCarVin("LDC613P23A1305189"));
assertFalse(Validator.isCarVin("LOC613P23A1305189"));
assertTrue(Validator.isCarVin("LSJA24U62JG269225")); //标准分类1
assertTrue(Validator.isCarVin("LDC613P23A1305189"... |
public abstract byte[] encode(MutableSpan input); | @Test void span_noRemoteServiceName_JSON_V2() {
clientSpan.remoteServiceName(null);
assertThat(new String(encoder.encode(clientSpan), UTF_8))
.isEqualTo(
"{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d50f68b\",\"kind\":\"CLIENT\",\"na... |
public static FromMatchesFilter create(Jid address) {
return new FromMatchesFilter(address, address != null ? address.hasNoResource() : false) ;
} | @Test
public void autoCompareMatchingBaseJid() {
FromMatchesFilter filter = FromMatchesFilter.create(BASE_JID1);
Stanza packet = StanzaBuilder.buildMessage().build();
packet.setFrom(BASE_JID1);
assertTrue(filter.accept(packet));
packet.setFrom(FULL_JID1_R1);
assertT... |
@Override
public boolean isAuthenticationRequired(SubjectConnectionReference conn) {
Subject subject = conn.getSubject();
if (subject.isAuthenticated()) {
//already authenticated:
return false;
}
//subject is not authenticated. Authentication is required by ... | @Test
public void testIsAuthenticationRequiredWhenSystemConnectionDoesNotRequireAuthenticationAndNotSystemAccount() {
Subject subject = new SubjectAdapter() {
@Override
public PrincipalCollection getPrincipals() {
return new SimplePrincipalCollection("foo", "iniRealm... |
public static <T> TypeSerializer<T> wrapIfNullIsNotSupported(
@Nonnull TypeSerializer<T> originalSerializer, boolean padNullValueIfFixedLen) {
return checkIfNullSupported(originalSerializer)
? originalSerializer
: wrap(originalSerializer, padNullValueIfFixedLen);
... | @Test
void testWrappingNeeded() {
assertThat(nullableSerializer)
.isInstanceOf(NullableSerializer.class)
.isEqualTo(
NullableSerializer.wrapIfNullIsNotSupported(
nullableSerializer, isPaddingNullValue()));
} |
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException {
final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest);
if (samlRequest instanceof AuthenticationRequest) {
dcMetadataResponseMapper.dcMetadataToAuthent... | @Test
public void resolveSamlRequestDcMetadataTest() throws DienstencatalogusException {
when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(stubDcResponse());
SamlRequest request = new ArtifactResolveRequest();
request.setConnectionEntityId(CONNECTION... |
public static String getProperty(String propertyName, String envName) {
return System.getenv().getOrDefault(envName, System.getProperty(propertyName));
} | @Test
void getProperty() {
System.setProperty("nacos.test", "google");
String property = PropertyUtils.getProperty("nacos.test", "xx");
assertEquals("google", property);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.