focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public CompletionStage<V> getAsync(K key) {
return cache.getAsync(key);
} | @Test
public void testGetAsync() throws Exception {
cache.put(42, "foobar");
Future<String> future = adapter.getAsync(42).toCompletableFuture();
String result = future.get();
assertEquals("foobar", result);
} |
private static boolean canSatisfyConstraints(ApplicationId appId,
PlacementConstraint constraint, SchedulerNode node,
AllocationTagsManager atm,
Optional<DiagnosticsCollector> dcOpt)
throws InvalidAllocationTagsQueryException {
if (constraint == null) {
LOG.debug("Constraint is found e... | @Test
public void testInvalidAllocationTagNamespace() {
AllocationTagsManager tm = new AllocationTagsManager(rmContext);
PlacementConstraintManagerService pcm =
new MemoryPlacementConstraintManager();
rmContext.setAllocationTagsManager(tm);
rmContext.setPlacementConstraintManager(pcm);
lo... |
public String getShare() {
return share;
} | @Test
void shareForDoubleSlashURIPathShouldBeExtracted() {
// relaxed handling, it could be rejected if we wanted to be strict
var remoteConf = context.getEndpoint("azure-files://account//share/", FilesEndpoint.class).getConfiguration();
assertEquals("share", remoteConf.getShare());
} |
@Override
public Long sendSingleNotifyToAdmin(Long userId, String templateCode, Map<String, Object> templateParams) {
return sendSingleNotify(userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams);
} | @Test
public void testSendSingleNotifyToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// mock Notify... |
public Long getAvgMergeTime() {
return avgMergeTime;
} | @Test(timeout = 10000)
public void testAverageMergeTime() throws IOException {
String historyFileName =
"job_1329348432655_0001-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist";
String confFileName =
"job_1329348432655_0001_conf.xml";
Configuration conf = new Config... |
public static AccessTokenValidator create(Map<String, ?> configs) {
return create(configs, (String) null);
} | @Test
public void testConfigureThrowsExceptionOnAccessTokenValidatorInit() {
OAuthBearerLoginCallbackHandler handler = new OAuthBearerLoginCallbackHandler();
AccessTokenRetriever accessTokenRetriever = new AccessTokenRetriever() {
@Override
public void init() throws IOExcepti... |
public static void add(String group, List<String> users) {
for (String user : users) {
Set<String> userGroups = userToNetgroupsMap.get(user);
// ConcurrentHashMap does not allow null values;
// So null value check can be used to check if the key exists
if (userGroups == null) {
//Ge... | @Test
public void testMembership() {
List<String> users = new ArrayList<String>();
users.add(USER1);
users.add(USER2);
NetgroupCache.add(GROUP1, users);
users = new ArrayList<String>();
users.add(USER1);
users.add(USER3);
NetgroupCache.add(GROUP2, users);
verifyGroupMembership(USER... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = models.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = 0;
for (int ... | @Test
public void testKin8nm() {
test("kin8nm", Kin8nm.formula, Kin8nm.data, 0.1704);
} |
public String getName() {
String path = uri.getPath();
int slash = path.lastIndexOf(SEPARATOR);
return path.substring(slash+1);
} | @Test (timeout = 30000)
public void testGetName() {
assertEquals("", new Path("/").getName());
assertEquals("foo", new Path("foo").getName());
assertEquals("foo", new Path("/foo").getName());
assertEquals("foo", new Path("/foo/").getName());
assertEquals("bar", new Path("/foo/bar").getName());
... |
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
super.pluginLoaded(pluginDescriptor);
if(extension.canHandlePlugin(pluginDescriptor.id())) {
for (PluginMetadataChangeListener listener: listeners) {
listener.onPluginMetadataCreate(pluginDescripto... | @Test
public void onPluginLoaded_shouldIgnoreNonAnalyticsPlugins() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
AnalyticsMetadataLoader metadataLoader = new AnalyticsMetadataLoader(pluginManager, metadataStore, infoBuilder, extension);
... |
static KiePMMLClusteringField getKiePMMLClusteringField(ClusteringField clusteringField) {
double fieldWeight = clusteringField.getFieldWeight() == null ? 1.0 :
clusteringField.getFieldWeight().doubleValue();
boolean isCenterField =
clusteringField.getCenterField() == nul... | @Test
void getKiePMMLClusteringField() {
ClusteringField clusteringField = new ClusteringField();
final Random random = new Random();
clusteringField.setField("TEXT");
clusteringField.setFieldWeight(random.nextDouble());
clusteringField.setCenterField(getRandomEnum(Clustering... |
public static final void loadAttributesMap( DataNode dataNode, AttributesInterface attributesInterface )
throws KettleException {
loadAttributesMap( dataNode, attributesInterface, NODE_ATTRIBUTE_GROUPS );
} | @Test
public void testLoadAttributesMap_DefaultTag() throws Exception {
try ( MockedStatic<AttributesMapUtil> mockedAttributesMapUtil = mockStatic( AttributesMapUtil.class ) ) {
mockedAttributesMapUtil.when( () -> AttributesMapUtil.loadAttributesMap( any( DataNode.class ),
any( AttributesInterface.c... |
Map<ProjectionProducer<PTransform<?, ?>>, Map<PCollection<?>, FieldAccessDescriptor>>
getPushdownOpportunities() {
return pushdownOpportunities.build();
} | @Test
public void testPushdownProducersWithMultipleOutputs_returnsMultiplePushdowns() {
Pipeline p = Pipeline.create();
PTransform<PBegin, PCollectionTuple> source = new MultipleOutputSourceWithPushdown();
PCollectionTuple outputs = p.apply(source);
Map<PCollection<?>, FieldAccessDescriptor> pCollect... |
public static void createTrustedCertificatesVolumes(List<Volume> volumeList, List<CertSecretSource> trustedCertificates, boolean isOpenShift) {
createTrustedCertificatesVolumes(volumeList, trustedCertificates, isOpenShift, null);
} | @Test
public void testTrustedCertificatesVolumes() {
CertSecretSource cert1 = new CertSecretSourceBuilder()
.withSecretName("first-certificate")
.withCertificate("ca.crt")
.build();
CertSecretSource cert2 = new CertSecretSourceBuilder()
... |
@Override
public PageResult<FileConfigDO> getFileConfigPage(FileConfigPageReqVO pageReqVO) {
return fileConfigMapper.selectPage(pageReqVO);
} | @Test
public void testGetFileConfigPage() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setName("芋道源码")
.setStorage(FileStorageEnum.LOCAL.getStorage());
dbFileConfig.setCreateTime(LocalDateTimeUtil.parse("2020-01-23", DatePattern.NORM_DATE_PATTERN));// 等会查询到
... |
@Override
public void finish()
throws IOException
{
writer.flush();
} | @Test
public void testJsonPrintingNoRows()
throws Exception
{
StringWriter writer = new StringWriter();
List<String> fieldNames = ImmutableList.of("first", "last");
OutputPrinter printer = new JsonPrinter(fieldNames, writer);
printer.finish();
assertEquals(w... |
public void incrementCount() {
incrementCount(headSlot, 1);
} | @Test
public void testIncrementCount() {
assertEquals(0, counter.get(1));
assertEquals(0, counter.get(2));
counter.incrementCount();
assertEquals(1, counter.get(1));
assertEquals(1, counter.get(2));
counter.incrementCount(2);
assertEquals(3, counter.get(2));
... |
public static LineageGraph convertToLineageGraph(List<Transformation<?>> transformations) {
DefaultLineageGraph.LineageGraphBuilder builder = DefaultLineageGraph.builder();
for (Transformation<?> transformation : transformations) {
List<LineageEdge> edges = processSink(transformation);
... | @Test
void testExtractLineageGraphFromLegacyTransformations() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Long> source = env.addSource(new LineageSourceFunction());
DataStreamSink<Long> sink = source.addSink(new L... |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String targetObjectId = reader.readLine();
String methodName = reader.readLine();
List<Object> arguments = getArguments(reader);
ReturnObject returnObject = invokeMethod(metho... | @Test
public void testReflectionException2() {
String inputCommand = target + "\nmethod1aa\ne\n";
try {
command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer);
assertTrue(sWriter.toString().startsWith("!xspy4j.Py4JException: "));
} catch (Exception e) {
e.printStackTrace();
... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
EntityType originatorEntityType = msg.getOriginator().getEntityType();
if (!EntityType.DEVICE.equals(originatorEntityType)) {
ctx.tellFailure(msg, new IllegalArgumentException(
"Unsupported originator entity type... | @Test
public void givenMsgArrivedTooFast_whenOnMsg_thenRateLimitsThisMsg() {
// GIVEN
ConcurrentReferenceHashMap<DeviceId, TbRateLimits> rateLimits = new ConcurrentReferenceHashMap<>();
ReflectionTestUtils.setField(node, "rateLimits", rateLimits);
var rateLimitMock = mock(TbRateLimi... |
@Override
public void reset() {
set(INIT);
} | @Test
public void testReset() {
SnapshotRegistry registry = new SnapshotRegistry(new LogContext());
TimelineLong value = new TimelineLong(registry);
registry.getOrCreateSnapshot(2);
value.set(1L);
registry.getOrCreateSnapshot(3);
value.set(2L);
registry.reset... |
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(itemType, "itemType may not be null");
if (dataTable.isEmpty()) {
return emptyList();
}
ListOrProblems<T> result = to... | @Test
void convert_to_list__double_column__throws_exception() {
DataTable table = parse("",
"| 3 | 5 |",
"| 6 | 7 |");
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> converter.toList(table, Integer.class))... |
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.importPolicy().classReference(inliner, getTopLevelClass(), getName());
} | @Test
public void inline() {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
context.put(PackageSymbol.class, Symtab.instance(context).rootPackage);
assertInlines("List", UClassIdent.create("java.util.List"));
assertInlines("Map.Entry", UClassIdent.create("java.util.Map.Entry"));
} |
public Set<String> usedStreamIds() {
final Set<String> queryStreamIds = queries().stream()
.map(Query::usedStreamIds)
.reduce(Collections.emptySet(), Sets::union);
final Set<String> searchTypeStreamIds = queries().stream()
.flatMap(q -> q.searchTypes().str... | @Test
void usedStreamIdsReturnsQueryStreamsWhenSearchTypesAreMissing() {
final Search search = searchWithQueriesWithStreams("c,d,e");
assertThat(search.usedStreamIds()).containsExactlyInAnyOrder("c", "d", "e");
} |
public boolean isDisabled() {
return _disabled;
} | @Test
public void withDisabledFalse()
throws JsonProcessingException {
String confStr = "{\"disabled\": false}";
IndexConfig config = JsonUtils.stringToObject(confStr, IndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
} |
@Override
public void run() {
SecurityManager sm = System.getSecurityManager();
if (!(sm instanceof SelSecurityManager)) {
throw new IllegalStateException("Invalid security manager: " + sm);
}
Thread.currentThread().setContextClassLoader(this.classLoader);
((SelSecurityManager) sm).setAccess... | @Test
public void testRun() throws Exception {
assertEquals(0, i);
System.setSecurityManager(new SelSecurityManager());
t2.start();
t2.join();
assertEquals(10, i);
assertNull(ex);
} |
@Override
public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria)
{
Map<String, String> variables = new HashMap<>();
if (userRegex.isPresent()) {
Matcher userMatcher = userRegex.get().matcher(criteria.getUser());
if (!userMatcher.matches()) {
... | @Test
public void testUserRegex()
{
ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "foo");
StaticSelector selector = new StaticSelector(
Optional.of(Pattern.compile("user.*")),
Optional.empty(),
Optional.empty(... |
@Override
public Map<String, Object> newMap() {
return new CaseInsensitiveMap<>();
} | @Test
public void testConstructFromOther() {
Map<String, Object> other = new FastHeadersMapFactory().newMap();
other.put("Foo", "cheese");
other.put("bar", 123);
Map<String, Object> map = new FastHeadersMapFactory().newMap(other);
assertEquals("cheese", map.get("FOO"));
... |
@Override
public boolean delete(URI segmentUri, boolean forceDelete)
throws IOException {
LOGGER.info("Deleting uri {} force {}", segmentUri, forceDelete);
try {
if (isDirectory(segmentUri)) {
if (!forceDelete) {
Preconditions.checkState(isEmptyDirectory(segmentUri),
... | @Test
public void testDeleteFile()
throws Exception {
String[] originalFiles = new String[]{"a-delete.txt", "b-delete.txt", "c-delete.txt"};
String fileToDelete = "a-delete.txt";
List<String> expectedResultList = new ArrayList<>();
for (String fileName : originalFiles) {
createEmptyFile("... |
public static Method setter(Class<?> o, String propertiesName) {
if (o == null) {
return null;
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o);
return descriptor.getWriteMethod();
} catch (IntrospectionException e) {
... | @Test
public void testSetter() {
Method name = BeanUtil.setter(Customer.class, "name");
Assert.assertEquals("setName", name.getName());
} |
@Override
public Object construct(String componentName) {
ClusteringConfiguration clusteringConfiguration = configuration.clustering();
boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer();
int level = configuration.locking().concurrencyLevel();
MemoryConfigurati... | @Test
public void testDefaultSegmented() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.cacheMode(CacheMode.DIST_ASYNC).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(DefaultSegmentedDataContainer.class, compone... |
@Override
public int run(String[] argv) {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-safemode".equals(cmd)) {
if (argv.length != 2) ... | @Test(timeout = 30000)
public void testPrintTopologyWithStatus() throws Exception {
redirectStream();
final Configuration dfsConf = new HdfsConfiguration();
final File baseDir = new File(
PathUtils.getTestDir(getClass()),
GenericTestUtils.getMethodName());
dfsConf.set(MiniDFSCl... |
@Override
public final int readInt() throws EOFException {
final int i = readInt(pos);
pos += INT_SIZE_IN_BYTES;
return i;
} | @Test
public void testReadIntPosition() throws Exception {
int readInt = in.readInt(2);
int theInt = Bits.readInt(INIT_DATA, 2, byteOrder == BIG_ENDIAN);
assertEquals(theInt, readInt);
} |
@Override
public Mono<Void> withoutFallback(final ServerWebExchange exchange, final Throwable throwable) {
Object error;
if (throwable instanceof DegradeException) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
error = ShenyuResultWrap.error(exchang... | @Test
public void testDegradeException() {
StepVerifier.create(fallbackHandler.withoutFallback(exchange, new DegradeException("Sentinel"))).expectSubscription().verifyComplete();
} |
public static String format(String json) {
final StringBuilder result = new StringBuilder();
Character wrapChar = null;
boolean isEscapeMode = false;
int length = json.length();
int number = 0;
char key;
for (int i = 0; i < length; i++) {
key = json.charAt(i);
if (CharUtil.DOUBLE_QUOTES == key || ... | @Test
public void formatTest() {
String json = "{'age':23,'aihao':['pashan','movies'],'name':{'firstName':'zhang','lastName':'san','aihao':['pashan','movies','name':{'firstName':'zhang','lastName':'san','aihao':['pashan','movies']}]}}";
String result = JSONStrFormatter.format(json);
assertNotNull(result);
} |
@Override
public double entropy() {
return entropy;
} | @Test
public void testEntropy() {
System.out.println("entropy");
BinomialDistribution instance = new BinomialDistribution(100, 0.3);
instance.rand();
assertEquals( 2.9412, instance.entropy(), 1E-4);
} |
public static PTransformMatcher classEqualTo(Class<? extends PTransform> clazz) {
return new EqualClassPTransformMatcher(clazz);
} | @Test
public void classEqualToDoesNotMatchSubclass() {
class MyPTransform extends PTransform<PCollection<KV<String, Integer>>, PCollection<Integer>> {
@Override
public PCollection<Integer> expand(PCollection<KV<String, Integer>> input) {
return PCollection.createPrimitiveOutputInternal(
... |
public boolean hasRequiredCoordinatorSidecars()
{
if (currentCoordinatorSidecarCount > 1) {
throw new PrestoException(TOO_MANY_SIDECARS,
format("Expected a single active coordinator sidecar. Found %s active coordinator sidecars", currentCoordinatorSidecarCount));
}
... | @Test
public void testHasRequiredCoordinatorSidecars()
throws InterruptedException
{
assertFalse(monitor.hasRequiredCoordinatorSidecars());
for (int i = numCoordinatorSidecars.get(); i < DESIRED_COORDINATOR_SIDECAR_COUNT; i++) {
addCoordinatorSidecar(nodeManager);
... |
@Override
public double getStdDev() {
// two-pass algorithm for variance, avoids numeric overflow
if (values.length <= 1) {
return 0;
}
final double mean = getMean();
double sum = 0;
for (long value : values) {
final double diff = value - me... | @Test
public void calculatesTheStdDev() {
assertThat(snapshot.getStdDev())
.isEqualTo(1.5811, offset(0.0001));
} |
@Override
public double read() {
return gaugeSource.read();
} | @Test
public void whenCreatedForDynamicDoubleMetricWithExtractedValue() {
SomeObject someObject = new SomeObject();
someObject.doubleField = 41.65D;
metricsRegistry.registerDynamicMetricsProvider(someObject);
DoubleGauge doubleGauge = metricsRegistry.newDoubleGauge("foo.doubleField")... |
static Set<Integer> getIndicesOfUpNodes(ClusterState clusterState, NodeType type) {
int nodeCount = clusterState.getNodeCount(type);
Set<Integer> nodesBeingUp = new HashSet<>();
for (int i = 0; i < nodeCount; ++i) {
Node node = new Node(type, i);
NodeState nodeState = cl... | @Test
void testIndicesOfUpNodes() {
when(clusterState.getNodeCount(NodeType.DISTRIBUTOR)).thenReturn(7);
NodeState nodeState = mock(NodeState.class);
when(nodeState.getState()).
thenReturn(State.MAINTENANCE). // 0
thenReturn(State.RETIRED). // 1
... |
@Override
public ListenableFuture<?> execute(Rollback statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.getTransactionId().isPr... | @Test
public void testUnknownTransactionRollback()
{
TransactionManager transactionManager = createTestTransactionManager();
Session session = sessionBuilder()
.setTransactionId(TransactionId.create()) // Use a random transaction ID that is unknown to the system
... |
public Mono<Table<String, TopicPartition, Long>> listConsumerGroupOffsets(List<String> consumerGroups,
// all partitions if null passed
@Nullable List<TopicPartition> p... | @Test
void testListConsumerGroupOffsets() throws Exception {
String topic = UUID.randomUUID().toString();
String anotherTopic = UUID.randomUUID().toString();
createTopics(new NewTopic(topic, 2, (short) 1), new NewTopic(anotherTopic, 1, (short) 1));
fillTopic(topic, 10);
Function<String, KafkaCons... |
@Operation(summary = "delete", description = "DELETE_WORKFLOWS_INSTANCE_NOTES")
@Parameters({
@Parameter(name = "workflowInstanceId", description = "WORKFLOW_INSTANCE_ID", schema = @Schema(implementation = Integer.class, example = "123456", required = true))
})
@DeleteMapping(value = "/{workflow... | @Test
public void testDeleteWorkflowInstanceById() {
User loginUser = getLoginUser();
Mockito.doNothing().when(processInstanceService).deleteProcessInstanceById(any(), eq(1));
Result result = workflowInstanceV2Controller.deleteWorkflowInstance(loginUser, 1);
Assertions.assertTrue(re... |
public static String convertToLowerUnderscore(String identifierName) {
return splitToLowercaseTerms(identifierName).stream().collect(Collectors.joining("_"));
} | @Test
public void convertToLowerUnderscore_separatesTerms_fromCamelCase() {
String identifierName = "camelCase";
String lowerUnderscore = NamingConventions.convertToLowerUnderscore(identifierName);
assertThat(lowerUnderscore).isEqualTo("camel_case");
} |
Map<Class, Object> getSerializers() {
return serializers;
} | @Test
public void testLoad_withDefaultConstructor() {
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setClassName("com.hazelcast.internal.serialization.impl.TestSerializerHook$TestSerializer");
serializerConfig.setTypeClassName("com.hazelcast.internal.serializat... |
@Override
public List<TransferItem> list(final Session<?> session, final Path directory, final Local local,
final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Children for %s", directory));
... | @Test
public void testChildrenRemoteAndLocalExist() throws Exception {
final NullLocal directory = new NullLocal(System.getProperty("java.io.tmpdir"), "t") {
@Override
public AttributedList<Local> list() {
final AttributedList<Local> list = new AttributedList<>();
... |
@Override
public void add(Double value) {
this.min = Math.min(this.min, value);
} | @Test
void testAdd() {
DoubleMinimum min = new DoubleMinimum();
min.add(1234.5768);
min.add(9876.5432);
min.add(-987.6543);
min.add(-123.4567);
assertThat(min.getLocalValue()).isCloseTo(-987.6543, within(0.0));
} |
DecodedJWT verifyJWT(PublicKey publicKey,
String publicKeyAlg,
DecodedJWT jwt) throws AuthenticationException {
if (publicKeyAlg == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new... | @Test
public void ensureFutureIATFails() throws Exception {
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
DefaultJwtBuilder defaultJwtBuilder = new DefaultJwtBuilder();
addValidMandatoryClaims(defaultJwtBuilder, basicProviderAudience);
// Override the exp set in the ab... |
protected String concat( String path, String name ) {
return FilenameUtils.concat( path, name );
} | @Test
public void testConcat() {
assertEquals( "/home/devuser/files/food.txt",
testInstance.concat( "/home/devuser/files", "food.txt" ).replace('\\', '/') );
assertEquals( "/home/devuser/files/food.txt",
testInstance.concat( "/home/devuser/files/", "food.txt" ).replace('\\', '/') );
assertE... |
@SuppressWarnings("unchecked")
public static <R extends Tuple> TupleSummaryAggregator<R> create(TupleTypeInfoBase<?> inType) {
Aggregator[] columnAggregators = new Aggregator[inType.getArity()];
for (int field = 0; field < inType.getArity(); field++) {
Class clazz = inType.getTypeAt(fiel... | @Test
void testCreate() {
// supported primitive types
assertThat(SummaryAggregatorFactory.create(String.class).getClass())
.isEqualTo(StringSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Short.class).getClass())
.isEqualTo(ShortSummaryAg... |
@Override
public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext)
{
doEvaluateDisruptContext(request, requestContext);
return _client.sendRequest(request, requestContext);
} | @Test
public void testSendRequest13()
{
when(_controller.getDisruptContext(any(String.class))).thenReturn(_disrupt);
_client.sendRequest(_multiplexed, _context, _multiplexedCallback);
verify(_underlying, times(1)).sendRequest(eq(_multiplexed), eq(_context), eq(_multiplexedCallback));
verify(_context... |
public String getInstanceStatus() {
String serviceId = RegisterContext.INSTANCE.getClientInfo().getServiceId();
String group = nacosRegisterConfig.getGroup();
try {
NamingService namingService = nacosServiceManager.getNamingService();
List<Instance> instances = namingServ... | @Test
public void testGetInstanceStatus() throws NacosException {
mockNamingService();
Assert.assertNotNull(nacosClient.getInstanceStatus());
} |
public static FlowGraph of(GraphCluster graph) throws IllegalVariableEvaluationException {
return FlowGraph.builder()
.nodes(GraphUtils.nodes(graph))
.edges(GraphUtils.edges(graph))
.clusters(GraphUtils.clusters(graph, new ArrayList<>())
.stream()
... | @Test
void dynamicIdSubflow() throws IllegalVariableEvaluationException, TimeoutException {
Flow flow = this.parse("flows/valids/task-flow-dynamic.yaml").toBuilder().revision(1).build();
IllegalArgumentException illegalArgumentException = Assertions.assertThrows(IllegalArgumentException.class, () -... |
public static void createTrustedCertificatesVolumeMounts(List<VolumeMount> volumeMountList, List<CertSecretSource> trustedCertificates, String tlsVolumeMountPath) {
createTrustedCertificatesVolumeMounts(volumeMountList, trustedCertificates, tlsVolumeMountPath, null);
} | @Test
public void testTrustedCertificatesVolumeMounts() {
CertSecretSource cert1 = new CertSecretSourceBuilder()
.withSecretName("first-certificate")
.withCertificate("ca.crt")
.build();
CertSecretSource cert2 = new CertSecretSourceBuilder()
... |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, TimeLimiter timeLimiter, String methodName)
throws Throwable {
TimeLimiterTransformer<?> timeLimiterTransformer = TimeLimiterTransformer.of(timeLimiter);
Object returnValue = proceedingJoinPoint.proceed();
return... | @Test
public void shouldThrowIllegalArgumentExceptionWithNotRxJava2Type() throws Throwable{
TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn("NOT RXJAVA2 TYPE");
try {
rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint,... |
@Override
public boolean shouldClientThrottle(short version) {
return version >= 4;
} | @Test
public void testShouldThrottle() {
for (short version : ApiKeys.OFFSET_FETCH.allVersions()) {
if (version < 8) {
OffsetFetchResponse response = new OffsetFetchResponse(throttleTimeMs, Errors.NONE, partitionDataMap);
if (version >= 4) {
as... |
@Override
protected void onStateExpiry(UUID sessionId, TransportProtos.SessionInfoProto sessionInfo) {
log.debug("Session with id: [{}] has expired due to last activity time.", sessionId);
SessionMetaData expiredSession = sessions.remove(sessionId);
if (expiredSession != null) {
... | @Test
void givenSessionExists_whenOnStateExpiryCalled_thenShouldPerformExpirationActions() {
// GIVEN
TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder()
.setSessionIdMSB(SESSION_ID.getMostSignificantBits())
.setSessionIdLSB(SE... |
@Override
public ExecuteContext onThrow(ExecuteContext context) {
if (shouldHandle(context)) {
ThreadLocalUtils.removeRequestTag();
}
return context;
} | @Test
public void testOnThrow() {
ThreadLocalUtils.addRequestTag(Collections.singletonMap("bar", Collections.singletonList("foo")));
Assert.assertNotNull(ThreadLocalUtils.getRequestTag());
// Test the on Throw method to verify whether the thread variable is released
interceptor.onTh... |
public void generateAcknowledgementPayload(
MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode)
throws MllpAcknowledgementGenerationException {
generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null);
} | @Test
public void testGenerateAcknowledgementPayload() throws Exception {
MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
hl7util.generateAcknowledgementPayload(mllpSocketBuffer, TEST_MESSAGE.getBytes(), "AA");
String actual = mllpSocketBuffer.toString();
... |
public static boolean isAllInventoryTasksFinished(final Collection<PipelineTask> inventoryTasks) {
if (inventoryTasks.isEmpty()) {
log.warn("inventoryTasks is empty");
}
return inventoryTasks.stream().allMatch(each -> each.getTaskProgress().getPosition() instanceof IngestFinishedPosi... | @Test
void assertAllInventoryTasksAreFinishedWhenCollectionIsEmpty() {
assertTrue(PipelineJobProgressDetector.isAllInventoryTasksFinished(Collections.emptyList()));
} |
@Udf
public String lcase(
@UdfParameter(description = "The string to lower-case") final String input) {
if (input == null) {
return null;
}
return input.toLowerCase();
} | @Test
public void shouldReturnNullForNullInput() {
final String result = udf.lcase(null);
assertThat(result, is(nullValue()));
} |
CompletionStage<HttpServer> serve(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route()
.handler(BodyHandler.create())
.failureHandler(this::handleFailure);
router.route(HttpMethod.GET, "/catalo... | @Test
public void testInspect() throws Exception {
Agent agent = cmd();
agent.port = 0;
Vertx vertx = Vertx.vertx();
HttpServer server = agent.serve(vertx).toCompletableFuture().get();
try {
int port = server.actualPort();
String route = """
... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testGenerateRecordsOnNewClassicGroup() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
JoinGroupRequestData request = new GroupMetadataManagerTestContext.JoinGroupRequestBuilder()
.withGro... |
public static String getViewGroupTypeByReflect(View view) {
Class<?> compatClass;
String viewType = SnapCache.getInstance().getCanonicalName(view.getClass());
compatClass = ReflectUtil.getClassByName("android.support.v7.widget.CardView");
if (compatClass != null && compatClass.isInstance... | @Test
public void getViewGroupTypeByReflect() {
LinearLayout linearLayout = new LinearLayout(mApplication);
Assert.assertEquals("android.widget.LinearLayout",
SAViewUtils.getViewGroupTypeByReflect(linearLayout));
} |
public Struct(Schema schema) {
if (schema.type() != Schema.Type.STRUCT)
throw new DataException("Not a struct schema: " + schema);
this.schema = schema;
this.values = new Object[schema.fields().size()];
} | @Test
public void testMissingFieldValidation() {
// Required int8 field
Schema schema = SchemaBuilder.struct().field("field", REQUIRED_FIELD_SCHEMA).build();
Struct struct = new Struct(schema);
assertThrows(DataException.class, struct::validate);
} |
@Override
public boolean mayHaveMergesPending(String bucketSpace, int contentNodeIndex) {
if (!stats.hasUpdatesFromAllDistributors()) {
return true;
}
ContentNodeStats nodeStats = stats.getStats().getNodeStats(contentNodeIndex);
if (nodeStats != null) {
Conten... | @Test
void unknown_content_node_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 2));
} |
@Override
public UrlPattern doGetPattern() {
return UrlPattern.create("/" + SamlValidationWs.SAML_VALIDATION_CONTROLLER + "/" + VALIDATION_INIT_KEY);
} | @Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern().matches("/saml/validation_init")).isTrue();
assertThat(underTest.doGetPattern().matches("/api/saml")).isFalse();
assertThat(underTest.doGetPattern().matches("/api/saml/validation_init")).isFalse();
assertThat(underTest.doGetPatte... |
public RunConfiguration getRunConfigurationByType( String type ) {
RunConfigurationProvider runConfigurationProvider = getProvider( type );
if ( runConfigurationProvider != null ) {
return runConfigurationProvider.getConfiguration();
}
return null;
} | @Test
public void testGetRunConfigurationByType() {
DefaultRunConfiguration defaultRunConfiguration =
(DefaultRunConfiguration) executionConfigurationManager.getRunConfigurationByType( DefaultRunConfiguration.TYPE );
assertNotNull( defaultRunConfiguration );
} |
ObjectFactory loadObjectFactory() {
Class<? extends ObjectFactory> objectFactoryClass = options.getObjectFactoryClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class, classLoader);
if (objectFactoryClass... | @Test
void shouldLoadSelectedObjectFactoryService() {
Options options = () -> DefaultObjectFactory.class;
ObjectFactoryServiceLoader loader = new ObjectFactoryServiceLoader(
ObjectFactoryServiceLoaderTest.class::getClassLoader,
options);
assertThat(loader.loadObjectFa... |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldLoadFromSvnPartial() throws Exception {
String buildXmlPartial =
"<svn url=\"https://foo.bar\" username=\"cruise\" password=\"password\" materialName=\"https___foo.bar\"/>";
MaterialConfig materialConfig = xmlLoader.fromXmlPartial(buildXmlPartial, SvnMaterialConfig.... |
public QueryParseResult parse(String sql, @Nonnull SqlSecurityContext ssc) {
try {
return parse0(sql, ssc);
} catch (QueryException e) {
throw e;
} catch (Exception e) {
String message;
// Check particular type of exception which causes typical lon... | @Test
public void test_trailingSemicolon() {
given(sqlValidator.validate(isA(SqlNode.class))).willReturn(validatedNode);
parser.parse("SELECT * FROM t;");
parser.parse("SELECT * FROM t;;");
} |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Un... | @Test
public void shouldThrowOnUnknownType() {
// Given:
final SqlBaseType unknownType = mock(SqlBaseType.class, "bob");
final SqlType type = mock(SqlType.class);
when(type.baseType()).thenReturn(unknownType);
// When:
final UnsupportedOperationException e = assertThrows(
UnsupportedO... |
static List<Locale> negotiatePreferredLocales(String headerValue) {
if (headerValue == null || headerValue.isBlank()) {
headerValue = DEFAULT_LOCALE.toLanguageTag();
}
try {
var languageRanges = Locale.LanguageRange.parse(headerValue);
return Locale.filter(languageRanges, supportedLocale... | @Test
void test_negotiatePreferredLocales_brokenThrowsValidationException() {
assertThrows(ValidationException.class, () -> LocaleUtils.negotiatePreferredLocales("x21;"));
} |
@InterfaceAudience.Private
@VisibleForTesting
int scanActiveLogs() throws IOException {
long startTime = Time.monotonicNow();
// Store the Last Processed Time and Offset
if (recoveryEnabled && appIdLogMap.size() > 0) {
try (FSDataOutputStream checkPointStream = fs.create(checkpointFile, true)) {
... | @Test
void testScanActiveLogsWithInvalidFile() throws Exception {
Path invalidFile = new Path(testActiveDirPath, "invalidfile");
try {
if (!fs.exists(invalidFile)) {
fs.createNewFile(invalidFile);
}
store.scanActiveLogs();
} catch (StackOverflowError error) {
fail("EntityLo... |
@PostMapping("/token")
@PermitAll
@Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@Parameters({
@Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"),
@Parameter(name = "code", description = "授权... | @Test
public void testPostAccessToken_password() {
// 准备参数
String granType = OAuth2GrantTypeEnum.PASSWORD.getGrantType();
String username = randomString();
String password = randomString();
String scope = "write read";
HttpServletRequest request = mockRequest("test_cl... |
public String getStringForDisplay() {
if (isEmpty()) {
return "";
}
StringBuilder display = new StringBuilder();
for (IgnoredFiles ignoredFiles : this) {
display.append(ignoredFiles.getPattern()).append(",");
}
return display.substring(0, display.l... | @Test
public void shouldConcatenateIgnoredFilesWithCommaWhenDisplaying() {
Filter filter = new Filter(new IgnoredFiles("/foo/**.*"), new IgnoredFiles("/another/**.*"), new IgnoredFiles("bar"));
assertThat(filter.getStringForDisplay(), is("/foo/**.*,/another/**.*,bar"));
} |
public CompletableFuture<Void> subscribeAsync(String topicName, boolean createTopicIfDoesNotExist) {
TopicName topicNameInstance = getTopicName(topicName);
if (topicNameInstance == null) {
return FutureUtil.failedFuture(
new PulsarClientException.AlreadyClosedException("T... | @Test(timeOut = 10000)
public void testParallelSubscribeAsync() throws Exception {
String topicName = "parallel-subscribe-async-topic";
MultiTopicsConsumerImpl<byte[]> impl = createMultiTopicsConsumer();
CompletableFuture<Void> firstInvocation = impl.subscribeAsync(topicName, true);
... |
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credenti... | @Test
public void doNotGetEcsAddressesIfEc2Configured() {
// given
AwsConfig awsConfig = AwsConfig.builder()
.setSecurityGroupName("my-security-group")
.setDiscoveryMode(DiscoveryMode.Client)
.build();
awsEcsClient = new AwsEcsClient(CLUSTER, a... |
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
} | @Test(expected = EncodingException.class)
public void testParsingNoSubType() {
MediaType.fromString("something");
} |
String getFileName(double lat, double lon) {
int lonInt = getMinLonForTile(lon);
int latInt = getMinLatForTile(lat);
return toLowerCase(getLatString(latInt) + getNorthString(latInt) + getLonString(lonInt) + getEastString(lonInt) + FILE_NAME_END);
} | @Disabled
@Test
public void testGetEleVerticalBorder() {
// Border between the tiles 50n000e and 70n000e
assertEquals("50n000e_20101117_gmted_mea075", instance.getFileName(69.999999, 19.493));
assertEquals(268, instance.getEle(69.999999, 19.5249), precision);
assertEquals("70n000... |
@Override
public boolean containsValue(Object value) {
return false;
} | @Test
public void testContainsValue() {
assertFalse(NULL_QUERY_CACHE.containsValue(1));
} |
public void removeUpTo(long item1, long item2) {
lock.writeLock().lock();
try {
Map.Entry<Long, RoaringBitmap> firstEntry = map.firstEntry();
while (firstEntry != null && firstEntry.getKey() <= item1) {
if (firstEntry.getKey() < item1) {
map.re... | @Test
public void testRemoveUpTo() {
ConcurrentBitmapSortedLongPairSet set = new ConcurrentBitmapSortedLongPairSet();
set.removeUpTo(0, 1000);
set.removeUpTo(10, 10000);
assertTrue(set.isEmpty());
set.add(1, 0);
int items = 10;
for (int i = 0; i < items; i++... |
void startup(@Observes StartupEvent event) {
if (jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) {
backgroundJobServerInstance.get().start();
}
if (jobRunrBuildTimeConfiguration.dashboard().enabled()) {
dashboardWebServerInstance.get().start();
}
... | @Test
void jobRunrStarterStartsBackgroundJobServerIfConfigured() {
when(backgroundJobServerConfiguration.enabled()).thenReturn(true);
jobRunrStarter.startup(new StartupEvent());
verify(backgroundJobServer).start();
} |
public static Object coerceValue(DMNType requiredType, Object valueToCoerce) {
return (requiredType != null && valueToCoerce != null) ? actualCoerceValue(requiredType, valueToCoerce) :
valueToCoerce;
} | @Test
void coerceValueCollectionToArrayNotConverted() {
Object item = "TESTED_OBJECT";
Object value = Collections.singleton(item);
DMNType requiredType = new SimpleTypeImpl("http://www.omg.org/spec/DMN/20180521/FEEL/",
"string",
... |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringWithEscaping() {
String[] result;
result = Const.splitString( null, null, null );
assertNull( result );
result = Const.splitString( "Hello, world", null, null );
assertNotNull( result );
assertEquals( result.length, 1 );
assertEquals( result[0], "Hello, w... |
public static String[] getParentFirstLoaderPatterns(ReadableConfig config) {
List<String> base = config.get(ALWAYS_PARENT_FIRST_LOADER_PATTERNS);
List<String> append = config.get(ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL);
return mergeListsToArray(base, append);
} | @Test
void testGetParentFirstLoaderPatterns() {
testParentFirst(
CoreOptions::getParentFirstLoaderPatterns,
CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS,
CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL);
} |
@Transactional
@Cacheable(CACHE_DATABASE_SEARCH)
@CacheEvict(value = CACHE_AVERAGE_REVIEW_RATING, allEntries = true)
public SearchHits<ExtensionSearch> search(ISearchService.Options options) {
// grab all extensions
var matchingExtensions = repositories.findAllActiveExtensions();
//... | @Test
public void testQueryStringExtensionName() {
var ext1 = mockExtension("yaml", 3.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages"));
var ext2 = mockExtension("java", 4.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages"));
var ext3 = mockExtension("openshift... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldMatchGenericMethodWithMultipleIdenticalGenerics() {
// Given:
final GenericType generic = GenericType.of("A");
givenFunctions(
function(EXPECTED, -1, generic, generic)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.... |
@Override
protected List<DavResource> list(final Path file) throws IOException {
return session.getClient().list(new DAVPathEncoder().encode(file), 0, Collections.unmodifiableSet(Stream.concat(
Stream.of(GUID_QN), ALL_ACL_QN.stream()
).collect(Collectors.toSet())));
} | @Test
public void testFindDirectory() throws Exception {
final Path home = new DefaultHomeFinderService(session).find();
final Path test = new CteraDirectoryFeature(session).mkdir(new Path(home,
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new Tra... |
public static List<Tab> getTabsFromJson(@Nullable final String tabsJson)
throws InvalidJsonException {
if (tabsJson == null || tabsJson.isEmpty()) {
return getDefaultTabs();
}
final List<Tab> returnTabs = new ArrayList<>();
final JsonObject outerJsonObject;
... | @Test
public void testInvalidIdRead() throws TabsJsonHelper.InvalidJsonException {
final int blankTabId = Tab.Type.BLANK.getTabId();
final String emptyTabsJson = "{\"" + JSON_TABS_ARRAY_KEY + "\":["
+ "{\"" + JSON_TAB_ID_KEY + "\":" + blankTabId + "},"
+ "{\"" + JSON_... |
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));... | @Test
void invokeNumberWithGroupCharSpace() {
FunctionTestUtil.assertResult(numberFunction.invoke("9 876", " ", null), BigDecimal.valueOf(9876));
FunctionTestUtil.assertResult(numberFunction.invoke("9 876 000", " ", null), BigDecimal.valueOf(9876000));
} |
public int readInt2() {
return byteBuf.readUnsignedShortLE();
} | @Test
void assertReadInt2() {
when(byteBuf.readUnsignedShortLE()).thenReturn(1);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt2(), is(1));
} |
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(d... | @Test
public void testPrivateTag() {
DecimalEncodedValue carSpeedEnc = new DecimalEncodedValueImpl("car_speed", 5, 5, false);
DecimalEncodedValue bikeSpeedEnc = new DecimalEncodedValueImpl("bike_speed", 4, 2, false);
EncodingManager em = EncodingManager.start().add(carSpeedEnc).add(bikeSpeed... |
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return DatasourceConfiguration.isEmbeddedStorage() && !EnvUtil.getStandaloneMode();
} | @Test
void testMatches() {
MockedStatic<DatasourceConfiguration> propertyUtilMockedStatic = Mockito.mockStatic(DatasourceConfiguration.class);
MockedStatic<EnvUtil> envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class);
propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbe... |
public BundleProcessor getProcessor(
BeamFnApi.ProcessBundleDescriptor descriptor,
List<RemoteInputDestination> remoteInputDesinations) {
checkState(
!descriptor.hasStateApiServiceDescriptor(),
"The %s cannot support a %s containing a state %s.",
BundleProcessor.class.getSimpleNa... | @Test
public void handleCleanupWithStateWhenProcessingBundleFails() throws Exception {
RuntimeException testException = new RuntimeException();
BeamFnDataOutboundAggregator mockInputSender = mock(BeamFnDataOutboundAggregator.class);
StateDelegator mockStateDelegator = mock(StateDelegator.class);
Stat... |
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if (StringUtils.isBlank(msg)) {
ctx.writeAndFlush(QosProcessHandler.PROMPT);
} else {
CommandContext commandContext = TelnetCommandDecoder.decode(msg);
commandContext.... | @Test
void testBye() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
ChannelFuture future = mock(ChannelFuture.cl... |
void setReplicas(PartitionReplica[] newReplicas) {
PartitionReplica[] oldReplicas = replicas;
replicas = newReplicas;
onReplicasChange(newReplicas, oldReplicas);
} | @Test
public void testSetReplicaAddresses_afterInitialSet() {
replicaOwners[0] = localReplica;
partition.setReplicas(replicaOwners);
partition.setReplicas(replicaOwners);
} |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
Num refValue = ref.getValue(index);
final boolean satisfied = refValue.isLessThanOrEqual(upper.getValue(index))
&& refValue.isGreaterThanOrEqual(lower.getValue(index));
traceIsSatisfied(index, sati... | @Test
public void isSatisfied() {
assertTrue(rule.isSatisfied(0));
assertTrue(rule.isSatisfied(1));
assertTrue(rule.isSatisfied(2));
assertFalse(rule.isSatisfied(3));
assertFalse(rule.isSatisfied(4));
assertTrue(rule.isSatisfied(5));
assertTrue(rule.isSatisfie... |
@Override
protected ActivityState<TransportProtos.SessionInfoProto> updateState(UUID sessionId, ActivityState<TransportProtos.SessionInfoProto> state) {
SessionMetaData session = sessions.get(sessionId);
if (session == null) {
return null;
}
state.setMetadata(session.get... | @Test
void givenSessionDoesNotExist_whenUpdatingActivityState_thenShouldReturnNull() {
// GIVEN
TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder()
.setSessionIdMSB(SESSION_ID.getMostSignificantBits())
.setSessionIdLSB(SESSION_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.