focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public List<StorageObjectOrIOException> getObjects(List<GcsPath> gcsPaths) throws IOException {
if (gcsPaths.isEmpty()) {
return ImmutableList.of();
} else if (gcsPaths.size() == 1) {
GcsPath path = gcsPaths.get(0);
try {
StorageObject object = getObject(path);
return Immutable... | @Test
public void testGetObjects() throws IOException {
GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil();
Storage mockStorage = Mockito.mock(Storage.class);
gcsUtil.setStorageClient(mockStorage);
gcsUtil.setBatchRequestSupplier(FakeBatcher::new);
Storage.Objects mockStorageObjects =... |
public ConfigCheckResult checkConfig() {
Optional<Long> appId = getAppId();
if (appId.isEmpty()) {
return failedApplicationStatus(INVALID_APP_ID_STATUS);
}
GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDe... | @Test
public void checkConfig_whenGithubAppConfigurationNotComplete_shouldReturnFailedAppCheck() {
when(gitHubSettings.appId()).thenReturn(APP_ID);
ConfigCheckResult checkResult = configValidator.checkConfig();
assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(INCOMP... |
@Override
public Infinispan create(URI uri) {
try {
return new HotRod(HotRodURI.create(uri).toConfigurationBuilder().build());
} catch (Throwable t) {
// Not a Hot Rod URI
return null;
}
} | @Test
public void testHotRodInstantiationByConfiguration() {
HotRodConfiguration configuration = new HotRodConfigurationBuilder().build();
try (Infinispan infinispan = Infinispan.create(configuration)) {
assertTrue(infinispan instanceof HotRod);
}
} |
@Override
public Collection<RedisServer> masters() {
List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS);
return toRedisServersList(masters);
} | @Test
public void testMasters() {
Collection<RedisServer> masters = connection.masters();
assertThat(masters).hasSize(1);
} |
void truncateTable() throws KettleDatabaseException {
if ( !meta.isPartitioningEnabled() && !meta.isTableNameInField() ) {
// Only the first one truncates in a non-partitioned step copy
//
if ( meta.truncateTable()
&& ( ( getCopy() == 0 && getUniqueStepNrAcrossSlaves() == 0 ) || !Utils.isE... | @Test
public void testTruncateTable_off() throws Exception {
tableOutputSpy.truncateTable();
verify( db, never() ).truncateTable( anyString(), anyString() );
} |
public static int checkMaxBytesLength(long length) {
if (length < 0) {
throw new AvroRuntimeException("Malformed data. Length is negative: " + length);
}
if (length > MAX_ARRAY_VM_LIMIT) {
throw new UnsupportedOperationException(
"Cannot read arrays longer than " + MAX_ARRAY_VM_LIMIT +... | @Test
void testCheckMaxBytesLength() {
helpCheckSystemLimits(SystemLimitException::checkMaxBytesLength, MAX_BYTES_LENGTH_PROPERTY, ERROR_VM_LIMIT_BYTES,
"Bytes length 1024 exceeds maximum allowed");
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateFileConfigMaster(Long id) {
// 校验存在
validateFileConfigExists(id);
// 更新其它为非 master
fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));
// 更新
fileConfigMapper.updateById(new Fi... | @Test
public void testUpdateFileConfigMaster_success() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据
FileConfigDO masterFileConfig = randomFileConfigDO().setMaster(true);
fileConfigMa... |
@Bean
public PluginDataHandler sofaPluginDataHandler() {
return new SofaPluginDataHandler();
} | @Test
public void testSofaPluginDataHandler() {
applicationContextRunner.run(context -> {
PluginDataHandler handler = context.getBean("sofaPluginDataHandler", PluginDataHandler.class);
assertNotNull(handler);
}
);
} |
public static Expression and(Expression... expressions)
{
return and(Arrays.asList(expressions));
} | @Test
public void testAnd()
{
Expression a = name("a");
Expression b = name("b");
Expression c = name("c");
Expression d = name("d");
Expression e = name("e");
assertEquals(
ExpressionUtils.and(a, b, c, d, e),
and(and(and(a, b), an... |
@Override
public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) {
if (CollUtil.isEmpty(postIds)) {
return Collections.emptyList();
}
Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), UserPostDO::getUserId);
if (CollUtil.isEmpty(... | @Test
public void testUserListByPostIds() {
// 准备参数
Collection<Long> postIds = asSet(10L, 20L);
// mock user1 数据
AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L)));
userMapper.insert(user1);
userPostMapper.insert(new UserPostDO().setUserId(user1... |
@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException {
IOUtils.closeQuietly(in);
return Checksum.NONE;
} | @Test
public void compute() throws Exception {
final NullInputStream in = new NullInputStream(0L);
new DisabledChecksumCompute().compute(in, new TransferStatus());
assertEquals(-1, in.read());
assertEquals(-1, in.read());
} |
@Udf(description = "Converts the number of days since 1970-01-01 00:00:00 UTC/GMT to a date "
+ "string using the given format pattern. The format pattern should be in the format"
+ " expected by java.time.format.DateTimeFormatter")
public String formatDate(
@UdfParameter(
description = "T... | @Test
public void shouldReturnNullOnNullDate() {
// When:
final String result = udf.formatDate(null, "yyyy-MM-dd");
// Then:
assertThat(result, is(nullValue()));
} |
@VisibleForTesting
WxMaService getWxMaService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMaService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MINI_APP.getType(), userType);
if (client != null && Objects.equals(client.... | @Test
public void testGetWxMaService_clientDisable() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 数据
SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())
.setUserType(userTyp... |
public static Expression convert(Filter[] filters) {
Expression expression = Expressions.alwaysTrue();
for (Filter filter : filters) {
Expression converted = convert(filter);
Preconditions.checkArgument(
converted != null, "Cannot convert filter to Iceberg: %s", filter);
expression =... | @Test
public void testNestedInInsideNot() {
Not filter =
Not.apply(And.apply(EqualTo.apply("col1", 1), In.apply("col2", new Integer[] {1, 2})));
Expression converted = SparkFilters.convert(filter);
assertThat(converted).as("Expression should not be converted").isNull();
} |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
InvokeMode invokeMode = RpcUtils.getInvokeMode(invoker.getUrl(), invocation);
if (InvokeMode.SYNC == invokeMode) {
return syncInvoke(invoker, invocation);
} else {
return a... | @Test
public void testInvokeAsync() {
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
final Result result = mock(Result.class... |
@Override
public Optional<String> buildEstimatedCountSQL(final String qualifiedTableName) {
return Optional.of(String.format("SELECT TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '%s'", qualifiedTableName));
} | @Test
void assertBuilderEstimateCountSQLWithoutKeyword() {
Optional<String> actual = sqlBuilder.buildEstimatedCountSQL("t_order");
assertTrue(actual.isPresent());
assertThat(actual.get(), is("SELECT TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 't_order'")... |
@Override
public void stopTrackScreenOrientation() {
} | @Test
public void stopTrackScreenOrientation() {
mSensorsAPI.stopTrackScreenOrientation();
} |
@Override
public StatusOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class);
if(log.isDebugEnabl... | @Test
public void testWriteMultipart() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.T... |
@VisibleForTesting
static void validateIntervalFreshness(IntervalFreshness intervalFreshness) {
if (!NumberUtils.isParsable(intervalFreshness.getInterval())) {
throw new ValidationException(
String.format(
"The interval freshness value '%s' is an i... | @Test
void testIllegalIntervalFreshness() {
assertThatThrownBy(() -> validateIntervalFreshness(IntervalFreshness.ofMinute("2efedd")))
.isInstanceOf(ValidationException.class)
.hasMessageContaining(
"The interval freshness value '2efedd' is an illegal i... |
public static String localDateTimeToString(final LocalDateTime localDateTime) {
return DATE_TIME_FORMATTER.format(localDateTime);
} | @Test
public void testLocalDateTimeToString() {
LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 23, 50, 0, 0);
assertEquals("2020-01-01 23:50:00", DateUtils.localDateTimeToString(localDateTime));
} |
public static HL7v2Read readAllRequests() {
return new HL7v2Read();
} | @Test
public void testHL7v2IOFailedReadsByParameter() {
List<HL7v2ReadParameter> badReadParameters =
Arrays.asList(
HL7v2ReadParameter.of(
"metadata-foo", "projects/a/locations/b/datasets/c/hl7V2Stores/d/messages/foo"),
HL7v2ReadParameter.of(
"metada... |
public int deleteById(ObjectId id) {
final WriteResult<ContentPackInstallation, ObjectId> writeResult = dbCollection.removeById(id);
return writeResult.getN();
} | @Test
@MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json")
public void deleteById() {
final ObjectId objectId = new ObjectId("5b4c935b4b900a0000000001");
final int deletedContentPacks = persistenceService.deleteById(objectId);
final Set<ContentPackInstallation> contentP... |
void add(final long recordingId, final long recordingDescriptorOffset)
{
ensurePositive(recordingId, "recordingId");
ensurePositive(recordingDescriptorOffset, "recordingDescriptorOffset");
final int nextPosition = count << 1;
long[] index = this.index;
if (nextPosition > 0)
... | @Test
void addThrowsIllegalArgumentExceptionIfRecordingOffsetIsNegative()
{
assertThrows(IllegalArgumentException.class, () -> catalogIndex.add(1024, Integer.MIN_VALUE));
} |
public static StatementExecutorResponse execute(
final ConfiguredStatement<AssertSchema> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
return AssertExecutor.execute(
statement.getMaskedStat... | @Test
public void shouldAssertNotExistSchemaBySubject() {
// Given
final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.of("abc"), Optional.empty(), Optional.empty(), false);
final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement
.of(KsqlParser.PreparedSta... |
public void abortTransaction(long transactionId, boolean abortPrepared, String reason,
TxnCommitAttachment txnCommitAttachment,
List<TabletCommitInfo> finishedTablets,
List<TabletFailInfo> failedTablets)
throw... | @Test
public void testAbortTransaction() throws UserException {
DatabaseTransactionMgr masterDbTransMgr =
masterTransMgr.getDatabaseTransactionMgr(GlobalStateMgrTestUtil.testDbId1);
long txnId2 = lableToTxnId.get(GlobalStateMgrTestUtil.testTxnLable2);
masterDbTransMgr.abortT... |
public boolean isEnabled() {
BasicAuthConfiguration basicAuthConfiguration = configuration();
if (basicAuthConfiguration == null) {
return false;
}
return Boolean.TRUE.equals(basicAuthConfiguration.getEnabled()) && basicAuthConfiguration.getUsername() != null && basicAuthCon... | @Test
void initFromYamlConfig() throws TimeoutException {
assertThat(basicAuthService.isEnabled(), is(true));
assertConfigurationMatchesApplicationYaml();
awaitOssAuthEventApiCall("admin@kestra.io");
} |
@Override
public Object execute(String command, byte[]... args) {
for (Method method : this.getClass().getDeclaredMethods()) {
if (method.getName().equalsIgnoreCase(command)
&& Modifier.isPublic(method.getModifiers())
&& (method.getParameterTypes().len... | @Test
public void testExecute() {
Long s = (Long) connection.execute("ttl", "key".getBytes());
assertThat(s).isEqualTo(-2);
connection.execute("flushDb");
} |
@Override
public String toString() {
return String.format("Bulkhead '%s'", this.name);
} | @Test
public void testToString() {
String result = bulkhead.toString();
assertThat(result).isEqualTo("Bulkhead 'test'");
} |
@Override
public NodeId getMasterFor(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_ID_NULL);
return store.getMaster(networkId, deviceId);
} | @Test
public void getMasterFor() {
mastershipMgr1.setRole(NID_LOCAL, VDID1, MASTER);
mastershipMgr1.setRole(NID_OTHER, VDID2, MASTER);
assertEquals("wrong master:", NID_LOCAL, mastershipMgr1.getMasterFor(VDID1));
assertEquals("wrong master:", NID_OTHER, mastershipMgr1.getMasterFor(VD... |
public final void setStrictness(Strictness strictness) {
Objects.requireNonNull(strictness);
this.strictness = strictness;
} | @Test
public void testCapitalizedTrueFailWhenStrict() {
JsonReader reader = new JsonReader(reader("TRUE"));
reader.setStrictness(Strictness.STRICT);
IOException expected = assertThrows(IOException.class, reader::nextBoolean);
assertThat(expected)
.hasMessageThat()
.startsWith(
... |
static void maybeReportHybridDiscoveryIssue(PluginDiscoveryMode discoveryMode, PluginScanResult serviceLoadingScanResult, PluginScanResult mergedResult) {
SortedSet<PluginDesc<?>> missingPlugins = new TreeSet<>();
mergedResult.forEach(missingPlugins::add);
serviceLoadingScanResult.forEach(missin... | @Test
public void testServiceLoadNoPlugins() {
try (LogCaptureAppender logCaptureAppender = LogCaptureAppender.createAndRegister(Plugins.class)) {
Plugins.maybeReportHybridDiscoveryIssue(PluginDiscoveryMode.SERVICE_LOAD, empty, empty);
assertTrue(logCaptureAppender.getEvents().stream... |
public ResourceConfigs toResourceConfigs() {
final ResourceConfigs resourceConfigs = new ResourceConfigs();
for (Resource resource : this) {
resourceConfigs.add(new ResourceConfig(resource.getName()));
}
return resourceConfigs;
} | @Test
void shouldConvertResourceListToResourceConfigs() {
final Resources resources = new Resources(new Resource("foo"), new Resource("bar"));
final ResourceConfigs resourceConfigs = resources.toResourceConfigs();
assertThat(resourceConfigs.size()).isEqualTo(2);
assertThat(resource... |
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (!configured())
throw new IllegalStateException("Callback handler not configured");
for (Callback callback : callbacks) {
if (callback instanceof OAuthBearerTokenCallback)... | @Test
public void addsExtensions() throws IOException, UnsupportedCallbackException {
Map<String, String> options = new HashMap<>();
options.put("unsecuredLoginExtension_testId", "1");
OAuthBearerUnsecuredLoginCallbackHandler callbackHandler = createCallbackHandler(options, new MockTime());
... |
@Override
public SelResult childrenAccept(SelParserVisitor visitor, Object data) {
SelResult res = SelResult.NONE;
if (children != null) {
for (int i = 0; i < children.length; ++i) {
res = (SelResult) children[i].jjtAccept(visitor, data);
switch (res) {
case BREAK:
... | @Test
public void testVisitedBreakNode() {
root.jjtAddChild(breakNode, 2);
root.jjtAddChild(breakNode, 1);
root.jjtAddChild(breakNode, 0);
SelResult res = root.childrenAccept(null, null);
assertEquals(SelResult.BREAK, res);
assertArrayEquals(new int[] {1, 0, 0, 0, 0}, visited);
} |
public <T> Span nextSpanWithParent(SamplerFunction<T> samplerFunction, T arg,
@Nullable TraceContext parent) {
return _toSpan(parent, nextContext(samplerFunction, arg, parent));
} | @Test void nextSpanWithParent_overrideToMakeNewTrace() {
Span span;
try (Scope scope = currentTraceContext.newScope(context)) {
span = tracer.nextSpanWithParent(deferDecision(), false, null);
}
assertThat(span.context().parentId()).isNull();
} |
public static boolean getBool(String property, JsonNode node) {
Preconditions.checkArgument(node.has(property), "Cannot parse missing boolean: %s", property);
JsonNode pNode = node.get(property);
Preconditions.checkArgument(
pNode != null && !pNode.isNull() && pNode.isBoolean(),
"Cannot pars... | @Test
public void getBool() throws JsonProcessingException {
assertThatThrownBy(() -> JsonUtil.getBool("x", JsonUtil.mapper().readTree("{}")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing boolean: x");
assertThatThrownBy(() -> JsonUtil.getBool("x", JsonUtil.... |
@Override
public ConfigFileList responseMessageForConfigFiles(String responseBody) {
ConfigFilesResponseMessage response = codec.getGson().fromJson(responseBody, ConfigFilesResponseMessage.class);
return ConfigFileList.from(response.getFiles());
} | @Test
public void shouldReturnErrorWhenInvalidResponseJSON() {
assertTrue(handler.responseMessageForConfigFiles("{\"files\": null}").hasErrors());
assertTrue(handler.responseMessageForConfigFiles("{\"blah\": [\"file\"]}").hasErrors());
assertTrue(handler.responseMessageForConfigFiles("{}").h... |
@Override
public void clearLossHistoryStats(MdId mdName, MaIdShort maName,
MepId mepId) throws CfmConfigException {
throw new UnsupportedOperationException("Not yet implemented");
} | @Test
public void testClearAllLossHistoryStatsOnMep() throws CfmConfigException {
//TODO: Implement underlying method
try {
soamManager.clearLossHistoryStats(MDNAME1, MANAME1, MEPID1);
fail("Expecting UnsupportedOperationException");
} catch (UnsupportedOperationExcep... |
public String getString(String path) {
return ObjectConverter.convertObjectTo(get(path), String.class);
} | @Test public void
can_parse_json_attributes_starting_with_a_number() {
// Given
String json = "{\n" +
" \"6269f15a0bb9b1b7d86ae718e84cddcd\" : {\n" +
" \"attr1\":\"val1\",\n" +
" \"attr2\":\"val2\",\n" +
" ... |
@Override
public void metricChange(final KafkaMetric metric) {
if (!THROUGHPUT_METRIC_NAMES.contains(metric.metricName().name())
|| !StreamsMetricsImpl.TOPIC_LEVEL_GROUP.equals(metric.metricName().group())) {
return;
}
addMetric(
metric,
getQueryId(metric),
getTopic... | @Test
public void shouldIgnoreNonThroughputMetric() {
// When:
listener.metricChange(mockMetric(
"other-metric",
2D,
STREAMS_TAGS_TASK_1)
);
// Then:
assertThrows(AssertionError.class, () -> verifyAndGetMetric("other-metric", QUERY_ONE_TAGS));
} |
public static boolean isJavaIdentifier(String name) {
if (name == null) {
return false;
}
int size = name.length();
if (size < 1) {
return false;
}
if (Character.isJavaIdentifierStart(name.charAt(0))) {
for (int i = 1; i < size; i++) {
... | @Test
public void testIsJavaIdentifier() {
assertTrue(StringHelper.isJavaIdentifier("foo"));
assertFalse(StringHelper.isJavaIdentifier("foo.bar"));
assertFalse(StringHelper.isJavaIdentifier(""));
assertFalse(StringHelper.isJavaIdentifier(null));
} |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testInvalidSpdyHeadersFrameStreamId() throws Exception {
short type = 8;
byte flags = 0;
int length = 4;
int streamId = 0; // invalid stream identifier
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, fla... |
@Override
public Comparable convert(Comparable value) {
if (!(value instanceof CompositeValue)) {
throw new IllegalArgumentException("Cannot convert [" + value + "] to composite");
}
CompositeValue compositeValue = (CompositeValue) value;
Comparable[] components = compos... | @Test
public void testConversion() {
assertEquals(value(1), converter(INTEGER_CONVERTER).convert(value(1)));
assertEquals(value(1), converter(INTEGER_CONVERTER).convert(value("1")));
assertEquals(value(1, true), converter(INTEGER_CONVERTER, BOOLEAN_CONVERTER).convert(value(1, true)));
... |
@Override
public void start() {
if (isStarted()) return;
try {
ServerSocket socket = getServerSocketFactory().createServerSocket(
getPort(), getBacklog(), getInetAddress());
ServerListener<RemoteReceiverClient> listener = createServerListener(socket);
runner = createServerRunner(l... | @Test
public void testStartWhenAlreadyStarted() throws Exception {
appender.start();
appender.start();
assertEquals(1, runner.getStartCount());
} |
@Override
public YamlShardingCacheOptionsConfiguration swapToYamlConfiguration(final ShardingCacheOptionsConfiguration data) {
YamlShardingCacheOptionsConfiguration result = new YamlShardingCacheOptionsConfiguration();
result.setSoftValues(data.isSoftValues());
result.setInitialCapacity(data... | @Test
void assertSwapToYamlConfiguration() {
YamlShardingCacheOptionsConfiguration actual = new YamlShardingCacheOptionsConfigurationSwapper().swapToYamlConfiguration(new ShardingCacheOptionsConfiguration(true, 128, 1024));
assertTrue(actual.isSoftValues());
assertThat(actual.getInitialCapac... |
public ApplicationBuilder architecture(String architecture) {
this.architecture = architecture;
return getThis();
} | @Test
void architecture() {
ApplicationBuilder builder = new ApplicationBuilder();
builder.architecture("architecture");
Assertions.assertEquals("architecture", builder.build().getArchitecture());
} |
public static RuleDescriptionSectionContextDto of(String key, String displayName) {
return new RuleDescriptionSectionContextDto(key, displayName);
} | @Test
void check_of_with_key_is_empty() {
assertThatThrownBy(() -> RuleDescriptionSectionContextDto.of("", CONTEXT_DISPLAY_NAME))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(KEY_MUST_BE_SET_ERROR);
} |
@Override
public ParallelismAndInputInfos decideParallelismAndInputInfosForVertex(
JobVertexID jobVertexId,
List<BlockingResultInfo> consumedResults,
int vertexInitialParallelism,
int vertexMinParallelism,
int vertexMaxParallelism) {
checkArgument(... | @Test
void testParallelismAlreadyDecided() {
final DefaultVertexParallelismAndInputInfosDecider decider =
createDecider(MIN_PARALLELISM, MAX_PARALLELISM, DATA_VOLUME_PER_TASK);
AllToAllBlockingResultInfo allToAllBlockingResultInfo =
createAllToAllBlockingResultInfo(
... |
public String characterEncoding()
{
return characterEncoding;
} | @Test
void shouldReturnUsAsciiWhenCharacterEncodingNotSpecifiedForTypeChar() throws Exception
{
final String testXmlString =
"<types>" +
" <type name=\"testCharDefaultCharacterEncoding\" primitiveType=\"char\" length=\"5\"/>" +
"</types>";
final Map<String... |
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) {
final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace();
final String importerDMNName = ((Definitions) importElement.getParent()).getName(... | @Test
void nSandModelNameWithAlias() {
final Import i = makeImport("ns1", "aliased", "m1");
final List<QName> available = Arrays.asList(new QName("ns1", "m1"),
new QName("ns2", "m2"),
new QName("n... |
public static boolean isProcessAlive(long pid, String user) throws IOException {
if (ServerUtils.IS_ON_WINDOWS) {
return isWindowsProcessAlive(pid, user);
}
return isPosixProcessAlive(pid, user);
} | @Test
public void testIsProcessAlive() throws Exception {
// specific selected process should not be alive for a randomly generated user
String randomUser = RandomStringUtils.randomAlphanumeric(12);
// get list of few running processes
Collection<Long> pids = getRunningProcessIds(nu... |
public CoordinatorResult<TxnOffsetCommitResponseData, CoordinatorRecord> commitTransactionalOffset(
RequestContext context,
TxnOffsetCommitRequestData request
) throws ApiException {
validateTransactionalOffsetCommit(context, request);
final TxnOffsetCommitResponseData response = ne... | @Test
public void testGenericGroupTransactionalOffsetCommitWithUnknownGroupId() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
assertThrows(IllegalGenerationException.class, () -> context.commitTransactionalOffset(
new TxnOffsetCommi... |
@Bean
public RegisterClientServerDisruptorPublisher registerClientServerDisruptorPublisher(final List<ShenyuClientRegisterService> shenyuClientRegisterService, final DiscoveryService discoveryService) {
RegisterClientServerDisruptorPublisher publisher = RegisterClientServerDisruptorPublisher.getInstance();
... | @Test
public void testRegisterClientServerDisruptorPublisher() {
DiscoveryService discoveryService = mock(DiscoveryService.class);
List<ShenyuClientRegisterService> shenyuClientRegisterService = new ArrayList<>();
RegisterClientServerDisruptorPublisher publisher = registerCenterConfiguration... |
@Override
public List<MethodMetadata> parseAndValidateMetadata(Class<?> targetType) {
List<MethodMetadata> methodsMetadata = this.delegate.parseAndValidateMetadata(targetType);
for (final MethodMetadata metadata : methodsMetadata) {
final Type type = metadata.returnType();
if (!isReactive(type)) ... | @Test
void onlyReactiveReturnTypesSupported() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
Contract contract = new ReactiveDelegatingContract(new Contract.Default());
contract.parseAndValidateMetadata(TestSynchronousService.class);
});
} |
private <T> T accept(Expression<T> expr) {
return expr.accept(this);
} | @Test
public void testNot() throws Exception {
final Expr.Greater trueExpr = Expr.Greater.create(Expr.NumberValue.create(2), Expr.NumberValue.create(1));
final Expr.Greater falseExpr = Expr.Greater.create(Expr.NumberValue.create(1), Expr.NumberValue.create(2));
assertThat(Expr.Not.create(fa... |
@Override
public boolean hasNext() {
return supplyWithLock(
() -> {
if (cacheQueue.size() > 0) {
return true;
} else if (closed) {
return false;
} else {
waitCa... | @Test
void testHasNext() throws ExecutionException, InterruptedException {
CompletableFuture<Object> udfTrigger = new CompletableFuture<>();
CompletableFuture<Object> udfReadIteratorFinishIdentifier = new CompletableFuture<>();
CompletableFuture<Object> udfFinishTrigger = new CompletableFutu... |
@Override
public ColumnStatistic getColumnStatistic(Table table, String column) {
Preconditions.checkState(table != null);
// get Statistics Table column info, just return default column statistics
if (StatisticUtils.statisticTableBlackListCheck(table.getId())) {
return ColumnSt... | @Test
public void testGetColumnStatistic(@Mocked CachedStatisticStorage cachedStatisticStorage) {
Database db = connectContext.getGlobalStateMgr().getDb("test");
OlapTable table = (OlapTable) db.getTable("t0");
new Expectations() {
{
cachedStatisticStorage.getCol... |
public void updateQuarantineState(PartitionState newPartitionState,
PartitionState oldPartitionState, long clusterAvgLatency)
{
long quarantineLatency = Math.max((long) (clusterAvgLatency * _relativeLatencyLowThresholdFactor),
MIN_QUARANTINE_LATENCY_MS);
quarantineLatency = Math.min(MAX_QUARANTI... | @Test
public void testQuarantineNotEnabledInConfig()
{
setup(RelativeLoadBalancerStrategyFactory.DEFAULT_QUARANTINE_MAX_PERCENT, false, false);
PartitionState state = new PartitionStateTestDataBuilder()
.setTrackerClientStateMap(TrackerClientMockHelper.mockTrackerClients(2),
Arrays.asLi... |
@Override
public byte[] putIfAbsent(final Bytes key,
final byte[] valueAndTimestamp) {
final byte[] previous = wrapped().putIfAbsent(key, valueAndTimestamp);
if (previous == null) {
// then it was absent
log(key, rawValue(valueAndTimestamp), valu... | @Test
public void shouldReturnNullOnPutIfAbsentWhenNoPreviousValue() {
assertThat(store.putIfAbsent(hi, rawThere), is(nullValue()));
} |
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schams to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVis... | @Test
void visit5() {
String s5 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"c2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
assertEquals("c1.... |
public static Permission getPermission(String name, String serviceName, String... actions) {
PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName);
if (permissionFactory == null) {
throw new IllegalArgumentException("No permissions found for service: " + serviceName);... | @Test
public void getPermission_CountdownLatch() {
Permission permission = ActionConstants.getPermission("foo", CountDownLatchServiceUtil.SERVICE_NAME);
assertNotNull(permission);
assertTrue(permission instanceof CountDownLatchPermission);
} |
@Override
public Graph<Entity> resolveForInstallation(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Entity> entities) {
if (entity instanceof EntityV1) {
return resolveF... | @Test
@MongoDBFixtures({"LookupCacheFacadeTest.json", "LookupDataAdapterFacadeTest.json", "LookupTableFacadeTest.json"})
public void resolveEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("5adf24dd4b900a0fdb4e530d"))
.type(ModelTypes.LOOKUP_TABLE_V1)
... |
public static long deriveChainId(long v) {
if (v == LOWER_REAL_V || v == (LOWER_REAL_V + 1)) {
return 0L;
}
return (v - CHAIN_ID_INC) / 2;
} | @Test
void deriveChainIdWhenMainNet() {
long v = 37;
long chainId = TransactionUtils.deriveChainId(v);
assertEquals(1, chainId);
} |
public List<DataRecord> merge(final List<DataRecord> dataRecords) {
Map<DataRecord.Key, DataRecord> result = new HashMap<>();
dataRecords.forEach(each -> {
if (PipelineSQLOperationType.INSERT == each.getType()) {
mergeInsert(each, result);
} else if (PipelineSQLOp... | @Test
void assertInsertBeforeDelete() {
DataRecord beforeDataRecord = mockInsertDataRecord(1, 10, 50);
DataRecord afterDataRecord = mockDeleteDataRecord(1, 10, 50);
Collection<DataRecord> actual = groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRecord));
assertThat(actual.... |
static boolean differenceGreaterThan(
Instant preexistingExecutionTime, Instant potentiallyNewExecutionTime, Duration delta) {
final Duration difference =
Duration.between(preexistingExecutionTime, potentiallyNewExecutionTime).abs();
return difference.toMillis() > delta.toMillis();
} | @Test
void test_differenceGreaterThan() {
assertTrue(
differenceGreaterThan(clock.now(), clock.now().minusSeconds(10), Duration.ofSeconds(1)));
assertTrue(
differenceGreaterThan(clock.now(), clock.now().plusSeconds(10), Duration.ofSeconds(1)));
assertFalse(
differenceGreaterThan(c... |
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 testPredicate()
{
final Predicate parsed = PredicateExpressionParser.parse("com.linkedin.data.it.AlwaysTruePredicate");
Assert.assertEquals(parsed.getClass(), AlwaysTruePredicate.class);
} |
@Override
public KeyValueIterator<Windowed<K>, V> fetch(final K key) {
Objects.requireNonNull(key, "key can't be null");
final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType);
for (final ReadOnlySessionStore<K, V> store : stores) {
tr... | @Test
public void shouldFetchKeyRangeAcrossStoresWithNullKeyFrom() {
final ReadOnlySessionStoreStub<String, Long> secondUnderlying = new
ReadOnlySessionStoreStub<>();
stubProviderTwo.addStore(storeName, secondUnderlying);
underlyingSessionStore.put(new Windowed<>("a", new Session... |
@Override
public TopicConfig examineTopicConfig(String addr,
String topic) throws RemotingSendRequestException, RemotingConnectException, RemotingTimeoutException, InterruptedException, MQBrokerException {
return defaultMQAdminExtImpl.examineTopicConfig(addr, topic);
} | @Test
public void testExamineTopicConfig() throws MQBrokerException, RemotingException, InterruptedException {
TopicConfig topicConfig = defaultMQAdminExt.examineTopicConfig("127.0.0.1:10911", "topic_test_examine_topicConfig");
assertThat(topicConfig.getTopicName().equals("topic_test_examine_topicCo... |
public SpoutOutputCollector getCollector() {
return collector;
} | @Test
public void testReadFailures() throws Exception {
// 1) create couple of input files to read
Path file1 = new Path(source.toString() + "/file1.txt");
Path file2 = new Path(source.toString() + "/file2.txt");
createTextFile(file1, 6);
createTextFile(file2, 7);
as... |
public int readInt1() {
return byteBuf.readUnsignedByte();
} | @Test
void assertReadInt1() {
when(byteBuf.readUnsignedByte()).thenReturn((short) 1);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt1(), is(1));
} |
private static Path toPath(@NonNull File file) throws IOException {
try {
return file.toPath();
} catch (InvalidPathException e) {
throw new IOException(e);
}
} | @Test
public void badPath() throws Exception {
final File newFile = tmp.newFile();
File parentExistsAndIsAFile = new File(newFile, "badChild");
assertTrue(newFile.exists());
assertFalse(parentExistsAndIsAFile.exists());
final IOException e = assertThrows(IOException.class,
... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testDowngradeFailsWithNewProtocolVersionInOnePod(VertxTestContext context) {
String oldKafkaVersion = KafkaVersionTestUtils.LATEST_KAFKA_VERSION;
String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.LATEST_PROTOCOL_VERSION;
String oldLogMessageFormatVersion = KafkaV... |
public static SortOrder buildSortOrder(Table table) {
return buildSortOrder(table.schema(), table.spec(), table.sortOrder());
} | @Test
public void testEmptySpecsV1() {
PartitionSpec spec = PartitionSpec.unpartitioned();
SortOrder order = SortOrder.builderFor(SCHEMA).withOrderId(1).asc("id", NULLS_LAST).build();
TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, spec, order, 1);
// pass PartitionSpec.unpar... |
@Override
public Optional<Decision> onBufferConsumed(BufferIndexAndChannel consumedBuffer) {
return Optional.of(Decision.builder().addBufferToRelease(consumedBuffer).build());
} | @Test
void testOnBufferConsumed() {
BufferIndexAndChannel bufferIndexAndChannel = new BufferIndexAndChannel(0, 0);
Optional<Decision> consumedDecision = spillStrategy.onBufferConsumed(bufferIndexAndChannel);
assertThat(consumedDecision)
.hasValueSatisfying(
... |
public void copyTo(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws IOException {
if (shouldMock()) {
return;
}
assert httpRequest != null;
assert httpResponse != null;
final long start = System.currentTimeMillis();
int dataLength = -1;
try {
final URLConnection connection... | @Test
public void testCopyTo() throws IOException {
Utils.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "mockLabradorRetriever", "false");
final File file = File.createTempFile("testLabradorRetriever", null);
try {
final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
final HttpSe... |
@Override
public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
LogicalOlapScanOperator scan = (LogicalOlapScanOperator) input.getOp();
PhysicalOlapScanOperator physicalOlapScan = new PhysicalOlapScanOperator(scan);
physicalOlapScan.setSalt(scan.getSalt());
... | @Test
public void transform(@Mocked OlapTable table) {
LogicalOlapScanOperator logical = new LogicalOlapScanOperator(table, Maps.newHashMap(), Maps.newHashMap(),
null, -1, ConstantOperator.createBoolean(true),
1, Lists.newArrayList(1L, 2L, 3L), null,
false, Li... |
public ObjectRecipient getOwner() {
if ( obj != null ) {
return obj.getOwner();
} else {
return null;
}
} | @Test
public void testGetOwner() {
assertEquals( RECIPIENT0, repositoryObjectAcls.getOwner().getName() );
repositoryObjectAcls = new UIRepositoryObjectAcls();
assertNull( repositoryObjectAcls.getOwner() );
} |
IdBatchAndWaitTime newIdBaseLocal(int batchSize) {
return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize);
} | @Test
public void when_currentTimeBeforeAllowedRange_then_fail() {
long lowestGoodTimestamp = DEFAULT_EPOCH_START - (1L << DEFAULT_BITS_TIMESTAMP);
gen.newIdBaseLocal(lowestGoodTimestamp, 0, 1);
assertThatThrownBy(() -> gen.newIdBaseLocal(lowestGoodTimestamp - 1, 0, 1)).isInstanceOf(Hazelca... |
@ThriftField(1)
public List<PrestoThriftRange> getRanges()
{
return ranges;
} | @Test
public void testFromValueSetNone()
{
PrestoThriftValueSet thriftValueSet = fromValueSet(ValueSet.none(BIGINT));
assertNotNull(thriftValueSet.getRangeValueSet());
assertEquals(thriftValueSet.getRangeValueSet().getRanges(), ImmutableList.of());
} |
@Deprecated(forRemoval=true, since = "13.0")
public static byte[] convertJavaToOctetStream(Object source, MediaType sourceMediaType, Marshaller marshaller) throws IOException, InterruptedException {
if (source == null) return null;
if (!sourceMediaType.match(MediaType.APPLICATION_OBJECT)) {
thro... | @Test
public void testJavaToOctetStreamConversion() throws IOException, InterruptedException {
Marshaller marshaller = new ProtoStreamMarshaller();
String string = "I've seen things you people wouldn't believe.";
Double number = 12.1d;
Instant complex = Instant.now();
byte[] binary = ne... |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testValidator235() {
String version = System.getProperty("java.version");
if (version.compareTo("1.6") < 0) {
System.out.println("Cannot run Unicode IDN tests");
return; // Cannot run the test
}
UrlValidator validator = new UrlValidator();
as... |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public void updateTenant(TenantSaveReqVO updateReqVO) {
// 校验存在
TenantDO tenant = validateUpdateTenant(updateReqVO.getId());
// 校验租户名称是否重复
validTenantNameDuplicate(updateReqVO.getName(), updateReqVO.getId());
... | @Test
public void testUpdateTenant_system() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackageId(PACKAGE_ID_SYSTEM));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
// 准备参数
TenantSaveReqVO reqVO = randomPojo(TenantSaveReqVO.class, o -> {
... |
@Override
public boolean sendHeartbeatMessage(int leaderId) {
var leaderInstance = instanceMap.get(leaderId);
return leaderInstance.isAlive();
} | @Test
void testSendHeartbeatMessage() {
var instance1 = new BullyInstance(null, 1, 1);
Map<Integer, Instance> instanceMap = Map.of(1, instance1);
var messageManager = new BullyMessageManager(instanceMap);
assertTrue(messageManager.sendHeartbeatMessage(1));
} |
public static <InputT, OutputT> MapElements<InputT, OutputT> via(
final InferableFunction<InputT, OutputT> fn) {
return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor());
} | @Test
@Category(NeedsRunner.class)
public void testSimpleFunctionOutputTypeDescriptor() throws Exception {
PCollection<String> output =
pipeline
.apply(Create.of("hello"))
.apply(
MapElements.via(
new SimpleFunction<String, String>() {
... |
public static TypeDescriptor javaTypeForFieldType(FieldType fieldType) {
switch (fieldType.getTypeName()) {
case LOGICAL_TYPE:
// TODO: shouldn't we handle this differently?
return javaTypeForFieldType(fieldType.getLogicalType().getBaseType());
case ARRAY:
return TypeDescriptors.... | @Test
public void testArrayTypeToJavaType() {
assertEquals(
TypeDescriptors.lists(TypeDescriptors.longs()),
FieldTypeDescriptors.javaTypeForFieldType(FieldType.array(FieldType.INT64)));
assertEquals(
TypeDescriptors.lists(TypeDescriptors.lists(TypeDescriptors.longs())),
FieldTy... |
@Nonnull
public static <T> T checkNonNullAndSerializable(@Nonnull T object, @Nonnull String objectName) {
//noinspection ConstantConditions
if (object == null) {
throw new IllegalArgumentException('"' + objectName + "\" must not be null");
}
checkSerializable(object, obje... | @Test
public void whenNullToCheckNonNullAndSerializable_thenThrowException() {
assertThatThrownBy(() -> Util.checkNonNullAndSerializable(null, "object"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("\"object\" must not be null");
} |
public List<? extends MqttProperty> getProperties(int propertyId) {
if (propertyId == MqttPropertyType.USER_PROPERTY.value) {
return userProperties == null ? Collections.<MqttProperty>emptyList() : userProperties;
}
if (propertyId == MqttPropertyType.SUBSCRIPTION_IDENTIFIER.value) {
... | @Test
public void testGetProperties() {
MqttProperties props = createSampleProperties();
assertEquals(
Collections.singletonList(new MqttProperties.StringProperty(CONTENT_TYPE.value(), "text/plain")),
props.getProperties(CONTENT_TYPE.value()));
List<MqttProp... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void retryOnResultUsingMaybe() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);
... |
@ApiOperation(value = "Get form data", tags = { "Forms" }, notes = "")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates that form data could be queried."),
@ApiResponse(code = 404, message = "Indicates that form data could not be found.") })
@GetMapping(value = "/for... | @Test
@Deployment
public void testGetFormData() throws Exception {
Map<String, Object> variableMap = new HashMap<>();
variableMap.put("SpeakerName", "John Doe");
Address address = new Address();
variableMap.put("address", address);
ProcessInstance processInstance = runtim... |
public void appEnterBackground() {
synchronized (mTrackTimer) {
try {
for (Map.Entry<String, EventTimer> entry : mTrackTimer.entrySet()) {
if (entry != null) {
if ("$AppEnd".equals(entry.getKey())) {
continue;
... | @Test
public void appEnterBackground() {
mInstance.addEventTimer("EventTimer", new EventTimer(TimeUnit.SECONDS, 10000L));
mInstance.appEnterBackground();
Assert.assertEquals(100, mInstance.getEventTimer("EventTimer").getStartTime());
} |
private Map<String, String> parseParamsFromConfig() {
Map<String, String> params = new HashMap<>();
switch (Config.cloud_native_storage_type.toLowerCase()) {
case "s3":
params.put(CloudConfigurationConstants.AWS_S3_ACCESS_KEY, Config.aws_s3_access_key);
params... | @Test
public void testParseParamsFromConfig() {
SharedDataStorageVolumeMgr sdsvm = new SharedDataStorageVolumeMgr();
Map<String, String> params = Deencapsulation.invoke(sdsvm, "parseParamsFromConfig");
Assert.assertEquals("access_key", params.get(AWS_S3_ACCESS_KEY));
Assert.assertEqu... |
@Override
public boolean isEmpty() {
return state.isEmpty();
} | @Test
void testIsEmpty() throws Exception {
assertThat(mapState.isEmpty()).isFalse();
} |
@Override
public AppResponse process(Flow flow, CancelFlowRequest request) {
Map<String, Object> logOptions = new HashMap<>();
if (appAuthenticator != null && appAuthenticator.getAccountId() != null) logOptions.put(lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId());
if ("upgrade_... | @Test
public void processReturnOkResponseWithAppAutheticatorAndRdaSession() {
mockedAppSession.setRdaSessionId("123");
AppResponse appResponse = cancelled.process(mockedFlow, cancelFlowRequest);
verify(rdaClient, times(1)).cancel(mockedAppSession.getRdaSessionId());
assertTrue(appR... |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldHandleFunctionCallsWithGenerics() {
// Given:
final UdfFactory udfFactory = mock(UdfFactory.class);
final KsqlScalarFunction udf = mock(KsqlScalarFunction.class);
when(udf.newInstance(any())).thenReturn(new AddUdf());
givenUdf("FOO", udfFactory, udf);
when(udf.parameter... |
@Override
public KTable<K, V> filter(final Predicate<? super K, ? super V> predicate) {
Objects.requireNonNull(predicate, "predicate can't be null");
return doFilter(predicate, NamedInternal.empty(), null, false);
} | @Test
public void shouldNotAllowNullPredicateOnFilter() {
assertThrows(NullPointerException.class, () -> table.filter(null));
} |
public static Instruction transition(Integer tableId) {
checkNotNull(tableId, "Table id cannot be null");
return new TableTypeTransition(tableId);
} | @Test
public void testTransitionMethod() {
final Instruction instruction = Instructions.transition(1);
final Instructions.TableTypeTransition tableInstruction =
checkAndConvert(instruction,
Instruction.Type.TABLE,
Instru... |
public void asyncRenameFiles(
List<CompletableFuture<?>> renameFileFutures,
AtomicBoolean cancelled,
Path writePath,
Path targetPath,
List<String> fileNames) {
FileSystem fileSystem;
try {
fileSystem = FileSystem.get(writePath.toUri... | @Test
public void asyncRenameFilesTest() {
HiveRemoteFileIO hiveRemoteFileIO = new HiveRemoteFileIO(new Configuration());
FileSystem fs = new MockedRemoteFileSystem(HDFS_HIVE_TABLE);
hiveRemoteFileIO.setFileSystem(fs);
FeConstants.runningUnitTest = true;
ExecutorService execu... |
@Override
public final boolean offer(int ordinal, @Nonnull Object item) {
if (ordinal == -1) {
return offerInternal(allEdges, item);
} else {
if (ordinal == bucketCount()) {
// ordinal beyond bucketCount will add to snapshot queue, which we don't allow through... | @Test
public void when_offer2FailsAndDifferentItemOffered_then_fail() {
do_when_offerDifferent_then_fail(e -> outbox.offer(0, e));
} |
@Override
public void checkCanCreateView(Identity identity, AccessControlContext context, CatalogSchemaTableName view)
{
if (!canAccessCatalog(identity, view.getCatalogName(), ALL)) {
denyCreateView(view.toString());
}
} | @Test
public void testRefreshing()
throws Exception
{
TransactionManager transactionManager = createTestTransactionManager();
AccessControlManager accessControlManager = new AccessControlManager(transactionManager);
File configFile = newTemporaryFile();
configFile.del... |
public static DefaultProcessCommands secondary(File directory, int processNumber) {
return new DefaultProcessCommands(directory, processNumber, false);
} | @Test
public void secondary_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception {
int processNumber = MAX_PROCESSES + 1;
expectProcessNumberNoValidIAE(() -> {
try (DefaultProcessCommands secondary = DefaultProcessCommands.secondary(temp.newFolder(), processNumber)) {
}
}, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.