focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Combine.BinaryCombineIntegerFn ofIntegers() {
return new Max.MaxIntegerFn();
} | @Test
public void testMaxIntegerFn() {
testCombineFn(Max.ofIntegers(), Lists.newArrayList(1, 2, 3, 4), 4);
} |
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) {
List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext()
? createShardingConditionsWithInsertValues(sqlStatementContext, params)
... | @Test
void assertCreateShardingConditionsInsertStatementWithGeneratedKeyContextUsingCommonExpressionSegmentNow() {
when(insertStatementContext.getInsertValueContexts()).thenReturn(Collections.singletonList(createInsertValueContextAsCommonExpressionSegmentWithNow()));
when(insertStatementContext.getG... |
@Override
public void write(ProjectDump.Metadata metadata) {
checkNotPublished();
if (metadataWritten.get()) {
throw new IllegalStateException("Metadata has already been written");
}
File file = new File(rootDir, METADATA.filename());
try (FileOutputStream output = FILES2.openOutputStream(fi... | @Test
public void writeMetadata_fails_if_called_twice() {
underTest.write(newMetadata());
assertThatThrownBy(() -> underTest.write(newMetadata()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Metadata has already been written");
} |
@Udf(schema = "ARRAY<STRUCT<K STRING, V BIGINT>>")
public List<Struct> entriesBigInt(
@UdfParameter(description = "The map to create entries from") final Map<String, Long> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
return e... | @Test
public void shouldComputeBigIntEntriesSorted() {
final Map<String, Long> map = createMap(Long::valueOf);
shouldComputeEntriesSorted(map, () -> entriesUdf.entriesBigInt(map, true));
} |
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// Do not allow framing; OF-997
... | @Test
public void nonExcludedUrlWillNotErrorWhenCIDROnAllowlist() throws Exception {
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(AdminUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager);
final String cidr = rem... |
@Override
public List<String> getPermissions() {
final Set<String> permissionSet = isServiceAccount() ? new HashSet<>() : new HashSet<>(this.permissions.userSelfEditPermissions(getName()));
@SuppressWarnings("unchecked")
final List<String> permissions = (List<String>) fields.get(PERMISSIONS)... | @Test
public void getPermissionsReturnsListOfPermissions() throws Exception {
final Permissions permissions = new Permissions(Collections.emptySet());
final List<String> customPermissions = Collections.singletonList("subject:action");
final Map<String, Object> fields = ImmutableMap.of(
... |
public static void setKiePMMLModelConstructor(final String generatedClassName,
final ConstructorDeclaration constructorDeclaration,
final String fileName,
final String na... | @Test
void setKiePMMLModelConstructor() {
String generatedClassName = "generatedClassName";
String fileName = "fileName";
String name = "newName";
List<MiningField> miningFields = IntStream.range(0, 3)
.mapToObj(i -> ModelUtils.convertToKieMiningField(getRandomMiningF... |
public ControllerResult<ElectMasterResponseHeader> electMaster(final ElectMasterRequestHeader request,
final ElectPolicy electPolicy) {
final String brokerName = request.getBrokerName();
final Long brokerId = request.getBrokerId();
final ControllerResult<ElectMasterResponseHeader> result... | @Test
public void testElectMasterPreferHigherEpoch() {
mockMetaData();
final ElectMasterRequestHeader request = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME);
ElectPolicy electPolicy = new DefaultElectPolicy(this.heartbeatManager::isBrokerActive, this.heartbeatManager::ge... |
@Override
public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final EueApiClient client = new EueApiClient(session);
if(status.isExists()) {
... | @Test
public void testMoveFile() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directo... |
@Override
public ArtifactPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
PluggableInstanceSettings storeConfigSettings = storeConfigMetadata(descriptor.id());
PluggableInstanceSettings publishArtifactConfigSettings = publishArtifactMetadata(descriptor.id());
PluggableInstanceSettin... | @Test
public void shouldContinueWithBuildingPluginInfoIfPluginSettingsIsNotProvidedByPlugin() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
doThrow(new RuntimeException("foo")).when(extension).getPluginSettingsConfiguration("plugin1");
ArtifactPluginI... |
public void close() {
synchronized (this) {
if (!closed) {
leaderCopyRLMTasks.values().forEach(RLMTaskWithFuture::cancel);
leaderExpirationRLMTasks.values().forEach(RLMTaskWithFuture::cancel);
followerRLMTasks.values().forEach(RLMTaskWithFuture::cancel... | @Test
public void testRemoveMetricsOnClose() throws IOException {
MockedConstruction<KafkaMetricsGroup> mockMetricsGroupCtor = mockConstruction(KafkaMetricsGroup.class);
try {
RemoteLogManager remoteLogManager = new RemoteLogManager(config.remoteLogManagerConfig(), brokerId, logDir, clus... |
@Override
public boolean syncVerifyData(DistroData verifyData, String targetServer) {
if (isNoExistTarget(targetServer)) {
return true;
}
// replace target server as self server so that can callback.
verifyData.getDistroKey().setTargetServer(memberManager.getSelf().getAdd... | @Test
void testSyncVerifyDataWithCallbackFailure() throws NacosException {
DistroData verifyData = new DistroData();
verifyData.setDistroKey(new DistroKey());
when(memberManager.hasMember(member.getAddress())).thenReturn(true);
when(memberManager.find(member.getAddress())).thenReturn... |
static Future<Optional<String>> newUpdateChecker(
GlobalConfig globalConfig, Verbosity verbosity, Consumer<LogEvent> log) {
if (!verbosity.atLeast(Verbosity.info) || globalConfig.isDisableUpdateCheck()) {
return Futures.immediateFuture(Optional.empty());
}
ExecutorService executorService = Execu... | @Test
public void testNewUpdateChecker_noUpdateCheck() throws ExecutionException, InterruptedException {
when(globalConfig.isDisableUpdateCheck()).thenReturn(true);
Future<Optional<String>> updateChecker =
JibCli.newUpdateChecker(globalConfig, Verbosity.info, ignored -> {});
assertThat(updateCheck... |
public static Predicate parse(String expression)
{
final Stack<Predicate> predicateStack = new Stack<>();
final Stack<Character> operatorStack = new Stack<>();
final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll("");
final StringTokenizer tokenizer = new StringTokenizer(tr... | @Test
public void testAnd()
{
final Predicate parsed = PredicateExpressionParser.parse("com.linkedin.data.it.AlwaysTruePredicate & com.linkedin.data.it.AlwaysFalsePredicate");
Assert.assertEquals(parsed.getClass(), AndPredicate.class);
final List<Predicate> children = ((AndPredicate) parsed).getChildPr... |
public String getProgress(final boolean running, final long size, final long transferred) {
return this.getProgress(System.currentTimeMillis(), running, size, transferred);
} | @Test
public void testProgressRemaining() {
final long start = System.currentTimeMillis();
Speedometer m = new Speedometer(start, true);
assertEquals("1 B of 5 B (20%, 1 B/sec, 4 seconds remaining)", m.getProgress(start + 1000L, true, 5L, 1L));
assertEquals("4 B of 5 B (80%, 2 B/sec,... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultMappingTreatment) {
DefaultMappingTreatment that = (DefaultMappingTreatment) obj;
return Objects.equals(address, that.address) &&
... | @Test
public void testEquals() {
IpPrefix ip1 = IpPrefix.valueOf(IP_ADDRESS_1);
MappingAddress address1 = MappingAddresses.ipv4MappingAddress(ip1);
MappingTreatment treatment1 = DefaultMappingTreatment.builder()
.withAddress(address1)
... |
public boolean hasValues(K key)
{
List<V> list = data.get(key);
if (list == null) {
return false;
}
return !list.isEmpty();
} | @Test
public void testHasValue()
{
assertThat(map.hasValues(1L), is(true));
assertThat(map.hasValues(42L), is(false));
} |
public static String generateRandomAlphanumericString(Random rnd, int length) {
checkNotNull(rnd);
checkArgument(length >= 0);
StringBuilder buffer = new StringBuilder(length);
for (int i = 0; i < length; i++) {
buffer.append(nextAlphanumericChar(rnd));
}
ret... | @Test
void testGenerateAlphanumeric() {
String str = StringUtils.generateRandomAlphanumericString(new Random(), 256);
assertThat(str).matches("[a-zA-Z0-9]{256}");
} |
@SuppressWarnings("unchecked")
public static void appendValue(Map<String, Object> map, String key, Object value) {
Object oldValue = map.get(key);
if (oldValue != null) {
List<Object> list;
if (oldValue instanceof List) {
list = (List<Object>) oldValue;
... | @Test
public void testAppendValue() {
Map<String, Object> map = new HashMap<>();
CollectionHelper.appendValue(map, "foo", 123);
assertEquals(1, map.size());
CollectionHelper.appendValue(map, "foo", 456);
assertEquals(1, map.size());
CollectionHelper.appendValue(map,... |
public CoordinatorResult<Void, CoordinatorRecord> cleanupGroupMetadata() {
long startMs = time.milliseconds();
List<CoordinatorRecord> records = new ArrayList<>();
groupMetadataManager.groupIds().forEach(groupId -> {
boolean allOffsetsExpired = offsetMetadataManager.cleanupExpiredOff... | @Test
public void testCleanupGroupMetadata() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
Time mockTime = new MockTime();
MockCoordinatorTimer<Void, CoordinatorRecord> ... |
@Override
public void deleteFiles(Iterable<String> pathsToDelete) throws BulkDeletionFailureException {
internalDeleteFiles(Streams.stream(pathsToDelete).map(BlobId::fromGsUtilUri));
} | @Test
public void testDeleteFiles() {
String prefix = "del/path/";
String path1 = prefix + "data1.dat";
storage.create(BlobInfo.newBuilder(TEST_BUCKET, path1).build());
String path2 = prefix + "data2.dat";
storage.create(BlobInfo.newBuilder(TEST_BUCKET, path2).build());
String path3 = "del/ski... |
@POST
@Timed
@ApiOperation(
value = "Launch input on this node",
response = InputCreated.class
)
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No such input type registered"),
@ApiResponse(code = 400, message = "Missing or invalid configurati... | @Test
public void testCreateInput() throws Exception {
when(configuration.isCloud()).thenReturn(false);
when(messageInputFactory.create(any(), any(), any())).thenReturn(messageInput);
when(inputService.save(any())).thenReturn("id");
assertThat(inputsResource.create(inputCreateReques... |
@Scheduled(
initialDelayString = "${kayenta.prometheus.health.initial-delay:PT2S}",
fixedDelayString = "${kayenta.prometheus.health.fixed-delay:PT5M}")
public void run() {
List<PrometheusHealthStatus> healthStatuses =
prometheusConfigurationProperties.getAccounts().stream()
.map(
... | @Test
public void oneRemoteIsDown() {
when(PROM_REMOTE_1.isHealthy()).thenReturn("OK");
when(PROM_REMOTE_2.isHealthy()).thenThrow(new RuntimeException("test 2"));
healthJob.run();
verify(healthCache)
.setHealthStatuses(
Arrays.asList(
PrometheusHealthJob.Prometheu... |
@Override
public Publisher<Exchange> to(String uri, Object data) {
String streamName = requestedUriToStream.computeIfAbsent(uri, camelUri -> {
try {
String uuid = context.getUuidGenerator().generateUuid();
context.addRoutes(new RouteBuilder() {
... | @Test
public void testToFunction() throws Exception {
context.start();
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Function<Object, Publisher<String>> fun = crs.to("bean:hello", String.class);
Flux.just(1,... |
@Override
public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters,
final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) {
Collection<Stri... | @Test
void assertDecideWhenContainsPartialDistinctAggregation() {
SelectStatementContext select = createStatementContext();
when(select.isContainsPartialDistinctAggregation()).thenReturn(true);
Collection<DataNode> includedDataNodes = new HashSet<>();
ShardingRule shardingRule = crea... |
static void setConstructor(final TreeCompilationDTO compilationDTO,
final ClassOrInterfaceDeclaration modelTemplate,
final String fullNodeClassName) {
KiePMMLModelFactoryUtils.init(compilationDTO,
modelTemplate);... | @Test
void setConstructor() {
String className = getSanitizedClassName(treeModel1.getModelName());
CompilationUnit cloneCU = JavaParserUtils.getKiePMMLModelCompilationUnit(className, PACKAGE_NAME,
KIE_PMML_TREE_MODEL_TEMPLATE_JAVA,
KIE_PMML_TREE_MODEL_TEMPLATE);
... |
@Override
public int run(String[] args) throws Exception {
try {
webServiceClient = WebServiceClient.getWebServiceClient().createClient();
return runCommand(args);
} finally {
if (yarnClient != null) {
yarnClient.close();
}
if (webServiceClient != null) {
webServi... | @Test(timeout = 5000l)
public void testUnknownApplicationId() throws Exception {
YarnClient mockYarnClient = createMockYarnClientUnknownApp();
LogsCLI cli = new LogsCLIForTest(mockYarnClient);
cli.setConf(conf);
int exitCode = cli.run(new String[] { "-applicationId",
ApplicationId.newInstance... |
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
return usage(args);
}
String action = args[0];
String name = args[1];
int result;
if (A_LOAD.equals(action)) {
result = loadClass(name);
} else if (A_CREATE.equals(action)) {
//first load t... | @Test
public void testLoadFindsSelf() throws Throwable {
run(FindClass.SUCCESS,
FindClass.A_LOAD, "org.apache.hadoop.util.TestFindClass");
} |
@Override
protected List<Object[]> rows() {
List<Object[]> rows = new ArrayList<>(mappings.size());
for (Mapping mapping : mappings) {
Map<String, String> options;
if (!securityEnabled) {
options = mapping.options();
} else {
option... | @Test
public void test_rows_dataconnection() {
// given
Mapping mapping = new Mapping(
"table-name",
new String[]{"external-schema", "table-external-name"},
"some-dc",
null,
null,
emptyList(),
... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testUnpartitionedBucketString() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
BucketFunction.BucketString function = new BucketFunction.BucketString();
UserDefinedScalarFunc udf = toUDF(function, expressions(intLit(5), fiel... |
@Override
@Nullable
public V put(@Nullable K key, @Nullable V value) {
return put(key, value, true);
} | @Test
void shouldApplySupplementalHash() {
Integer key = 123;
this.map.put(key, "123");
assertNotEquals(this.map.getSupplementalHash(), key.hashCode());
assertNotEquals(this.map.getSupplementalHash() >> 30 & 0xFF, 0);
} |
@Override
public Object clone() {
MultiMergeJoinMeta retval = (MultiMergeJoinMeta) super.clone();
int nrKeys = keyFields == null ? 0 : keyFields.length;
int nrSteps = inputSteps == null ? 0 : inputSteps.length;
retval.allocateKeys( nrKeys );
retval.allocateInputSteps( nrSteps );
System.arrayco... | @Test
public void cloneTest() throws Exception {
MultiMergeJoinMeta meta = new MultiMergeJoinMeta();
meta.allocateKeys( 2 );
meta.allocateInputSteps( 3 );
meta.setKeyFields( new String[] { "key1", "key2" } );
meta.setInputSteps( new String[] { "step1", "step2", "step3" } );
// scalars should b... |
public static boolean isUnderDeviceRootNode(ResourceId path) {
int rootIdx = ResourceIds.startsWithRootNode(path) ? 0 : -1;
return path.nodeKeys().size() >= rootIdx + 3 &&
DEVICE_SCHEMA.equals(path.nodeKeys().get(rootIdx + DEVICE_INDEX).schemaId()) &&
(path.nodeKeys().get... | @Test
public void testDeviceSubtreeEventTest() {
// root relative ResourceId used by DynamicConfigEvent
ResourceId evtDevice = ResourceId.builder()
.addBranchPointSchema(DEVICES_NAME, DCS_NAMESPACE)
.addBranchPointSchema(DEVICE_NAME, DCS_NAMESPACE)
... |
public PipelineGroups getLocal() {
PipelineGroups locals = new PipelineGroups();
for (PipelineConfigs pipelineConfigs : this) {
PipelineConfigs local = pipelineConfigs.getLocal();
if (local != null)
locals.add(local);
}
return locals;
} | @Test
public void shouldGetLocalPartsWhenOriginIsRepo() {
PipelineConfigs defaultGroup = createGroup("defaultGroup", createPipelineConfig("pipeline1", "stage1"));
defaultGroup.setOrigins(new RepoConfigOrigin());
PipelineGroups groups = new PipelineGroups(defaultGroup);
assertThat(gro... |
@Override
protected void setProperties(Map<String, String> properties) throws DdlException {
Preconditions.checkState(properties != null);
for (String key : properties.keySet()) {
if (!DRIVER_URL.equals(key) && !URI.equals(key) && !USER.equals(key) && !PASSWORD.equals(key)
... | @Test(expected = DdlException.class)
public void testWithoutURI() throws Exception {
Map<String, String> configs = getMockConfigs();
configs.remove(JDBCResource.URI);
JDBCResource resource = new JDBCResource("jdbc_resource_test");
resource.setProperties(configs);
} |
public static GSBlobIdentifier parseUri(URI uri) {
Preconditions.checkArgument(
uri.getScheme().equals(GSFileSystemFactory.SCHEME),
String.format("URI scheme for %s must be %s", uri, GSFileSystemFactory.SCHEME));
String finalBucketName = uri.getAuthority();
if (S... | @Test(expected = IllegalArgumentException.class)
public void shouldFailToParseUriMissingBucketName() {
BlobUtils.parseUri(URI.create("gs:///foo/bar"));
} |
public static <K> KTableHolder<K> build(
final KTableHolder<K> left,
final KTableHolder<K> right,
final TableTableJoin<K> join
) {
final LogicalSchema leftSchema;
final LogicalSchema rightSchema;
if (join.getJoinType().equals(RIGHT)) {
leftSchema = right.getSchema();
rightSc... | @Test
public void shouldDoInnerJoin() {
// Given:
givenInnerJoin(R_KEY);
// When:
final KTableHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
verify(leftKTable).join(
same(rightKTable),
eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.value(... |
@Override
public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
return this.write(file, this.toHeaders(file, status, expect), status);
}
catch(ConflictException e) {
... | @Test
public void testWriteContentRangeTwoBytes() throws Exception {
final DAVWriteFeature feature = new DAVWriteFeature(session);
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final byte[... |
Map<String, String> getShardIterators() {
if (streamArn == null) {
streamArn = getStreamArn();
}
// Either return cached ones or get new ones via GetShardIterator requests.
if (currentShardIterators.isEmpty()) {
DescribeStreamResponse streamDescriptionResult
... | @Test
void shouldProgressThroughTreeWhenShardIteratorsAreRetrievedRepeatedly() throws Exception {
component.getConfiguration().setStreamIteratorType(StreamIteratorType.FROM_START);
Ddb2StreamEndpoint endpoint = (Ddb2StreamEndpoint) component.createEndpoint("aws2-ddbstreams://myTable");
Shard... |
public boolean isValidConnectionNameCharacter( char c ) {
return CONNECTION_NAME_INVALID_CHARACTERS.indexOf( c ) < 0;
} | @Test
public void testIsValidConnectionNameCharacterReturnsTrueOnValidCharacters() {
for ( char c : ACCEPTED_CHARACTERS_FULL_SET.toCharArray() ) {
assertTrue( fileNameParser.isValidConnectionNameCharacter( c ) );
}
} |
@Override
public AppResponse process(Flow flow, ConfirmRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
var authAppSession = appSessionService.getSession(request.getAuthSessionId());
if (!isAppSessionAuthenticated(authAppSession) || !request.getUserAppId().eq... | @Test
public void processHasOidcSession() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
authAppSession.setEidasUit(false);
authAppSession.setOidcSessionId("test");
authAppSession.setAction(null);
when(oidcClient.confirmOidc(authAppSession.getAccountId(), mo... |
public Result parse(final String string) throws DateNotParsableException {
return this.parse(string, new Date());
} | @Test
public void testLast4hours() throws Exception {
DateTime reference = DateTime.now(DateTimeZone.UTC);
NaturalDateParser.Result last4 = naturalDateParser.parse("last 4 hours", reference.toDate());
assertThat(last4.getFrom()).as("from should be exactly 4 hours in the past").isEqualTo(refe... |
@InvokeOnHeader(Web3jConstants.ETH_SIGN)
void ethSign(Message message) throws IOException {
String address = message.getHeader(Web3jConstants.ADDRESS, configuration::getAddress, String.class);
String sha3HashOfDataToSign = message.getHeader(Web3jConstants.SHA3_HASH_OF_DATA_TO_SIGN,
c... | @Test
public void ethSignTest() throws Exception {
EthSign response = Mockito.mock(EthSign.class);
Mockito.when(mockWeb3j.ethSign(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getSignature()).thenReturn("test");
... |
@InvokeOnHeader(Web3jConstants.ETH_SUBMIT_HASHRATE)
void ethSubmitHashrate(Message message) throws IOException {
String hashrate = message.getHeader(Web3jConstants.ETH_HASHRATE, configuration::getHashrate, String.class);
String clientId = message.getHeader(Web3jConstants.CLIENT_ID, configuration::ge... | @Test
public void ethSubmitHashrateTest() throws Exception {
EthSubmitHashrate response = Mockito.mock(EthSubmitHashrate.class);
Mockito.when(mockWeb3j.ethSubmitHashrate(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.submi... |
@Udf
public <T> Map<String, T> union(
@UdfParameter(description = "first map to union") final Map<String, T> map1,
@UdfParameter(description = "second map to union") final Map<String, T> map2) {
final List<Map<String, T>> nonNullInputs =
Stream.of(map1, map2)
.filter(Objects::nonNull)... | @Test
public void shouldUnionNonEmptyMaps() {
final Map<String, String> input1 = Maps.newHashMap();
input1.put("foo", "spam");
input1.put("bar", "baloney");
final Map<String, String> input2 = Maps.newHashMap();
input2.put("one", "apple");
input2.put("two", "banana");
input2.put("three", "... |
@Override
public Object nextEntry() throws IOException {
return null;
} | @Test
public void testNextEntry() throws IOException {
assertNull( inStream.nextEntry() );
} |
public List<String> getInsertColumnNames() {
return getSqlStatement().getSetAssignment().map(this::getColumnNamesForSetAssignment).orElseGet(() -> getColumnNamesForInsertColumns(getSqlStatement().getColumns()));
} | @Test
void assertGetInsertColumnNamesForSetAssignmentForMySQL() {
MySQLInsertStatement insertStatement = new MySQLInsertStatement();
List<ColumnSegment> columns = new LinkedList<>();
columns.add(new ColumnSegment(0, 0, new IdentifierValue("col")));
ColumnAssignmentSegment insertState... |
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (existsInTfsJar(name)) {
return jarClassLoader.loadClass(name);
}
return super.loadClass(name);
} | @Test
public void canLoadClassFromParent() throws Exception {
assertThat(nestedJarClassLoader.loadClass(this.getClass().getCanonicalName()))
.isNotNull()
.hasPackage(this.getClass().getPackageName());
assertThat(nestedJarClassLoader.loadClass(this.getClass().getCanoni... |
ConcurrentPublication addPublication(final String channel, final int streamId)
{
clientLock.lock();
try
{
ensureActive();
ensureNotReentrant();
final long registrationId = driverProxy.addPublication(channel, streamId);
stashedChannelByRegistra... | @Test
void shouldNotPreTouchLogBuffersForPublicationIfDisabled()
{
final int streamId = -53453894;
final String channel = "aeron:ipc?alias=test";
final long publicationId = 113;
final String logFileName = SESSION_ID_2 + "-log";
context.preTouchMappedMemory(false);
... |
protected int compareDataNode(final DatanodeDescriptor a,
final DatanodeDescriptor b, boolean isBalanceLocal) {
boolean toleranceLimit = Math.max(a.getDfsUsedPercent(), b.getDfsUsedPercent())
< balancedSpaceToleranceLimit;
if (a.equals(b)
|| (toleranceLimit && Math.abs(a.getDfsUsedPercent... | @Test
public void testChooseSimilarDataNode() {
DatanodeDescriptor[] tolerateDataNodes;
DatanodeStorageInfo[] tolerateStorages;
int capacity = 3;
Collection<Node> allTolerateNodes = new ArrayList<>(capacity);
String[] ownerRackOfTolerateNodes = new String[capacity];
for (int i = 0; i < capaci... |
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, CreateDownloadShareRequest options, final PasswordCallback callback) throws BackgroundException {
try {
if(log.isDebugEnabled()) {
log.debug(String.format("Create download share for %s", file));
... | @Test
public void testEncrypted() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).createRoom(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.T... |
public void meddle(MigrationHistory migrationHistory) {
// change last migration number on specific cases
migrationHistory.getLastMigrationNumber()
.ifPresent(migrationNumber -> {
Long newMigrationNumber = meddledSteps.get(migrationNumber);
if (newMigrationNumber != null) {
Regis... | @Test
public void no_effect_if_no_last_migration_number() {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.empty());
underTest.meddle(migrationHistory);
verify(migrationHistory).getLastMigrationNumber();
verifyNoMoreInteractions(migrationHistory, migrationSteps);
} |
@Override
public void onLeave(Class<? extends State> newState) {
if (!StateWithExecutionGraph.class.isAssignableFrom(newState)) {
// we are leaving the StateWithExecutionGraph --> we need to dispose temporary services
operatorCoordinatorHandler.disposeAllOperatorCoordinators();
... | @Test
void testOperatorCoordinatorShutdownOnLeave() throws Exception {
try (MockStateWithExecutionGraphContext context =
new MockStateWithExecutionGraphContext()) {
final TestingOperatorCoordinatorHandler testingOperatorCoordinatorHandler =
new TestingOperato... |
String loadAll(int n) {
return loadAllQueries.computeIfAbsent(n, loadAllFactory);
} | @Test
public void testLoadAllIsEscaped() {
Queries queries = new Queries(mappingEscape, idColumnEscape, columnMetadataEscape);
String result = queries.loadAll(2);
assertEquals("SELECT * FROM \"my\"\"mapping\" WHERE \"i\"\"d\" IN (?, ?)", result);
} |
@Udf(description = "Subtracts a duration from a time")
public Time timeSub(
@UdfParameter(description = "A unit of time, for example SECOND or HOUR") final TimeUnit unit,
@UdfParameter(
description = "An integer number of intervals to subtract") final Integer interval,
@UdfParameter(descri... | @Test
public void shouldAddToTime() {
// When:
assertThat(udf.timeSub(TimeUnit.MILLISECONDS, 50, new Time(1000)).getTime(), is(950L));
assertThat(udf.timeSub(TimeUnit.DAYS, 2, new Time(1000)).getTime(), is(1000L));
assertThat(udf.timeSub(TimeUnit.DAYS, -2, new Time(1000)).getTime(), is(1000L));
as... |
public SchemaKStream<K> selectKey(
final FormatInfo valueFormat,
final List<Expression> keyExpression,
final Optional<KeyFormat> forceInternalKeyFormat,
final Stacker contextStacker,
final boolean forceRepartition
) {
final boolean keyFormatChange = forceInternalKeyFormat.isPresent()... | @Test(expected = KsqlException.class)
public void shouldThrowOnRepartitionByMissingField() {
// Given:
final PlanNode logicalPlan = givenInitialKStreamOf(
"SELECT col0, col2, col3 FROM test1 PARTITION BY not_here EMIT CHANGES;");
final UserRepartitionNode repartitionNode = (UserRepartitionNode) lo... |
public void updateCheckboxes( EnumSet<RepositoryFilePermission> permissionEnumSet ) {
updateCheckboxes( false, permissionEnumSet );
} | @Test
public void testUpdateCheckboxesAllPermissionsAppropriateTrue() {
permissionsCheckboxHandler.updateCheckboxes( true, EnumSet.of( RepositoryFilePermission.ALL ) );
verify( readCheckbox, times( 1 ) ).setChecked( true );
verify( writeCheckbox, times( 1 ) ).setChecked( true );
verify( deleteCheckbox... |
public static String removeHtmlAttr(String content, String... attrs) {
String regex;
for (final String attr : attrs) {
// (?i) 表示忽略大小写
// \s* 属性名前后的空白符去除
// [^>]+? 属性值,至少有一个非>的字符,>表示标签结束
// \s+(?=>) 表示属性值后跟空格加>,即末尾的属性,此时去掉空格
// (?=\s|>) 表示属性值后跟空格(属性后还有别的属性)或者跟>(最后一个属性)
regex = StrUtil.f... | @Test
public void issueI6YNTFTest() {
String html = "<html><body><div class=\"a1 a2\">hello world</div></body></html>";
String cleanText = HtmlUtil.removeHtmlAttr(html,"class");
assertEquals("<html><body><div>hello world</div></body></html>", cleanText);
html = "<html><body><div class=a1>hello world</div></bo... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
new BrickAttributesFinderFeature(session).find(file);
return true;
}
catch(NotfoundException e) {
return false;
}
} | @Test
public void testFindNotFound() throws Exception {
assertFalse(new BrickFindFeature(session).find(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file))));
} |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowLogicalTablesStatement sqlStatement, final ContextManager contextManager) {
DialectDatabaseMetaData dialectDatabaseMetaData = new DatabaseTypeRegistry(database.getProtocolType()).getDialectDatabaseMetaData();
String schemaName = ... | @Test
void assertRowDataWithFullAndLike() {
Collection<LocalDataQueryResultRow> actual = executor.getRows(new ShowLogicalTablesStatement(true, null, "t_order_%"), mock(ContextManager.class));
assertThat(actual.size(), is(1));
LocalDataQueryResultRow row = actual.iterator().next();
as... |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testParseReverseDateRangeWithoutYearAndDay_645() throws ParseException {
DateRange dateRange = dateRangeParser.getRange("Aug 10-Jan");
assertFalse(dateRange.isInRange(getCalendar(2016, Calendar.AUGUST, 9)));
assertTrue(dateRange.isInRange(getCalendar(2016, Calendar.AUGUST, ... |
public SourceRecordJson(@Nullable SourceRecord sourceRecord) {
if (sourceRecord == null) {
throw new IllegalArgumentException();
}
this.value = (Struct) sourceRecord.value();
if (this.value == null) {
this.event = new Event(null, null, null);
} else {
Event.Metadata metadata = th... | @Test
public void testSourceRecordJson() {
SourceRecord record = buildSourceRecord();
SourceRecordJson json = new SourceRecordJson(record);
String jsonString = json.toJson();
String expectedJson =
"{\"metadata\":"
+ "{\"connector\":\"test-connector\",\"version\":\"version-connect... |
public Fetch<K, V> collectFetch() {
return fetchCollector.collectFetch(fetchBuffer);
} | @Test
public void testFetchRequestInternalError() {
buildFetcher();
makeFetchRequestWithIncompleteRecord();
try {
collectFetch();
fail("collectFetch should have thrown a KafkaException");
} catch (KafkaException e) {
assertTrue(e.getMessage().start... |
public static Optional<PMMLModel> getPMMLModel(String fileName, String modelName, PMMLRuntimeContext pmmlContext) {
logger.trace("getPMMLModel {} {}", fileName, modelName);
String fileNameToUse = !fileName.endsWith(PMML_SUFFIX) ? fileName + PMML_SUFFIX : fileName;
return getPMMLModels(pmmlContex... | @Test
void getPMMLModelFromClassLoader() {
modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME);
KiePMMLModelFactory kiePmmlModelFactory = PMMLLoaderUtils.loadKiePMMLModelFactory(modelLocalUriId,
... |
@JsonProperty("progress")
public int progress() {
if (indices.isEmpty()) {
return 100; // avoid division by zero. No indices == migration is immediately done
}
final BigDecimal sum = indices.stream()
.filter(i -> i.progress() != null)
.map(RemoteR... | @Test
void testProgressOneIndexNotStarted() {
final RemoteReindexMigration migration = withIndices(
index("one", RemoteReindexingMigrationAdapter.Status.NOT_STARTED)
);
Assertions.assertThat(migration.progress()).isEqualTo(0);
} |
@Override
public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext)
{
doEvaluateDisruptContext(request, requestContext);
return _client.sendRequest(request, requestContext);
} | @Test
public void testSendRequest10()
{
when(_builder.build()).thenReturn(_request);
when(_controller.getDisruptContext(any(String.class), any(ResourceMethod.class))).thenReturn(_disrupt);
_client.sendRequest(_builder, _behavior);
verify(_underlying, times(1)).sendRequest(eq(_request), any(RequestCo... |
protected JobMeta instantiateJobMeta() {
return new JobMeta();
} | @Test
public void testInstantiateJobMeta() {
JobMeta jobMeta = zipService.instantiateJobMeta();
assertNotNull( jobMeta );
} |
public static int compare(Date date1, Date date2) {
return CompareUtil.compare(date1, date2);
} | @Test
public void compareTest() {
final Date date1 = DateUtil.parse("2021-04-13 23:59:59.999");
final Date date2 = DateUtil.parse("2021-04-13 23:59:10");
assertEquals(1, DateUtil.compare(date1, date2));
assertEquals(1, DateUtil.compare(date1, date2, DatePattern.NORM_DATETIME_PATTERN));
assertEquals(0, DateU... |
public static BadRequestException userAlreadyExists(String userName) {
return new BadRequestException("user already exists for userName:%s", userName);
} | @Test
public void testUserAlreadyExists(){
BadRequestException userAlreadyExists = BadRequestException.userAlreadyExists("user");
assertEquals("user already exists for userName:user", userAlreadyExists.getMessage());
} |
@VisibleForTesting
void initializeForeachArtifactRollup(
ForeachStepOverview foreachOverview,
ForeachStepOverview prevForeachOverview,
String foreachWorkflowId) {
Set<Long> iterationsToRunInNewRun =
foreachOverview.getIterationsToRunFromDetails(prevForeachOverview);
WorkflowRollupOve... | @Test
public void testGetAggregatedRollupFromIterationsNotManyUneven() {
ArgumentCaptor<List<Long>> captor = ArgumentCaptor.forClass(List.class);
Set<Long> iterations = LongStream.rangeClosed(1, 3).boxed().collect(Collectors.toSet());
doReturn(Collections.singletonList(new WorkflowRollupOverview()))
... |
public Set<ModuleState> getAllModuleStates() {
reBuildModuleState();
return new HashSet<>(moduleStates.values());
} | @Test
void testGetAllModuleStates() {
assertEquals(2, ModuleStateHolder.getInstance().getAllModuleStates().size());
} |
@Override
@PublicAPI(usage = ACCESS)
public boolean isAnnotatedWith(Class<? extends Annotation> annotationType) {
return isAnnotatedWith(annotationType.getName());
} | @Test
public void isAnnotatedWith_predicate() {
assertThat(importClassWithContext(Parent.class)
.isAnnotatedWith(DescribedPredicate.alwaysTrue()))
.as("predicate matches").isTrue();
assertThat(importClassWithContext(Parent.class)
.isAnnotatedWith(Descr... |
@Override
public ProcessingResult process(ReplicationTask task) {
try {
EurekaHttpResponse<?> httpResponse = task.execute();
int statusCode = httpResponse.getStatusCode();
Object entity = httpResponse.getEntity();
if (logger.isDebugEnabled()) {
... | @Test
public void testBatchableTaskNetworkFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
replicationClient.withNetworkError(1);
ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM)
{
return;
}
var message = event.getMessage();
if (FISHING_CATCH_REGEX.matcher(message).find())
{
session.setLastFishCaught(Instant.now());
spotOverlay.setHidden(false);
fishingSpotMinimapOve... | @Test
public void testAnglerfish()
{
ChatMessage chatMessage = new ChatMessage();
chatMessage.setType(ChatMessageType.SPAM);
chatMessage.setMessage("You catch an Anglerfish.");
fishingPlugin.onChatMessage(chatMessage);
assertNotNull(fishingPlugin.getSession().getLastFishCaught());
} |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentExecutor,
TokenSecretAuthData authData,
PhotosContainerResource data)
throws Exception {
if (data == null) {
// Nothing to do
return ImportResult.OK;
}
BackblazeDataTransferC... | @Test
public void testEmptyPhotosAndAlbums() throws Exception {
PhotosContainerResource data = mock(PhotosContainerResource.class);
when(data.getAlbums()).thenReturn(new ArrayList<>());
when(data.getPhotos()).thenReturn(new ArrayList<>());
BackblazePhotosImporter sut =
new BackblazePhotosImpo... |
public CosmosDbContainerOperations createContainerIfNotExistAndGetContainerOperations(
final String containerId, final String containerPartitionKeyPath, final ThroughputProperties throughputProperties,
final IndexingPolicy indexingPolicy) {
CosmosDbUtils.validateIfParameterIsNotEmpty(con... | @Test
void createContainerIfNotExistAndGetContainerOperations() {
final CosmosAsyncDatabase database = mock(CosmosAsyncDatabase.class);
final CosmosAsyncContainer containerNew = mock(CosmosAsyncContainer.class);
final CosmosAsyncContainer containerExisting = mock(CosmosAsyncContainer.class);... |
public GetShardIteratorRequest request(String stream, Shard shard) {
for (Specification specification : specifications) {
if (specification.matches(shard)) {
return specification.request(stream, shard);
}
}
return defaultRequest(stream, shard);
} | @Test
public void unspecified() {
assertEquals(
new GetShardIteratorRequest()
.withShardId(SHARD3.getShardId())
.withStreamName(STREAM)
.withShardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER)
... |
@Override
public Object read(final PostgreSQLPacketPayload payload, final int parameterValueLength) {
byte[] bytes = new byte[parameterValueLength];
payload.getByteBuf().readBytes(bytes);
String result = new String(bytes);
return new PostgreSQLTypeUnspecifiedSQLParameter(result);
... | @Test
void assertRead() {
String timestampStr = "2020-08-23 15:57:03+08";
int expectedLength = 4 + timestampStr.length();
ByteBuf byteBuf = ByteBufTestUtils.createByteBuf(expectedLength);
byteBuf.writeInt(timestampStr.length());
byteBuf.writeCharSequence(timestampStr, Standar... |
@Override
public void deleteTenant(Long id) {
// 校验存在
validateUpdateTenant(id);
// 删除
tenantMapper.deleteById(id);
} | @Test
public void testDeleteTenant_system() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackageId(PACKAGE_ID_SYSTEM));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbTenant.getId();
// 调用, 并断言异常
assertServiceE... |
@Override
public ScalarOperator visitSubfield(SubfieldOperator operator, Void context) {
return shuttleIfUpdate(operator);
} | @Test
void testSubfieldOperator() {
ColumnRefOperator column1 = new ColumnRefOperator(1, INT, "id", true);
SubfieldOperator operator = new SubfieldOperator(column1, INT, Lists.newArrayList("a"));
{
ScalarOperator newOperator = shuttle.visitSubfield(operator, null);
as... |
public static RocketMQLogCollectClient getRocketMqLogCollectClient() {
return ROCKET_MQ_LOG_COLLECT_CLIENT;
} | @Test
public void testGetRocketMqLogCollectClient() {
Assertions.assertEquals(LoggingRocketMQPluginDataHandler.getRocketMqLogCollectClient().getClass(), RocketMQLogCollectClient.class);
} |
public static Map<String, Object> merge(Map<String, Object> a, Map<String, Object> b) {
if (a == null && b == null) {
return null;
}
if (a == null || a.isEmpty()) {
return copyMap(b);
}
if (b == null || b.isEmpty()) {
return copyMap(a);
... | @SuppressWarnings("unchecked")
@Test
void merge() {
Map<String, Object> a = Map.of(
"map", Map.of(
"map_a", "a",
"map_b", "b",
"map_c", "c"
),
"string", "a",
"int", 1,
"lists", Collections.singlet... |
@GetMapping("/plugin/deleteAll")
public Mono<String> deleteAll() {
LOG.info("delete all apache shenyu local plugin");
subscriber.refreshPluginDataAll();
return Mono.just(Constants.SUCCESS);
} | @Test
public void testDeleteAll() throws Exception {
final String[] testPluginName = {"testDeleteAllPluginName", "testDeleteAllPluginName2"};
Arrays.stream(testPluginName).map(s ->
new PluginData("id", s, null, null, null, null))
.forEach(subscriber::onSubscribe);
... |
@Override
public void lock() {
try {
lockInterruptibly(-1, null);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
} | @Test
public void testAutoExpire() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
RedissonClient r = createInstance();
Thread t = new Thread() {
@Override
public void run() {
RLock lock = r.getSpinLock("lock");
... |
@Override
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch) {
return offsetsForTimes(timestampsToSearch, Duration.ofMillis(defaultApiTimeoutMs));
} | @Test
public void testOffsetsForTimesWithZeroTimeout() {
consumer = newConsumer();
TopicPartition tp = new TopicPartition("topic1", 0);
Map<TopicPartition, OffsetAndTimestamp> expectedResult = Collections.singletonMap(tp, null);
Map<TopicPartition, Long> timestampToSearch = Collectio... |
public static int intOrZero(Integer value) {
if (value == null) {
return 0;
}
return value;
} | @Test
public void testNullSafeInt() {
assertEquals(0, Apiary.intOrZero(null));
Integer value = 82348902;
assertEquals(value.intValue(), Apiary.intOrZero(value));
} |
@Override
public Map<PCollection<?>, ReplacementOutput> mapOutputs(
Map<TupleTag<?>, PCollection<?>> outputs, PCollection<T> newOutput) {
return ReplacementOutputs.singleton(outputs, newOutput);
} | @Test
public void mapOutputsSucceeds() {
PCollection<Long> original = pipeline.apply("Original", GenerateSequence.from(0));
PCollection<Long> replacement = pipeline.apply("Replacement", GenerateSequence.from(0));
Map<PCollection<?>, ReplacementOutput> mapping =
factory.mapOutputs(PValues.expandOut... |
Plugin create(Options.Plugin plugin) {
try {
return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument());
} catch (IOException | URISyntaxException e) {
throw new CucumberException(e);
}
} | @Test
void instantiates_custom_string_arg_plugin() {
PluginOption option = parse(WantsString.class.getName() + ":hello");
WantsString plugin = (WantsString) fc.create(option);
assertThat(plugin.arg, is(equalTo("hello")));
} |
@Override
public void commitSync() {
commitSync(Duration.ofMillis(defaultApiTimeoutMs));
} | @Test
public void testCommitSyncAwaitsCommitAsyncCompletionWithNonEmptyOffsets() {
final TopicPartition tp = new TopicPartition("foo", 0);
final CompletableFuture<Void> asyncCommitFuture = setUpConsumerWithIncompleteAsyncCommit(tp);
// Mock to complete sync event
completeCommitSyncA... |
@VisibleForTesting
LoadingCache<String, AlluxioURI> getPathResolverCache() {
return mPathResolverCache;
} | @Test
@DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu")
@Ignore
public void pathTranslation() {
final LoadingCache<String, AlluxioURI> resolver = mFuseFs.getPathResolverCache();
AlluxioURI expected = new AlluxioURI(TEST_ROOT_PATH);
AlluxioURI actual = resolver.apply("/");
... |
public Set<ContentPackInstallation> findByContentPackId(ModelId id) {
final DBQuery.Query query = DBQuery.is(ContentPackInstallation.FIELD_CONTENT_PACK_ID, id);
try (final DBCursor<ContentPackInstallation> installations = dbCollection.find(query)) {
return ImmutableSet.copyOf((Iterator<Conte... | @Test
@MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json")
public void findByContentPackIdWithInvalidId() {
final Set<ContentPackInstallation> contentPacks = persistenceService.findByContentPackId(ModelId.of("does-not-exist"));
assertThat(contentPacks).isEmpty();
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldSupportExplicitEmitFinalOnBareQuery() {
// Given:
final SingleStatementContext stmt =
givenQuery("SELECT * FROM TEST1 EMIT FINAL;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat("Should be push", result.isPullQuery(),... |
public boolean validateTree(ValidationContext validationContext) {
validate(validationContext);
boolean isValid = errors().isEmpty();
for (JobConfig jobConfig : this) {
isValid = jobConfig.validateTree(validationContext) && isValid;
}
return isValid;
} | @Test
public void shouldReturnFalseIfAnyDescendentIsInvalid() {
JobConfig jobConfig = mock(JobConfig.class);
when(jobConfig.validateTree(any(PipelineConfigSaveValidationContext.class))).thenReturn(false);
JobConfigs jobConfigs = new JobConfigs(jobConfig);
boolean isValid = jobConfig... |
public void eval(Object... args) throws HiveException {
// When the parameter is (Integer, Array[Double]), Flink calls udf.eval(Integer,
// Array[Double]), which is not a problem.
// But when the parameter is a single array, Flink calls udf.eval(Array[Double]),
// at this point java's v... | @Test
public void testStack() throws Exception {
Object[] constantArgs = new Object[] {2, null, null, null, null};
DataType[] dataTypes =
new DataType[] {
DataTypes.INT(),
DataTypes.STRING(),
DataTypes.STRING(),
... |
public static FunctionConfig convertFromDetails(FunctionDetails functionDetails) {
functionDetails = validateFunctionDetails(functionDetails);
FunctionConfig functionConfig = new FunctionConfig();
functionConfig.setTenant(functionDetails.getTenant());
functionConfig.setNamespace(function... | @Test
public void testFunctionConfigConvertFromDetails() {
String name = "test1";
String namespace = "ns1";
String tenant = "tenant1";
String classname = getClass().getName();
int parallelism = 3;
Map<String, String> userConfig = new HashMap<>();
userConfig.pu... |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void shouldPrintTablesList() {
// Given:
final KsqlEntityList entityList = new KsqlEntityList(ImmutableList.of(
new TablesList("e", ImmutableList.of(
new SourceInfo.Table("B", "t2", "JSON", "JSON", true),
new SourceInfo.Table("A", "t1", "KAFKA", "AVRO", false)
... |
@Override
public void onAction(Action action) {
if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
var menuAction = (MenuAction) action;
selected = menuAction.getMenuItem();
notifyChange();
}
} | @Test
void testOnAction() {
final var menuStore = new MenuStore();
final var view = mock(View.class);
menuStore.registerView(view);
verifyNoMoreInteractions(view);
// Menu should not react on content action ...
menuStore.onAction(new ContentAction(Content.COMPANY));
verifyNoMoreInteract... |
@Override
public int hashCode()
{
return Objects.hash(_elements, _metadata, _total, _pageIncrement);
} | @Test(dataProvider = "testHashCodeDataProvider")
public void testHashCode
(
boolean hasSameHashCode,
@Nonnull CollectionResult<TestRecordTemplateClass.Foo, TestRecordTemplateClass.Bar> collectionResult1,
@Nonnull CollectionResult<TestRecordTemplateClass.Foo, TestRecordTemplateClass... |
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {} | @Test
void testRemoveListener() {
configuration.removeListener(null, null);
configuration.removeListener(null, null, null);
} |
@SuppressWarnings("unchecked")
@Override
public <S extends StateStore> S getStateStore(final String name) {
final StateStore store = stateManager.getGlobalStore(name);
return (S) getReadWriteStore(store);
} | @Test
public void shouldNotAllowCloseForTimestampedKeyValueStore() {
when(stateManager.getGlobalStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME)).thenReturn(mock(TimestampedKeyValueStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME);
try... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.