focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public RFuture<V> takeAsync() {
return commandExecutor.writeAsync(getRawName(), codec, RedisCommands.BLPOP_VALUE, getRawName(), 0);
} | @Test
public void testTakeAsyncCancel() {
Config config = createConfig();
config.useSingleServer().setConnectionMinimumIdleSize(1).setConnectionPoolSize(1);
RedissonClient redisson = Redisson.create(config);
RBlockingQueue<Integer> queue1 = getQueue(redisson);
for (int i = 0... |
protected static VplsOperation getOptimizedVplsOperation(Deque<VplsOperation> operations) {
if (operations.isEmpty()) {
return null;
}
// no need to optimize if the queue contains only one operation
if (operations.size() == 1) {
return operations.getFirst();
... | @Test
public void testOptimizeOperationsAToU() {
Deque<VplsOperation> operations = new ArrayDeque<>();
VplsData vplsData = VplsData.of(VPLS1);
vplsData.addInterfaces(ImmutableSet.of(V100H1));
VplsOperation vplsOperation = VplsOperation.of(vplsData,
... |
@Inject
public FragmentStatsProvider() {} | @Test
public void testFragmentStatsProvider()
{
FragmentStatsProvider fragmentStatsProvider = new FragmentStatsProvider();
QueryId queryId1 = new QueryId("queryid1");
QueryId queryId2 = new QueryId("queryid2");
PlanFragmentId planFragmentId1 = new PlanFragmentId(1);
PlanF... |
@Override
public int getUnstableBars() {
return surroundingHigherBars;
} | @Test
public void testGetUnstableBars_whenSetSurroundingBars_ReturnsSameValue() {
int surroundingBars = 2;
RecentSwingLowIndicator swingLowIndicator = new RecentSwingLowIndicator(series, surroundingBars);
assertEquals(surroundingBars, swingLowIndicator.getUnstableBars());
} |
public static <T> Collector<T, ?, Optional<T>> singleton() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.size() > 1) throw new IllegalArgumentException("More than one element");
return list.stream().findAny(... | @Test
public void singleton_collector_throws_when_multiple() {
List<String> items = List.of("foo1", "bar", "foo2");
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> items.stream().filter(s -> s.startsWith("foo")).collect(CustomCollectors.singlet... |
public static Object typeConvert(String tableName ,String columnName, String value, int sqlType, String mysqlType) {
if (value == null
|| (value.equals("") && !(isText(mysqlType) || sqlType == Types.CHAR || sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR))) {
return null;
... | @Test
public void typeConvertInputNotNullNotNullNotNullPositiveNotNullOutputPositive() {
// Arrange
final String tableName = "foo";
final String columnName = "foo";
final String value = "3";
final int sqlType = 4;
final String mysqlType = "foo";
// Act
final Object actual =
J... |
public void register(GracefulShutdownHook shutdownHook) {
if (isShuttingDown.get()) {
// Avoid any changes to the shutdown hooks set when the shutdown is already in progress
throw new IllegalStateException("Couldn't register shutdown hook because shutdown is already in progress");
... | @Test
public void withExceptionOnShutdown() throws Exception {
final AtomicBoolean hook1Called = new AtomicBoolean(false);
final AtomicBoolean hook2Called = new AtomicBoolean(false);
shutdownService.register(() -> hook1Called.set(true));
shutdownService.register(() -> { throw new Ex... |
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by(
PredicateT predicate) {
return new Filter<>(predicate);
} | @Test
@Category(NeedsRunner.class)
public void testNoFilterByPredicate() {
PCollection<Integer> output =
p.apply(Create.of(1, 2, 4, 5)).apply(Filter.by(new TrivialFn(false)));
PAssert.that(output).empty();
p.run();
} |
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.starts... | @Test
public void shouldReturnUnresolvedForTopicPrefixedStreamsConfig() {
final String prop = StreamsConfig.TOPIC_PREFIX + TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG;
assertThat(resolver.resolve(
KsqlConfig.KSQL_STREAMS_PREFIX + prop, true), is(unresolvedItem(prop)));
} |
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception {
LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation);
MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con... | @Test
public void shouldNotDefineATrackingToolWithoutARegex() {
CruiseConfig cruiseConfig = ConfigMigrator.load(ConfigFileFixture.ONE_PIPELINE);
PipelineConfig pipelineConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1"));
pipelineConfig.setTrackingTool(new Track... |
String getFileName(double lat, double lon) {
int lonInt = getMinLonForTile(lon);
int latInt = getMinLatForTile(lat);
return toLowerCase(getNorthString(latInt) + getPaddedLatString(latInt) + getEastString(lonInt) + getPaddedLonString(lonInt));
} | @Test
public void testGetFileName() {
assertEquals("n42e011", instance.getFileName(42.940339, 11.953125));
assertEquals("n38w078", instance.getFileName(38.548165, -77.167969));
assertEquals("n14w005", instance.getFileName(14.116047, -4.277344));
assertEquals("s52w058", instance.getFi... |
private static void handleRpcException(RpcException e, RetryContext context) {
// When enable_collect_query_detail_info is set to true, the plan will be recorded in the query detail,
// and hence there is no need to log it here.
ConnectContext connectContext = context.connectContext;
if ... | @Test
public void testHandleRpcException() throws Exception {
String sql = "select * from t0";
StatementBase statementBase = SqlParser.parse(sql, connectContext.getSessionVariable()).get(0);
ExecPlan execPlan = getExecPlan(sql);
ExecuteExceptionHandler.RetryContext retryContext =
... |
@Override
public void writeByteBuffer(ByteBuffer buf) {
try {
if (buf.hasArray()) {
out.write(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining());
} else {
byte[] bytes = Utils.toArray(buf);
out.write(bytes);
}... | @Test
public void testWritingSlicedByteBuffer() {
byte[] expectedArray = new byte[]{2, 3, 0, 0};
ByteBuffer sourceBuffer = ByteBuffer.wrap(new byte[]{0, 1, 2, 3});
ByteBuffer resultBuffer = ByteBuffer.allocate(4);
// Move position forward to ensure slice is not whole buffer
... |
@Override
public void handleGlobalFailure(final Throwable error) {
final long timestamp = System.currentTimeMillis();
setGlobalFailureCause(error, timestamp);
log.info("Trying to recover from a global failure.", error);
final FailureHandlingResult failureHandlingResult =
... | @Test
void handleGlobalFailureWithLocalFailure() {
final JobGraph jobGraph = singleJobVertexJobGraph(2);
final JobVertex onlyJobVertex = getOnlyJobVertex(jobGraph);
enableCheckpointing(jobGraph);
final DefaultScheduler scheduler = createSchedulerAndStartScheduling(jobGraph);
... |
TableViewBuilderImpl(PulsarClientImpl client, Schema<T> schema) {
this.client = client;
this.schema = schema;
this.conf = new TableViewConfigurationData();
} | @Test
public void testTableViewBuilderImpl() throws PulsarClientException {
TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME)
.autoUpdatePartitionsInterval(5, TimeUnit.SECONDS)
.subscriptionName("testSubscriptionName")
.cryptoKeyReader(mock(CryptoKeyReader.clas... |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
public void testMultimapCachedPartialEntry() {
final String tag = "multimap";
StateTag<MultimapState<byte[], Integer>> addr =
StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of());
MultimapState<byte[], Integer> multimapState = underTest.state(NAMESPACE, addr);
final byte[] key... |
@Override
public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context)
throws KeySourceException {
var jwksUrl = discoverJwksUrl();
try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) {
return jwkSetSource.getJWKSet(null... | @Test
void getJWKSet_success(WireMockRuntimeInfo wm) throws KeySourceException {
var kid = "test";
var jwks =
"""
{
"keys": [
{
"kty": "EC",
"use": "sig",
"crv": "P-256",
"kid": "%s",
"x": "PFjgWFHOCAtnw47F3bT99fmWOKcDARN45JGEPgB8yKs... |
public static SchemaKStream<?> buildSource(
final PlanBuildContext buildContext,
final DataSource dataSource,
final QueryContext.Stacker contextStacker
) {
final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed();
switch (dataSource.getDataSourceType()) {
case KST... | @Test
public void shouldReplaceTableSourceV1WithSame() {
// Given:
givenNonWindowedTable();
givenExistingQueryWithOldPseudoColumnVersion(tableSourceV1);
// When:
final SchemaKStream<?> result = SchemaKSourceFactory.buildSource(
buildContext,
dataSource,
contextStacker
... |
@Override
public void executor(final Collection<MetaDataRegisterDTO> metaDataRegisterDTOList) {
metaDataRegisterDTOList.forEach(meta -> Optional.ofNullable(this.shenyuClientRegisterService.get(meta.getRpcType()))
.ifPresent(shenyuClientRegisterService -> {
synchronized (s... | @Test
public void testExecutor() {
List<MetaDataRegisterDTO> list = new ArrayList<>();
metadataExecutorSubscriber.executor(list);
Assertions.assertTrue(list.isEmpty());
list.add(MetaDataRegisterDTO.builder().appName("test").build());
ShenyuClientRegisterService service = mock... |
@Override
public Short convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
} | @Test
void testConvert() {
assertEquals(Short.valueOf("1"), converter.convert("1"));
assertNull(converter.convert(null));
assertThrows(NumberFormatException.class, () -> {
converter.convert("ttt");
});
} |
public static String initNamespaceForNaming(NacosClientProperties properties) {
String tmpNamespace = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAME... | @Test
void testInitNamespaceFromPropNamespaceWithCloudParsing() {
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String expect = "ns1";
properties.setProperty(PropertyKeyConst.NAMESPACE, expect);
String ns = InitUtils.initNamespaceForNaming(propert... |
public boolean isJobCounter() {
return JOB_COUNTER_NAME.equals(name);
} | @Test
public void testJobCounter() {
assertFalse("jobCounter", new Counter("spring", null).isJobCounter());
assertTrue("jobCounter", new Counter("job", null).isJobCounter());
} |
public String getApplicationName() {
return getApplicationModel().getApplicationName();
} | @Test
void getApplicationName() {
ApplicationModel applicationModel = ApplicationModel.defaultModel();
String mockMetrics = "MockMetrics";
applicationModel
.getApplicationConfigManager()
.setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics... |
@Override
public CompletableFuture<DeleteGroupsResponseData.DeletableGroupResultCollection> deleteGroups(
RequestContext context,
List<String> groupIds,
BufferSupplier bufferSupplier
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(DeleteGroupsReque... | @Test
public void testDeleteGroups() throws Exception {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
mock... |
public static int getTypeOid(final String columnTypeName) {
Preconditions.checkArgument(COLUMN_TYPE_NAME_OID_MAP.containsKey(columnTypeName), "Cannot find PostgreSQL type oid for columnTypeName '%s'", columnTypeName);
return COLUMN_TYPE_NAME_OID_MAP.get(columnTypeName);
} | @Test
void assertGetTypeOidSuccess() {
assertThat(PostgreSQLArrayColumnType.getTypeOid("_int4"), is(1007));
} |
@Override
protected boolean isStepCompleted(@NonNull Context context) {
return SetupSupport.isThisKeyboardSetAsDefaultIME(context);
} | @Test
public void testKeyboardNotEnabled() {
WizardPageSwitchToKeyboardFragment fragment = startFragment();
Assert.assertFalse(fragment.isStepCompleted(getApplicationContext()));
ImageView stateIcon = fragment.getView().findViewById(R.id.step_state_icon);
Assert.assertNotNull(stateIcon);
Assert.... |
@GetMapping("/health")
@Secured(resource = Commons.NACOS_CORE_CONTEXT + "/cluster", action = ActionTypes.READ, signType = SignType.CONSOLE)
public RestResult<String> getHealth() {
return RestResultUtils.success(memberManager.getSelf().getState().name());
} | @Test
void testGetHealth() {
Member self = new Member();
self.setState(NodeState.UP);
Mockito.when(serverMemberManager.getSelf()).thenReturn(self);
RestResult<String> result = nacosClusterController.getHealth();
assertEquals(NodeState.UP.name(), result.getData());
... |
public static Write write() {
return new AutoValue_RedisIO_Write.Builder()
.setConnectionConfiguration(RedisConnectionConfiguration.create())
.setMethod(Write.Method.APPEND)
.build();
} | @Test
public void testWriteWithMethodSAdd() {
String key = "testWriteWithMethodSAdd";
List<String> values = Arrays.asList("0", "1", "2", "3", "2", "4", "0", "5");
List<KV<String, String>> data = buildConstantKeyList(key, values);
PCollection<KV<String, String>> write = p.apply(Create.of(data));
w... |
public String getMountedExternalStorageDirectoryPath() {
String path = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
path = getExternalStorageDirectoryPath();
}
return path... | @Test
public void getMountedExternalStorageDirectoryPathReturnsNullWhenNoFs() {
ShadowEnvironment.setExternalStorageState(Environment.MEDIA_NOFS);
assertThat(contextUtil.getMountedExternalStorageDirectoryPath(), is(nullValue()));
} |
@Nullable static String getPropertyIfString(Message message, String name) {
try {
Object o = message.getObjectProperty(name);
if (o instanceof String) return o.toString();
return null;
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting property {0} from message {1}"... | @Test void getPropertyIfString_notString() throws Exception {
message.setByteProperty("b3", (byte) 0);
assertThat(MessageProperties.getPropertyIfString(message, "b3"))
.isNull();
} |
@Override
protected List<SegmentConversionResult> convert(PinotTaskConfig pinotTaskConfig, List<File> segmentDirs,
File workingDir)
throws Exception {
int numInputSegments = segmentDirs.size();
_eventObserver.notifyProgress(pinotTaskConfig, "Converting segments: " + numInputSegments);
String t... | @Test
public void testRollupWithTimeTransformation()
throws Exception {
FileUtils.deleteQuietly(WORKING_DIR);
RealtimeToOfflineSegmentsTaskExecutor realtimeToOfflineSegmentsTaskExecutor =
new RealtimeToOfflineSegmentsTaskExecutor(null, null);
realtimeToOfflineSegmentsTaskExecutor.setMinionE... |
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> stream,
final StreamSelect<K> step,
final RuntimeBuildContext buildContext
) {
final QueryContext queryContext = step.getProperties().getQueryContext();
final LogicalSchema sourceSchema = stream.getSchema();
final Optional... | @Test
public void shouldReturnResultKStream() {
// When:
final KStreamHolder<Struct> result = step.build(planBuilder, planInfo);
// Then:
assertThat(result.getStream(), is(resultKStream));
assertThat(result.getExecutionKeyFactory(), is(executionKeyFactory));
} |
public static int dot(int[] a, int[] b) {
int sum = 0;
for (int p1 = 0, p2 = 0; p1 < a.length && p2 < b.length; ) {
int i1 = a[p1];
int i2 = b[p2];
if (i1 == i2) {
sum++;
p1++;
p2++;
} else if (i1 > i2) {
... | @Test
public void testDot_doubleArr_doubleArr() {
System.out.println("dot");
double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300};
assertEquals(3.350726, MathEx.dot(x, y), 1E-6);
} |
@Override
public void start() {
try {
forceMkdir(downloadDir);
for (File tempFile : listTempFile(this.downloadDir)) {
deleteQuietly(tempFile);
}
} catch (IOException e) {
throw new IllegalStateException("Fail to create the directory: " + downloadDir, e);
}
} | @Test
public void throw_exception_if_download_dir_is_invalid() throws Exception {
ServerFileSystem fs = mock(ServerFileSystem.class);
// download dir is a file instead of being a directory
File downloadDir = testFolder.newFile();
when(fs.getDownloadedPluginsDir()).thenReturn(downloadDir);
pluginD... |
public static ServiceInfo fromKey(final String key) {
return new ServiceInfo(key);
} | @Test
void testFromKey() {
String key1 = "group@@name";
String key2 = "group@@name@@c2";
ServiceInfo s1 = ServiceInfo.fromKey(key1);
ServiceInfo s2 = ServiceInfo.fromKey(key2);
assertEquals(key1, s1.getKey());
assertEquals(key2, s2.getKey());
} |
@VisibleForTesting
List<String> parseTemplateContentParams(String content) {
return ReUtil.findAllGroup1(PATTERN_PARAMS, content);
} | @Test
public void testParseTemplateContentParams() {
// 准备参数
String content = "正在进行登录操作{operation},您的验证码是{code}";
// mock 方法
// 调用
List<String> params = smsTemplateService.parseTemplateContentParams(content);
// 断言
assertEquals(Lists.newArrayList("operation",... |
public synchronized void recoverNumaResource(ContainerId containerId) {
Container container = context.getContainers().get(containerId);
ResourceMappings resourceMappings = container.getResourceMappings();
List<Serializable> assignedResources = resourceMappings
.getAssignedResources(NUMA_RESOURCE_TYP... | @Test
public void testRecoverNumaResource() throws Exception {
@SuppressWarnings("unchecked")
ConcurrentHashMap<ContainerId, Container> mockContainers = mock(
ConcurrentHashMap.class);
Context mockContext = mock(Context.class);
Container mockContainer = mock(Container.class);
ResourceMappi... |
@Override
public final void unsubscribe(URL url, NotifyListener listener) {
if (!shouldSubscribe(url)) { // Should Not Subscribe
return;
}
url = addRegistryClusterKey(url);
doUnsubscribe(url, listener);
} | @Test
void testUnsubscribe() {
// do subscribe to prepare for unsubscribe verification
Set<String> multiApps = new TreeSet<>();
multiApps.add(APP_NAME1);
multiApps.add(APP_NAME2);
NotifyListener testServiceListener2 = mock(NotifyListener.class);
URL url2 = URL.valueOf... |
@Override
public boolean supportsOuterJoins() {
return false;
} | @Test
void assertSupportsOuterJoins() {
assertFalse(metaData.supportsOuterJoins());
} |
@Override
public String filterType() {
return ZuulConstant.ERROR_TYPE;
} | @Test
public void testFilterType() throws Exception {
SentinelZuulErrorFilter sentinelZuulErrorFilter = new SentinelZuulErrorFilter();
Assert.assertEquals(sentinelZuulErrorFilter.filterType(), ERROR_TYPE);
} |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.precision(column.getColumnLength())
.length(column.getColumn... | @Test
public void testReconvertDouble() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.DOUBLE_TYPE).build();
BasicTypeDefine typeDefine = IrisTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName())... |
@Override
public final void getSize(@NonNull SizeReadyCallback cb) {
sizeDeterminer.getSize(cb);
} | @Test
public void testSizeCallbacksAreCalledInOrderPreDraw() {
SizeReadyCallback[] cbs = new SizeReadyCallback[25];
for (int i = 0; i < cbs.length; i++) {
cbs[i] = mock(SizeReadyCallback.class);
target.getSize(cbs[i]);
}
int width = 100;
int height = 111;
parent.getLayoutParams().... |
@Override
public String toString() {
return String.format("%s,%s,%s", getType(), null == beginValue ? "" : beginValue, null == endValue ? "" : endValue);
} | @Test
void assertToString() {
assertThat(new StringPrimaryKeyIngestPosition("hi", "jk").toString(), is("s,hi,jk"));
} |
@Override
protected String getKeyName() {
return RateLimitEnum.SLIDING_WINDOW.getKeyName();
} | @Test
public void getKeyNameTest() {
MatcherAssert.assertThat("sliding_window_request_rate_limiter", is(slidingWindowRateLimiterAlgorithm.getKeyName()));
} |
public static <K, V> StoreBuilder<SessionStore<K, V>> sessionStoreBuilder(final SessionBytesStoreSupplier supplier,
final Serde<K> keySerde,
final Serde<V> valueSer... | @Test
public void shouldThrowIfSupplierIsNullForSessionStoreBuilder() {
final Exception e = assertThrows(NullPointerException.class, () -> Stores.sessionStoreBuilder(null, Serdes.ByteArray(), Serdes.ByteArray()));
assertEquals("supplier cannot be null", e.getMessage());
} |
public static Map<String, String> parseContentTypeParams(String mimeType) {
List<String> items = StringUtils.split(mimeType, ';', false);
int count = items.size();
if (count <= 1) {
return null;
}
Map<String, String> map = new LinkedHashMap<>(count - 1);
for (... | @Test
void testParseContentTypeParams() {
Map<String, String> map = HttpUtils.parseContentTypeParams("application/json");
assertNull(map);
map = HttpUtils.parseContentTypeParams("application/json; charset=UTF-8");
match(map, "{ charset: 'UTF-8' }");
map = HttpUtils.parseConte... |
@Override
public Matrix toMatrix() {
return Matrix.of(graph);
} | @Test
public void testToMatrix() {
System.out.println("toMatrix digraph = false");
AdjacencyMatrix graph = new AdjacencyMatrix(8, false);
graph.addEdge(0, 2);
graph.addEdge(1, 7);
graph.addEdge(2, 6);
graph.addEdge(7, 4);
graph.addEdge(3, 4);
graph.ad... |
public Node chooseRandomWithStorageType(final String scope,
final Collection<Node> excludedNodes, StorageType type) {
netlock.readLock().lock();
try {
if (scope.startsWith("~")) {
return chooseRandomWithStorageType(
NodeBase.ROOT, scope.substring(1), excludedNodes, type);
}... | @Test
public void testChooseRandomWithStorageTypeWrapper() throws Exception {
Node n;
DatanodeDescriptor dd;
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r4", null, null,
StorageType.ARCHIVE);
HashSet<Node> excluded = new HashSet<>();
// exclude the host on r4 (since there is only one h... |
@Operation(summary = "Read the answers of the 3 apdus and read the pip/pp to send to digid x")
@PostMapping(value = Constants.URL_NIK_POLYMORPHICDATA, consumes = "application/json", produces = "application/json")
public PolyDataResponse getPolymorphicDataRestService(@Valid @RequestBody NikApduResponsesRequest r... | @Test
public void getPolymorphicDataRestServiceTest() {
PolyDataResponse expectedResponse = new PolyDataResponse();
when(nikServiceMock.getPolymorphicDataRestService(any(NikApduResponsesRequest.class))).thenReturn(expectedResponse);
PolyDataResponse actualResponse = nikController.getPolymor... |
public static void main(String[] args) {
// eagerly initialized singleton
var ivoryTower1 = IvoryTower.getInstance();
var ivoryTower2 = IvoryTower.getInstance();
LOGGER.info("ivoryTower1={}", ivoryTower1);
LOGGER.info("ivoryTower2={}", ivoryTower2);
// lazily initialized singleton
var thre... | @Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldAllowPortOmissionForRemoteEnvironmentStreaming() {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(FlinkRunner.class);
options.setFlinkMaster("host");
StreamExecutionEnvironment sev =
FlinkExecutionEnvironments.createStreamExecutionEnviron... |
@Override
public AppResponse process(Flow flow, MijnDigidSessionRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException, SharedServiceClientException {
appSession = appSessionService.getSession(request.getMijnDigidSessionId());
appAuthenticator = appAuthenticatorServic... | @Test
public void getEmptyListNotificationsTest() throws FlowNotDefinedException, SharedServiceClientException, IOException, NoSuchAlgorithmException {
//given
when(appSessionService.getSession(any())).thenReturn(mockedAppSession);
when(appAuthenticatorService.findByUserAppId(any())).thenRet... |
@Override
public void metricChange(final KafkaMetric metric) {
if (!THROUGHPUT_METRIC_NAMES.contains(metric.metricName().name())
|| !StreamsMetricsImpl.TOPIC_LEVEL_GROUP.equals(metric.metricName().group())) {
return;
}
addMetric(
metric,
getQueryId(metric),
getTopic... | @Test
public void shouldThrowWhenTopicNameTagIsMissing() {
// When:
assertThrows(
KsqlException.class,
() -> listener.metricChange(mockMetric(
BYTES_CONSUMED_TOTAL,
2D,
ImmutableMap.of(
"thread-id", THREAD_ID,
"task-id", TASK_ID_1,
"processor-n... |
@Override
public Map<String, String> getEnvironments() {
return ConfigurationUtils.getPrefixedKeyValuePairs(
ResourceManagerOptions.CONTAINERIZED_MASTER_ENV_PREFIX, flinkConfig);
} | @Test
void testGetEnvironments() {
final Map<String, String> expectedEnvironments = new HashMap<>();
expectedEnvironments.put("k1", "v1");
expectedEnvironments.put("k2", "v2");
expectedEnvironments.forEach(
(k, v) ->
flinkConfig.setString(
... |
@Override
public void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) {
int payloadLength = in.markReaderIndex().readUnsignedMediumLE();
int remainPayloadLength = SEQUENCE_LENGTH + payloadLength;
if (in.readableBytes() < remainPayloadLength) {
... | @Test
void assertDecodeWithEmptyPacket() {
when(byteBuf.markReaderIndex()).thenReturn(byteBuf);
when(byteBuf.readableBytes()).thenReturn(1);
when(byteBuf.readUnsignedMediumLE()).thenReturn(0);
List<Object> out = new LinkedList<>();
new MySQLPacketCodecEngine().decode(context,... |
@Override
public void onServerStart(Server server) {
if (!done) {
initCe();
this.done = true;
}
} | @Test
public void onServerStart_has_no_effect_if_called_twice_to_support_medium_test_doing_startup_tasks_multiple_times() {
underTest.onServerStart(server);
reset(processingScheduler, cleaningScheduler);
underTest.onServerStart(server);
verifyNoInteractions(processingScheduler, cleaningScheduler);
... |
public Future<Void> closeAsync() {
// Execute close asynchronously in case this is being invoked on an eventloop to avoid blocking
return GlobalEventExecutor.INSTANCE.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
close();
... | @Test
public void testCloseAsync() throws Exception {
final LocalAddress addr = new LocalAddress(getLocalAddrId());
final EventLoopGroup group = new DefaultEventLoopGroup();
// Start server
final ServerBootstrap sb = new ServerBootstrap()
.group(group)
... |
@Override
public void init(final InternalProcessorContext<KIn, VIn> context) {
// It is important to first create the sensor before calling init on the
// parent object. Otherwise due to backwards compatibility an empty sensor
// without parent is created with the same name.
// Once ... | @Test
public void shouldThrowStreamsExceptionWithExplicitErrorMessage() {
final InternalMockProcessorContext<String, String> context = new InternalMockProcessorContext<>();
final SourceNode<String, String> node =
new SourceNode<>(context.currentNode().name(), new TheDeserializer(), new ... |
@Override
public void checkBeforeUpdate(final CreateReadwriteSplittingRuleStatement sqlStatement) {
ReadwriteSplittingRuleStatementChecker.checkCreation(database, sqlStatement.getRules(), null == rule ? null : rule.getConfiguration(), sqlStatement.isIfNotExists());
} | @Test
void assertCheckSQLStatementWithDuplicateLogicResource() {
DataSourceMapperRuleAttribute ruleAttribute = mock(DataSourceMapperRuleAttribute.class);
when(ruleAttribute.getDataSourceMapper()).thenReturn(Collections.singletonMap("duplicate_ds", Collections.singleton("ds_0")));
when(databa... |
@Override
public StringResourceVersion exists(String key) throws Exception {
checkNotNull(key, "Key in ConfigMap.");
return kubeClient
.getConfigMap(configMapName)
.map(
configMap -> {
final String content = configM... | @Test
void testExistsWithDeletingEntry() throws Exception {
new Context() {
{
runTest(
() -> {
leaderCallbackGrantLeadership();
final TestingLongStateHandleHelper.LongStateHandle state =
... |
@Override
public void write(final MySQLPacketPayload payload, final Object value) {
if (value instanceof BigDecimal) {
payload.writeInt8(((BigDecimal) value).longValue());
} else if (value instanceof Integer) {
payload.writeInt8(((Integer) value).longValue());
} else ... | @Test
void assertWriteWithBigDecimal() {
new MySQLInt8BinaryProtocolValue().write(payload, new BigDecimal(1L));
verify(payload).writeInt8(1L);
} |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void tableAnonymousStoreTypedMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.table("input-topic")
.groupBy((key, value) -> null)
.count(Materialized.as(Materialized.StoreType.IN_MEMORY));
f... |
@GetMapping("/task/resend-failed-messages")
@Operation(summary = "Resend all failed messages")
public void resend() {
afnemersindicatieService.resendUnsentMessages();
} | @Test
void testResend(){
when(afnemersbericht.getType()).thenReturn(Afnemersbericht.Type.Ap01);
List<Afnemersbericht> afnemersberichten = Arrays.asList(afnemersbericht);
when(afnemersberichtRepository.findByStatus(Afnemersbericht.Status.SEND_FAILED)).thenReturn(afnemersberichten);
c... |
public static Configuration getTimelineServiceHBaseConf(Configuration conf)
throws IOException {
if (conf == null) {
throw new NullPointerException();
}
Configuration hbaseConf;
String timelineServiceHBaseConfFilePath =
conf.get(YarnConfiguration.TIMELINE_SERVICE_HBASE_CONFIGURATION... | @Test
void testWithHbaseConfAtHdfsFileSystem() throws IOException {
MiniDFSCluster hdfsCluster = null;
try {
HdfsConfiguration hdfsConfig = new HdfsConfiguration();
hdfsCluster = new MiniDFSCluster.Builder(hdfsConfig)
.numDataNodes(1).build();
FileSystem fs = hdfsCluster.getFileSy... |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionsMap) {
if (!ValidationUtils.isHdfsScheme(mPath)) {
mMsg.append(String.format(
"UFS path %s is not HDFS. Skipping validation for HDFS properties.%n", mPath));
return new ValidationTaskResult(ValidationUtils.Stat... | @Test
public void validConf() {
String hdfsSite = Paths.get(sTestDir.toPath().toString(), "hdfs-site.xml").toString();
ValidationTestUtils.writeXML(hdfsSite, ImmutableMap.of("key1", "value1", "key3", "value3"));
String coreSite = Paths.get(sTestDir.toPath().toString(), "core-site.xml").toString();
Va... |
@ConstantFunction.List(list = {
@ConstantFunction(name = "date_trunc", argTypes = {VARCHAR, DATETIME}, returnType = DATETIME, isMonotonic = true),
@ConstantFunction(name = "date_trunc", argTypes = {VARCHAR, DATE}, returnType = DATE, isMonotonic = true)
})
public static ConstantOperator d... | @Test
public void dateTrunc() {
String[][] testCases = {
{"second", "2015-03-23 09:23:55", "2015-03-23T09:23:55"},
{"minute", "2015-03-23 09:23:55", "2015-03-23T09:23"},
{"hour", "2015-03-23 09:23:55", "2015-03-23T09:00"},
{"day", "2015-03-23 0... |
public synchronized boolean saveNamespace(long timeWindow, long txGap,
FSNamesystem source) throws IOException {
if (timeWindow > 0 || txGap > 0) {
final FSImageStorageInspector inspector = storage.readAndInspectDirs(
EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK),
Start... | @Test
public void testHasNonEcBlockUsingStripedIDForLoadSnapshot()
throws IOException{
// start a cluster
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(9)
.build();
cluster.waitActi... |
public static org.apache.iceberg.Table loadIcebergTable(SparkSession spark, String name)
throws ParseException, NoSuchTableException {
CatalogAndIdentifier catalogAndIdentifier = catalogAndIdentifier(spark, name);
TableCatalog catalog = asTableCatalog(catalogAndIdentifier.catalog);
Table sparkTable =... | @Test
public void testLoadIcebergTable() throws Exception {
spark.conf().set("spark.sql.catalog.hive", SparkCatalog.class.getName());
spark.conf().set("spark.sql.catalog.hive.type", "hive");
spark.conf().set("spark.sql.catalog.hive.default-namespace", "default");
String tableFullName = "hive.default.... |
@VisibleForTesting
Collection<String> getVolumesLowOnSpace() throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Going to check the following volumes disk space: " + volumes);
}
Collection<String> lowVolumes = new ArrayList<String>();
for (CheckedVolume volume : volumes.values()) {
... | @Test
public void testCheckingExtraVolumes() throws IOException {
Configuration conf = new Configuration();
File nameDir = new File(BASE_DIR, "name-dir");
nameDir.mkdirs();
conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, nameDir.getAbsolutePath());
conf.set(DFSConfigKeys.DFS_NAMENODE_CHECKED_VO... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testGgNewPb()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Fight duration: <col=ff0000>1:36</col> (new personal best)", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your Grotesque Guardians kill count is:... |
String[] cleanFilters( String[] filters ) {
return !ArrayUtils.isEmpty( filters )
? Arrays.asList( filters ).stream().filter( f -> !StringUtils.isBlank( f ) ).toArray( String[]::new )
: null;
} | @Test
public void testCleanFilters() {
String[] EMPTY_ARRAY = new String[]{};
assertNull( testInstance.cleanFilters( null ) );
assertNull( testInstance.cleanFilters( new String[]{} ) );
assertArrayEquals( EMPTY_ARRAY, testInstance.cleanFilters( new String[]{ null } ) );
assertArrayEquals( EMP... |
@Override
public int size() {
return contents.size();
} | @Test
public void testGetSetByType2() throws HCatException {
HCatRecord inpRec = getGetSet2InpRec();
HCatRecord newRec = new DefaultHCatRecord(inpRec.size());
HCatSchema hsch =
HCatSchemaUtils.getHCatSchema("a:binary,b:map<string,string>,c:array<int>,d:struct<i:int>");
newRec.setByteArray("... |
@Override
public void doUnregister(URL url) {
try {
checkDestroyed();
zkClient.delete(toUrlPath(url));
} catch (Throwable e) {
throw new RpcException(
"Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e... | @Test
void testDoUnregisterWithException() {
Assertions.assertThrows(RpcException.class, () -> {
URL errorUrl = URL.valueOf("multicast://0.0.0.0/");
zookeeperRegistry.doUnregister(errorUrl);
});
} |
public final void doesNotContainKey(@Nullable Object key) {
check("keySet()").that(checkNotNull(actual).keySet()).doesNotContain(key);
} | @Test
public void doesNotContainKey() {
ImmutableMultimap<String, String> multimap = ImmutableMultimap.of("kurt", "kluever");
assertThat(multimap).doesNotContainKey("daniel");
assertThat(multimap).doesNotContainKey(null);
} |
@Udf(description = "Returns the inverse (arc) tangent of an INT value")
public Double atan(
@UdfParameter(
value = "value",
description = "The value to get the inverse tangent of."
) final Integer value
) {
return atan(value == null ? null : value.doubleVa... | @Test
public void shouldHandlePositive() {
assertThat(udf.atan(0.43), closeTo(0.40609805831761564, 0.000000000000001));
assertThat(udf.atan(0.5), closeTo(0.4636476090008061, 0.000000000000001));
assertThat(udf.atan(1.0), closeTo(0.7853981633974483, 0.000000000000001));
assertThat(udf.atan(1), closeTo(... |
@Override
public void close() {
close(Duration.ofMillis(0));
} | @Test
public void shouldThrowOnFlushProducerIfProducerIsClosed() {
buildMockProducer(true);
producer.close();
assertThrows(IllegalStateException.class, producer::flush);
} |
@Override
public int addListener(ObjectListener listener) {
if (listener instanceof StreamAddListener) {
return addListener("__keyevent@*:xadd", (StreamAddListener) listener, StreamAddListener::onAdd);
}
if (listener instanceof StreamRemoveListener) {
return addListen... | @Test
public void testAddListener() {
testWithParams(redisson -> {
RStream<String, String> ss = redisson.getStream("test");
ss.createGroup(StreamCreateGroupArgs.name("test-group").makeStream());
CountDownLatch latch = new CountDownLatch(1);
ss.addListener(new ... |
@Override
public Revision checkpoint(String noteId,
String notePath,
String commitMessage,
AuthenticationInfo subject) throws IOException {
Revision revision = super.checkpoint(noteId, notePath, commitMessage, subject);
up... | @Test
/**
* Test the case when the check-pointing (add new files and commit) it pushes the local commits to the remote
* repository
*/
void pushLocalChangesToRemoteRepositoryOnCheckpointing() throws IOException, GitAPIException {
// Add a new paragraph to the local repository
addParagraphToNotebook... |
@Override
public Statement createStatement()
throws SQLException {
validateState();
return new PinotStatement(this);
} | @Test
public void unsetUserAgentTest()
throws Exception {
DummyPinotControllerTransport userAgentPinotControllerTransport = DummyPinotControllerTransport
.create(null);
PinotConnection pinotConnection =
new PinotConnection("dummy", _dummyPinotClientTransport, "dummy", userAgentPinotCont... |
public Properties getProperties() {
return properties;
} | @Test
public void testApplicationProperties() {
assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.app.props.no"));
assertEquals("true", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.app.props"));
} |
public Filter parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) {
if (!filterExpression.contains(FIELD_AND_VALUE_SEPARATOR)) {
throw new IllegalArgumentException(WRONG_FILTER_EXPR_FORMAT_ERROR_MSG);
}
final String[] split = filterExpression.... | @Test
void parsesFilterExpressionCorrectlyForDateType() {
assertEquals(new SingleValueFilter("created_at", new DateTime(2012, 12, 12, 12, 12, 12, DateTimeZone.UTC).toDate()),
toTest.parseSingleExpression("created_at:2012-12-12 12:12:12",
List.of(EntityAttribute.build... |
public void isInOrder() {
isInOrder(Ordering.natural());
} | @Test
public void isInOrderMultipleFailures() {
expectFailureWhenTestingThat(asList(1, 3, 2, 4, 0)).isInOrder();
} |
public static Field getField(Class<?> clazz, String fieldName) {
return internalGetField(clazz.getCanonicalName(), clazz, fieldName);
} | @Test
public void getFieldTest() {
assertThat(getField(Person.class, "firstName")).isNotNull();
assertThat(getField(SubPerson.class, "firstName")).isNotNull();
assertThat(getField(SubPerson.class, "additionalField")).isNotNull();
assertThatThrownBy(() -> getField(Person.class, "notEx... |
public static Builder builder(
String projectId, String location, CredentialsProvider credentialsProvider) {
checkArgument(!Strings.isNullOrEmpty(projectId), "projectID can not be null or empty");
checkArgument(!Strings.isNullOrEmpty(location), "location can not be null or empty");
return new Builder(... | @Test
public void testBuilderWithInvalidLocationShouldFail() {
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class,
() -> DatastreamResourceManager.builder(PROJECT_ID, "", null));
assertThat(exception).hasMessageThat().contains("location can not be... |
@Override
public Collection<ScoredEntry<V>> entryRangeReversed(int startIndex, int endIndex) {
return get(entryRangeReversedAsync(startIndex, endIndex));
} | @Test
public void testEntryRangeReversed() {
RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple");
set.add(10, 1);
set.add(20, 2);
set.add(30, 3);
set.add(40, 4);
set.add(50, 5);
Collection<ScoredEntry<Integer>> vals = set.entryRangeReversed(... |
@Override
public Collection<RedisServer> masters() {
List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS);
return toRedisServersList(masters);
} | @Test
public void testMasters() {
Collection<RedisServer> masters = connection.masters();
assertThat(masters).hasSize(1);
} |
@Override
public synchronized boolean tryReturnRecordAt(
boolean isAtSplitPoint, @Nullable ShufflePosition groupStart) {
if (lastGroupStart == null && !isAtSplitPoint) {
throw new IllegalStateException(
String.format("The first group [at %s] must be at a split point", groupStart.toString()))... | @Test
public void testTryReturnNonMonotonic() throws Exception {
GroupingShuffleRangeTracker tracker =
new GroupingShuffleRangeTracker(ofBytes(3, 0, 0), ofBytes(5, 0, 0));
tracker.tryReturnRecordAt(true, ofBytes(3, 4, 5));
tracker.tryReturnRecordAt(true, ofBytes(3, 4, 6));
expected.expect(Ille... |
@VisibleForTesting
public void validateDictTypeExists(String type) {
DictTypeDO dictType = dictTypeService.getDictType(type);
if (dictType == null) {
throw exception(DICT_TYPE_NOT_EXISTS);
}
if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) {
... | @Test
public void testValidateDictTypeExists_notExists() {
assertServiceException(() -> dictDataService.validateDictTypeExists(randomString()), DICT_TYPE_NOT_EXISTS);
} |
void onAddRcvDestination(final long registrationId, final String destinationChannel, final long correlationId)
{
if (destinationChannel.startsWith(IPC_CHANNEL))
{
onAddRcvIpcDestination(registrationId, destinationChannel, correlationId);
}
else if (destinationChannel.star... | @Test
void shouldThrowExceptionWhenRcvDestinationHasControlModeResponseSet()
{
final Exception exception = assertThrowsExactly(InvalidChannelException.class,
() -> driverConductor.onAddRcvDestination(5, "aeron:udp?control-mode=response", 7)
);
assertEquals(
"ERRO... |
public static Optional<Throwable> findThrowableInChain(Predicate<Throwable> condition, @Nullable Throwable t) {
final Set<Throwable> seen = new HashSet<>();
while (t != null && !seen.contains(t)) {
if (condition.test(t)) {
return Optional.of(t);
}
seen... | @Test
void findsSimpleException() {
final RuntimeException e = new RuntimeException();
assertThat(findThrowableInChain(t -> t instanceof RuntimeException, e)).contains(e);
assertThat(findThrowableInChain(t -> false, e)).isEmpty();
} |
@Override
public int division(int n1, int n2) throws Exception {
int n5 = n1 / n2;
return n5;
} | @Test(expected = Exception.class)
public void testDivisionByZero() throws Exception {
Controlador controlador = new Controlador();
controlador.division(5, 0);
} |
public static <T> AsIterable<T> asIterable() {
return new AsIterable<>();
} | @Test
@Category(ValidatesRunner.class)
public void testSideInputWithNestedIterables() {
final PCollectionView<Iterable<Integer>> view1 =
pipeline
.apply("CreateVoid1", Create.of((Void) null).withCoder(VoidCoder.of()))
.apply(
"OutputOneInteger",
Pa... |
@Override
public List<ImportValidationFeedback> verifyRule( Object subject ) {
List<ImportValidationFeedback> feedback = new ArrayList<>();
if ( !isEnabled() || !( subject instanceof TransMeta ) ) {
return feedback;
}
TransMeta transMeta = (TransMeta) subject;
String description = transMe... | @Test
public void testVerifyRule_EmptyDescription_EnabledRule() {
TransformationHasDescriptionImportRule importRule = getImportRule( 10, true );
TransMeta transMeta = new TransMeta();
transMeta.setDescription( "" );
List<ImportValidationFeedback> feedbackList = importRule.verifyRule( transMeta );
... |
public static boolean isEligibleForCarbonsDelivery(final Message stanza)
{
// To properly handle messages exchanged with a MUC (or similar service), the server must be able to identify MUC-related messages.
// This can be accomplished by tracking the clients' presence in MUCs, or by checking for the... | @Test
public void testMucGroupChat() throws Exception
{
// Setup test fixture.
final Message input = new Message();
input.setType(Message.Type.groupchat);
// Execute system under test.
final boolean result = Forwarded.isEligibleForCarbonsDelivery(input);
// Veri... |
@Override
public List<SyntheticBoundedSource> split(long desiredBundleSizeBytes, PipelineOptions options)
throws Exception {
// Choose number of bundles either based on explicit parameter,
// or based on size and hints.
int desiredNumBundles =
(sourceOptions.forceNumInitialBundles == null)
... | @Test
public void testSplitIntoBundles() throws Exception {
testSplitIntoBundlesP(1);
testSplitIntoBundlesP(-1);
testSplitIntoBundlesP(5);
PipelineOptions options = PipelineOptionsFactory.create();
testSourceOptions.forceNumInitialBundles = 37;
assertEquals(37, new SyntheticBoundedSource(test... |
@GetMapping("/{id}")
@RequiresPermissions("system:dict:edit")
public ShenyuAdminResult detail(@PathVariable("id") @Valid
@Existed(provider = ShenyuDictMapper.class,
message = "dict is not existed") final String id) {
return ... | @Test
public void testDetail() throws Exception {
given(this.shenyuDictService.findById("123")).willReturn(shenyuDictVO);
this.mockMvc.perform(MockMvcRequestBuilders.get("/shenyu-dict/{id}", "123"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(Sheny... |
private Object convertCharset(Object content, Charset contentCharset, Charset destinationCharset, boolean outputAsString) {
byte[] bytes = StandardConversions.convertCharset(content, contentCharset, destinationCharset);
return outputAsString ? new String(bytes, destinationCharset) : bytes;
} | @Test
public void testCharset() {
Charset korean = Charset.forName("EUC-KR");
MediaType textPlainKorean = TEXT_PLAIN.withCharset(korean);
MediaType jsonKorean = APPLICATION_JSON.withCharset(korean);
MediaType textPlainAsString = TEXT_PLAIN.withClassType(String.class);
MediaType jsonAsSt... |
public DMNContext populateContextWith(Map<String, Object> json) {
for (Entry<String, Object> kv : json.entrySet()) {
InputDataNode idn = model.getInputByName(kv.getKey());
if (idn != null) {
processInputDataNode(kv, idn);
} else {
DecisionNode ... | @Test
void trafficViolationAll() throws Exception {
final DMNRuntime runtime = createRuntimeWithAdditionalResources("Traffic Violation.dmn", DMNRuntimeTypesTest.class);
final DMNModel dmnModel = runtime.getModel("https://github.com/kiegroup/drools/kie-dmn/_A4BCA8B8-CF08-433F-93B2-A2598F19ECFF", "Tra... |
Future<RecordMetadata> send(final ProducerRecord<byte[], byte[]> record,
final Callback callback) {
maybeBeginTransaction();
try {
return producer.send(record, callback);
} catch (final KafkaException uncaughtException) {
if (isRecoverable(... | @Test
public void shouldFailOnMaybeBeginTransactionIfTransactionsNotInitializedForExactlyOnceBeta() {
final StreamsProducer streamsProducer =
new StreamsProducer(
eosBetaConfig,
"threadId-StreamThread-0",
eosBetaMockClientSupplier,
... |
public static boolean typeIsTransitivelyDependent(HollowStateEngine stateEngine, String dependentType, String dependencyType) {
if(dependentType.equals(dependencyType))
return true;
HollowSchema dependentTypeSchema = stateEngine.getSchema(dependentType);
if(dependen... | @Test
public void determinesIfSchemasAreTransitivelyDependent() throws IOException {
String schemasText = "TypeA { TypeB b; }"
+ "TypeB { TypeC c; }"
+ "TypeC { TypeD d; }";
List<HollowSchema> schemas = HollowSchemaParser.parseCollection... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.