focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static SerdeFeatures buildValueFeatures(
final LogicalSchema schema,
final Format valueFormat,
final SerdeFeatures explicitFeatures,
final KsqlConfig ksqlConfig
) {
final boolean singleColumn = schema.value().size() == 1;
final ImmutableSet.Builder<SerdeFeature> builder = Immut... | @Test
public void shouldDefaultToNoSingleValueWrappingIfNoExplicitAndNoConfigDefault() {
// When:
final SerdeFeatures result = SerdeFeaturesFactory.buildValueFeatures(
SINGLE_FIELD_SCHEMA,
JSON,
SerdeFeatures.of(),
ksqlConfig
);
// Then:
assertThat(result.findAny(S... |
List<Transfer> getTransfersToStop(String toStopId, String toRouteId) {
final List<Transfer> allInboundTransfers = transfersToStop.getOrDefault(toStopId, Collections.emptyList());
final Map<String, List<Transfer>> byFromStop = allInboundTransfers.stream()
.filter(t -> t.transfer_type == 0... | @Test
public void testInternalTransfersByToRouteIfRouteSpecific() {
List<Transfer> transfersToStop = sampleFeed.getTransfersToStop("BEATTY_AIRPORT", "AB");
assertEquals(5, transfersToStop.size());
assertEquals("AB", transfersToStop.get(0).from_route_id);
assertEquals("FUNNY_BLOCK_AB"... |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testOldStyleResourcesSeparatedBySpacesInvalid() throws Exception {
String value = "2 vcores 5120 mb 555 mb";
expectUnparsableResource(value);
parseResourceConfigValue(value);
} |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesNumberUsingJavaTypeBigDecimal() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "number");
objectNode.put("existingJavaType", "j... |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentImportExecutor,
TokensAndUrlAuthData authData,
VideosContainerResource resource)
throws Exception {
KoofrClient koofrClient = koofrClientFactory.create(authData);
monitor.debug(
() -... | @Test
public void testImportItemFromURLWithAlbum() throws Exception {
server.enqueue(new MockResponse().setResponseCode(200).setBody("123"));
server.enqueue(new MockResponse().setResponseCode(200).setBody("4567"));
server.enqueue(new MockResponse().setResponseCode(200).setBody("89"));
when(client.ens... |
public String format(Date then)
{
if (then == null)
then = now();
Duration d = approximateDuration(then);
return format(d);
} | @Test
public void testCenturiesFromNow() throws Exception
{
PrettyTime t = new PrettyTime(now);
Assert.assertEquals("3 centuries from now", t.format(now.plus(3, ChronoUnit.CENTURIES)));
} |
public EqualityPartition generateEqualitiesPartitionedBy(Predicate<VariableReferenceExpression> variableScope)
{
ImmutableSet.Builder<RowExpression> scopeEqualities = ImmutableSet.builder();
ImmutableSet.Builder<RowExpression> scopeComplementEqualities = ImmutableSet.builder();
ImmutableSet.... | @Test
public void testEqualityPartitionGeneration()
{
EqualityInference.Builder builder = new EqualityInference.Builder(METADATA);
builder.addEquality(variable("a1"), variable("b1"));
builder.addEquality(add("a1", "a1"), multiply(variable("a1"), number(2)));
builder.addEquality(v... |
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('[');
int numColumns = _columnNames.length;
for (int i = 0; i < numColumns; i++) {
stringBuilder.append(_columnNames[i]).append('(').append(_columnDataTypes[i]).append(')').append(',');
... | @Test
public void testColumnDataType() {
for (DataSchema.ColumnDataType columnDataType : new DataSchema.ColumnDataType[]{INT, LONG}) {
Assert.assertTrue(columnDataType.isNumber());
Assert.assertTrue(columnDataType.isWholeNumber());
Assert.assertFalse(columnDataType.isArray());
Assert.asser... |
@Override
public String key() {
return "git";
} | @Test
public void sanityCheck() {
assertThat(newGitScmProvider().key()).isEqualTo("git");
} |
public static Configuration windows() {
return WindowsHolder.WINDOWS;
} | @Test
public void testFileSystemForDefaultWindowsConfiguration() throws IOException {
FileSystem fs = Jimfs.newFileSystem(Configuration.windows());
assertThat(fs.getRootDirectories())
.containsExactlyElementsIn(ImmutableList.of(fs.getPath("C:\\")))
.inOrder();
assertThatPath(fs.getPath(""... |
public static void deleteApplicationFiles(final String applicationFilesDir) {
if (!StringUtils.isNullOrWhitespaceOnly(applicationFilesDir)) {
final org.apache.flink.core.fs.Path path =
new org.apache.flink.core.fs.Path(applicationFilesDir);
try {
final... | @Test
void testDeleteApplicationFiles(@TempDir Path tempDir) throws Exception {
final Path applicationFilesDir = Files.createTempDirectory(tempDir, ".flink");
Files.createTempFile(applicationFilesDir, "flink", ".jar");
try (Stream<Path> files = Files.list(tempDir)) {
assertThat(f... |
Optional<TextRange> mapRegion(@Nullable Region region, InputFile file) {
if (region == null) {
return Optional.empty();
}
int startLine = Objects.requireNonNull(region.getStartLine(), "No start line defined for the region.");
int endLine = Optional.ofNullable(region.getEndLine()).orElse(startLine)... | @Test
public void mapRegion_whenStartLineIsNull_shouldThrow() {
when(region.getStartLine()).thenReturn(null);
assertThatNullPointerException()
.isThrownBy(() -> regionMapper.mapRegion(region, INPUT_FILE))
.withMessage("No start line defined for the region.");
} |
@JsonIgnore
public long getFirstRestartIterationId() {
if (restartInfo != null && !restartInfo.isEmpty()) {
return restartInfo.stream().min(Long::compare).get();
}
return 0;
} | @Test
public void testGetFirstRestartIterationId() throws Exception {
ForeachStepOverview overview =
loadObject(
"fixtures/instances/sample-foreach-step-overview.json", ForeachStepOverview.class);
assertEquals(0, overview.getFirstRestartIterationId());
overview.addOne(23L, WorkflowIns... |
public ElasticAgentInformation getElasticAgentInformationFromResponseBody(String responseBody) {
final ElasticAgentInformationDTO elasticAgentInformationDTO = FORCED_EXPOSE_GSON.fromJson(responseBody, ElasticAgentInformationDTO.class);
return elasticAgentInformationConverterV5.fromDTO(elasticAgentInform... | @Test
public void shouldGetTheElasticAgentInformationFromResponseBodyOfMigrateCall() throws CryptoException {
String responseBody = "{" +
" \"plugin_settings\":{" +
" \"key2\":\"password\", " +
" \"key\":\"value\"" +
" }," +... |
public HsDataView registerNewConsumer(
int subpartitionId,
HsConsumerId consumerId,
HsSubpartitionConsumerInternalOperations operation)
throws IOException {
synchronized (lock) {
checkState(!isReleased, "HsFileDataManager is already released.");
... | @Test
void testRunReadBuffersThrowException() throws Exception {
TestingHsSubpartitionFileReader reader = new TestingHsSubpartitionFileReader();
CompletableFuture<Throwable> cause = new CompletableFuture<>();
reader.setFailConsumer((cause::complete));
reader.setReadBuffersConsumer(
... |
private RemotingCommand getMaxOffset(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(GetMaxOffsetResponseHeader.class);
final GetMaxOffsetResponseHeader responseHeader = (GetMaxOffsetResp... | @Test
public void testGetMaxOffset() throws Exception {
messageStore = mock(MessageStore.class);
when(messageStore.getMaxOffsetInQueue(anyString(), anyInt())).thenReturn(Long.MIN_VALUE);
when(brokerController.getMessageStore()).thenReturn(messageStore);
GetMaxOffsetRequestHeader getM... |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testTruncateDecimalTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("truncate(%s,%s)", INT_SV_COLUMN, LONG_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.asser... |
@Description("Returns the number of points in a Geometry")
@ScalarFunction("ST_NumPoints")
@SqlType(BIGINT)
public static long stNumPoints(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
return getPointCount(EsriGeometrySerde.deserialize(input));
} | @Test
public void testSTNumPoints()
{
assertNumPoints("POINT EMPTY", 0);
assertNumPoints("MULTIPOINT EMPTY", 0);
assertNumPoints("LINESTRING EMPTY", 0);
assertNumPoints("MULTILINESTRING EMPTY", 0);
assertNumPoints("POLYGON EMPTY", 0);
assertNumPoints("MULTIPOLYGON... |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
return this.processRequest(ctx.channel(), request, true);
} | @Test
public void testSingleAck_appendAck() throws RemotingCommandException {
{
// buffer addAk OK
PopBufferMergeService popBufferMergeService = mock(PopBufferMergeService.class);
when(popBufferMergeService.addAk(anyInt(), any())).thenReturn(true);
when(popMes... |
public BigDecimal calculateProductGramsForRequiredFiller(Filler filler, BigDecimal fillerGrams) {
if (filler == null || fillerGrams == null || fillerGrams.doubleValue() <= 0) {
return BigDecimal.valueOf(0);
}
if (filler.equals(Filler.PROTEIN)) {
return calculateProductGr... | @Test
void calculateProductGramsForRequiredFiller_negativeValue() {
BigDecimal result = product.calculateProductGramsForRequiredFiller(Filler.CARBOHYDRATE, BigDecimal.valueOf(-999));
assertEquals(BigDecimal.valueOf(0), result);
} |
public double currentConsumptionRate() {
return aggregateStat(ConsumerCollector.CONSUMER_MESSAGES_PER_SEC, false);
} | @Test
public void shouldAggregateStatsAcrossAllConsumers() {
final MetricCollectors metricCollectors = new MetricCollectors();
final ConsumerCollector collector1 = new ConsumerCollector();
collector1.configure(
ImmutableMap.of(
ConsumerConfig.CLIENT_ID_CONFIG, "client1",
K... |
@Override
public PageResult<OAuth2ClientDO> getOAuth2ClientPage(OAuth2ClientPageReqVO pageReqVO) {
return oauth2ClientMapper.selectPage(pageReqVO);
} | @Test
public void testGetOAuth2ClientPage() {
// mock 数据
OAuth2ClientDO dbOAuth2Client = randomPojo(OAuth2ClientDO.class, o -> { // 等会查询到
o.setName("潜龙");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
});
oauth2ClientMapper.insert(dbOAuth2Client);
... |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testEncodingPositionAddNewFields() throws Exception {
Schema schema1 =
Schema.builder()
.addNullableField("f_int32", FieldType.INT32)
.addNullableField("f_string", FieldType.STRING)
.build();
Schema schema2 =
Schema.builder()
.a... |
@Override
public List<SQLPrimaryKey> getPrimaryKeys(String catName, String db_name, String tbl_name) throws MetaException {
PrimaryKeysRequest request = new PrimaryKeysRequest(db_name, tbl_name);
request.setCatName(catName);
return getPrimaryKeys(request);
} | @Test
public void testGetPrimaryKeys() throws Exception {
Database db1 =
new DatabaseBuilder().setName(DB1).setDescription("description")
.setLocation("locationurl").build(conf);
objectStore.createDatabase(db1);
StorageDescriptor sd1 = new StorageDescriptor(
ImmutableList.of(ne... |
@Override
public synchronized Multimap<String, String> findBundlesForUnloading(final LoadData loadData,
final ServiceConfiguration conf) {
selectedBundlesCache.clear();
final double threshold = conf.getLoadBalancerBrokerThresho... | @Test
public void testBrokerReachThreshold() {
LoadData loadData = new LoadData();
LocalBrokerData broker1 = new LocalBrokerData();
broker1.setCpu(new ResourceUsage(140, 100));
broker1.setMemory(new ResourceUsage(10, 100));
broker1.setDirectMemory(new ResourceUsage(10, 100))... |
public boolean isMatch(Map<String, Pattern> patterns) {
if (!patterns.isEmpty()) {
return matchPatterns(patterns);
}
// Empty pattern is still considered as a match.
return true;
} | @Test
public void testIsMatchMismatchFail() throws UnknownHostException {
Uuid uuid = Uuid.randomUuid();
ClientMetricsInstanceMetadata instanceMetadata = new ClientMetricsInstanceMetadata(uuid,
ClientMetricsTestUtils.requestContext());
Map<String, Pattern> patternMap = new HashM... |
@NonNull
public URI callback(@NonNull CallbackRequest request) {
var session = mustFindSession(request.sessionId());
var idToken =
session
.trustedSectoralIdpStep()
.exchangeSectoralIdpCode(request.code(), session.codeVerifier());
session = removeSession(request.sessionI... | @Test
void callback_unknownSession() {
var config = new RelyingPartyConfig(null, null);
var sessionRepo = mock(SessionRepo.class);
var sut = new AuthService(BASE_URI, config, null, sessionRepo, null, null);
var sessionId = UUID.randomUUID().toString();
when(sessionRepo.load(sessionId)).thenRe... |
@Override
public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager)
{
ImmutableList.Builder<ScalarFunctionImplementationChoice> implementationChoices = ImmutableList.builder();
for (PolymorphicScalarFunctionCho... | @Test
public void testSelectsMultipleChoiceWithBlockPosition()
throws Throwable
{
Signature signature = SignatureBuilder.builder()
.kind(SCALAR)
.operatorType(IS_DISTINCT_FROM)
.argumentTypes(DECIMAL_SIGNATURE, DECIMAL_SIGNATURE)
... |
public static List<Class<?>> findEntityClassesFromDirectory(String[] pckgs) {
@SuppressWarnings("unchecked")
final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class);
try (final PackageNamesScanner scanner = new PackageNamesScanner(pckgs, true)) {
while (... | @Test
void testFindEntityClassesFromMultipleDirectories() {
//given
String packageWithEntities = "io.dropwizard.hibernate.fake.entities.pckg";
String packageWithEntities2 = "io.dropwizard.hibernate.fake2.entities.pckg";
//when
List<Class<?>> findEntityClassesFromDirectory =
... |
public static String toJagexName(String str)
{
return CharMatcher.ascii().retainFrom(str.replaceAll("[\u00A0_-]", " ")).trim();
} | @Test
public void toJagexName()
{
assertEquals("lab rat", Text.toJagexName("lab rat"));
assertEquals("lab rat", Text.toJagexName("-lab_rat"));
assertEquals("lab rat", Text.toJagexName(" lab-rat__"));
assertEquals("lab rat", Text.toJagexName("lab\u00A0rat\u00A0\u00A0"));
assertEquals("Test Man", Text.toJage... |
public void setBaseResource(Resource baseResource) {
handler.setBaseResource(baseResource);
} | @Test
void setsBaseResourceList(@TempDir Path tempDir) throws Exception {
Resource wooResource = Resource.newResource(Files.createDirectory(tempDir.resolve("dir-1")));
Resource fooResource = Resource.newResource(Files.createDirectory(tempDir.resolve("dir-2")));
final Resource[] testResource... |
@Override
public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback) throws BackgroundException {
if(containerService.isContainer(source)) {
if(new SimplePathPredicate(sourc... | @Test
public void testMoveDataRoom() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final String directoryname = new AlphanumericRandomStringService().random();
final Path test = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(directoryname, EnumS... |
public static Map<String, Object> flatten(Map<String, Object> originalMap, String parentKey, String separator) {
final Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
final String key = parentKey.isEmpty() ? entry.getKey() : pare... | @Test
public void flattenAddsParentKeys() throws Exception {
final Map<String, Object> map = ImmutableMap.of(
"map", ImmutableMap.of(
"foo", "bar",
"baz", "qux"));
final Map<String, Object> expected = ImmutableMap.of(
"t... |
public long getUpdateTime() {
return updateTime;
} | @Test
public void testGetUpdateTime() {
long lastUpdateTime = replicatedRecord.getUpdateTime();
sleepAtLeastMillis(100);
replicatedRecord.setValue("newValue", 0);
assertTrue("replicatedRecord.getUpdateTime() should return a greater update time",
replicatedRecord.getU... |
static String isHostParam(final String given) {
final String hostUri = StringHelper.notEmpty(given, "host");
final Matcher matcher = HOST_PATTERN.matcher(given);
if (!matcher.matches()) {
throw new IllegalArgumentException(
"host must be an absolute URI (e.g. ht... | @Test
public void nonUriHostParametersAreNotAllowed() {
assertThrows(IllegalArgumentException.class,
() -> RestOpenApiHelper.isHostParam("carrot"));
} |
public static <T> MasterTriggerRestoreHook<T> wrapHook(
MasterTriggerRestoreHook<T> hook, ClassLoader userClassLoader) {
return new WrappedMasterHook<>(hook, userClassLoader);
} | @Test
void wrapHook() throws Exception {
final String id = "id";
Thread thread = Thread.currentThread();
final ClassLoader originalClassLoader = thread.getContextClassLoader();
final ClassLoader userClassLoader = new URLClassLoader(new URL[0]);
final CompletableFuture<Void>... |
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
} | @Test
public void getStringLines_linux() {
Settings settings = new MapSettings();
settings.setProperty("foo", "one\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\ntwo\n");
assertThat(settings.getStringLines("foo")).isEqua... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatPauseQuery() {
// Given:
final PauseQuery query = PauseQuery.query(Optional.empty(), new QueryId("FOO"));
// When:
final String formatted = SqlFormatter.formatSql(query);
// Then:
assertThat(formatted, is("PAUSE FOO"));
} |
@Override
public void start() throws Exception {
validateConfiguration(configs, registry.getNames());
} | @Test
void startValidationsShouldSucceedWhenNoHealthChecksConfigured() throws Exception {
// given
List<HealthCheckConfiguration> configs = emptyList();
HealthCheckRegistry registry = new HealthCheckRegistry();
// when
HealthCheckConfigValidator validator = new HealthCheckCo... |
public EnumSet<RepositoryFilePermission> getPermissionSet() {
return ace.getPermissions();
} | @Test
public void testGetPermissionSet() {
UIRepositoryObjectAcl uiAcl = new UIRepositoryObjectAcl( createObjectAce() );
EnumSet<RepositoryFilePermission> permissions = uiAcl.getPermissionSet();
assertNotNull( permissions );
assertEquals( 1, permissions.size() );
assertTrue( permissions.contains... |
public static long getDirectoryFilesSize(java.nio.file.Path path, FileVisitOption... options)
throws IOException {
if (path == null) {
return 0L;
}
try (Stream<java.nio.file.Path> pathStream = Files.walk(path, options)) {
return pathStream
... | @Test
void testGetDirectorySize() throws Exception {
final File parent = TempDirUtils.newFolder(temporaryFolder);
// Empty directory should have size 0
assertThat(FileUtils.getDirectoryFilesSize(parent.toPath())).isZero();
// Expected size: (20*5^0 + 20*5^1 + 20*5^2 + 20*5^3) * 1 b... |
public Rule<ProjectNode> projectNodeRule()
{
return new PullUpExpressionInLambdaProjectNodeRule();
} | @Test
public void testInvalidNestedLambdaInProjection()
{
tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).projectNodeRule())
.setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true")
.on(p ->
{
p.variab... |
@Override
public Object convert(String value) {
if (isNullOrEmpty(value)) {
return value;
}
if (value.contains("=")) {
final Map<String, String> fields = new HashMap<>();
Matcher m = PATTERN.matcher(value);
while (m.find()) {
... | @Test
public void testFilterSupportsMultipleIdenticalKeys() {
TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>());
@SuppressWarnings("unchecked")
Map<String, String> result = (Map<String, String>) f.convert("Ohai I am a message k1=v1 k1=v2 Awesome!");
assert... |
public void addEdge(final V u, final V v, final int capacity, final int cost, final int flow) {
Objects.requireNonNull(u);
Objects.requireNonNull(v);
addEdge(u, new Edge(v, capacity, cost, capacity - flow, flow));
} | @Test
public void testNullNode() {
final Graph<Integer> graph1 = new Graph<>();
assertThrows(NullPointerException.class, () -> graph1.addEdge(null, 1, 1, 1, 1));
assertThrows(NullPointerException.class, () -> graph1.addEdge(1, null, 1, 1, 1));
} |
@Override
@MethodNotAvailable
public void loadAll(boolean replaceExistingValues) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testLoadAllWithListener() {
adapter.loadAll(Collections.emptySet(), true, null);
} |
@Override
public Iterable<MappingEntry> getMappingEntriesByAppId(Type type, ApplicationId appId) {
Set<MappingEntry> mappingEntries = Sets.newHashSet();
for (Device d : deviceService.getDevices()) {
for (MappingEntry mappingEntry : store.getMappingEntries(type, d.id())) {
... | @Test
public void getMappingEntriesByAddId() {
addMapping(MAP_DATABASE, 1);
addMapping(MAP_DATABASE, 2);
assertTrue("should have two mappings",
Lists.newLinkedList(
service.getMappingEntriesByAppId(MAP_DATABASE, appId)).size() == 2);
} |
public BackgroundException map(final IOException failure, final Path directory) {
return super.map("Connection failed", failure, directory);
} | @Test
public void testMapPathName() {
final DefaultIOExceptionMappingService s = new DefaultIOExceptionMappingService();
assertEquals("Download n failed.", s.map("Download {0} failed", new SocketException("s"),
new Path("/n", EnumSet.of(Path.Type.directory, Path.Type.volume))).getMessage... |
protected List<Long> chooseTablets() {
GlobalStateMgr globalStateMgr = GlobalStateMgr.getCurrentState();
MetaObject chosenOne;
List<Long> chosenTablets = Lists.newArrayList();
// sort dbs
List<Long> dbIds = globalStateMgr.getLocalMetastore().getDbIds();
if (dbIds.isEmpt... | @Test
public void testChooseTablets(@Mocked GlobalStateMgr globalStateMgr) {
long dbId = 1L;
long tableId = 2L;
long partitionId = 3L;
long indexId = 4L;
long tabletId = 5L;
long replicaId = 6L;
long backendId = 7L;
TStorageMedium medium = TStorageMedi... |
public List<ChangeStreamRecord> toChangeStreamRecords(
PartitionMetadata partition,
ChangeStreamResultSet resultSet,
ChangeStreamResultSetMetadata resultSetMetadata) {
if (this.isPostgres()) {
// In PostgresQL, change stream records are returned as JsonB.
return Collections.singletonLi... | @Test
public void testMappingDeleteJsonRowNewValuesToDataChangeRecord() {
final DataChangeRecord dataChangeRecord =
new DataChangeRecord(
"partitionToken",
Timestamp.ofTimeSecondsAndNanos(10L, 20),
"transactionId",
false,
"1",
"tableN... |
@SuppressWarnings({"unchecked", "rawtypes"})
public Collection<DataNode> getDataNodes(final String tableName) {
Collection<DataNode> result = getDataNodesByTableName(tableName);
if (result.isEmpty()) {
return result;
}
for (Entry<ShardingSphereRule, DataNodeBuilder> entry... | @Test
void assertGetDataNodesForSingleTableWithDataNodeContainedRuleAndDataSourceContainedRule() {
DataNodes dataNodes = new DataNodes(mockShardingSphereRules());
Collection<DataNode> actual = dataNodes.getDataNodes("t_single");
assertThat(actual.size(), is(3));
Iterator<DataNode> it... |
@Override
public CRFModel train(SequenceDataset<Label> sequenceExamples, Map<String, Provenance> runProvenance) {
if (sequenceExamples.getOutputInfo().getUnknownCount() > 0) {
throw new IllegalArgumentException("The supplied Dataset contained unknown Outputs, and this Trainer is supervised.");
... | @Test
public void testValidExample() {
SequenceDataset<Label> p = SequenceDataGenerator.generateGorillaDataset(5);
SequenceModel<Label> m = t.train(p);
m.predict(p.getExample(0));
Helpers.testSequenceModelSerialization(m,Label.class);
Helpers.testSequenceModelProtoSerializati... |
@VisibleForTesting
List<String> getFuseInfo() {
return mFuseInfo;
} | @Test
public void UnderFileSystemLocal() {
try (FuseUpdateChecker checker = getUpdateCheckerWithUfs("/home/ec2-user/testFolder")) {
Assert.assertTrue(containsTargetInfo(checker.getFuseInfo(),
FuseUpdateChecker.LOCAL_FS));
}
} |
String instanceName(String instanceName) {
return sanitize(instanceName, INSTANCE_RESERVED);
} | @Test
public void replacesIllegalCharactersInInstanceName() throws Exception {
assertThat(sanitize.instanceName("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz-quux");
} |
protected static DataSource getDataSourceFromJndi( String dsName, Context ctx ) throws NamingException {
if ( Utils.isEmpty( dsName ) ) {
throw new NamingException( BaseMessages.getString( PKG, "DatabaseUtil.DSNotFound", String.valueOf( dsName ) ) );
}
Object foundDs = FoundDS.get( dsName );
if ( ... | @Test
public void testCaching() throws NamingException {
DataSource dataSource = mock( DataSource.class );
when( context.lookup( testName ) ).thenReturn( dataSource ).thenThrow( new NullPointerException() );
assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
assertEqu... |
public boolean isSensitive(ConfigRecord record) {
ConfigResource.Type type = ConfigResource.Type.forId(record.resourceType());
return isSensitive(type, record.name());
} | @Test
public void testIsSensitive() {
assertFalse(SCHEMA.isSensitive(BROKER, "foo.bar"));
assertTrue(SCHEMA.isSensitive(BROKER, "quuux"));
assertTrue(SCHEMA.isSensitive(BROKER, "quuux2"));
assertTrue(SCHEMA.isSensitive(BROKER, "unknown.config.key"));
assertFalse(SCHEMA.isSens... |
@Override
public int hashCode() {
return Objects.hash(targetImage, imageDigest, imageId, tags, imagePushed);
} | @Test
public void testEquality_differentImagePushed() {
JibContainer container1 = new JibContainer(targetImage1, digest1, digest1, tags1, true);
JibContainer container2 = new JibContainer(targetImage1, digest1, digest1, tags1, false);
Assert.assertNotEquals(container1, container2);
Assert.assertNotEq... |
@Override
public CompletableFuture<?> getAvailableFuture() {
return targetPartition.getAvailableFuture();
} | @TestTemplate
void testIsAvailableOrNot() throws Exception {
// setup
final NetworkBufferPool globalPool = new NetworkBufferPool(10, 128);
final BufferPool localPool = globalPool.createBufferPool(1, 1, 1, Integer.MAX_VALUE, 0);
final ResultPartitionWriter resultPartition =
... |
@VisibleForTesting
@SuppressWarnings("nullness") // ok to have nullable elements on stream
static String renderName(String prefix, MetricResult<?> metricResult) {
MetricKey key = metricResult.getKey();
MetricName name = key.metricName();
String step = key.stepName();
return Streams.concat(
... | @Test
public void testRenderNameWithPrefix() {
MetricResult<Object> metricResult =
MetricResult.create(
MetricKey.create(
"myStep.one.two(three)", MetricName.named("myNameSpace//", "myName()")),
123,
456);
String renderedName = SparkBeamMetric.render... |
public static int findNextPositivePowerOfTwo(final int value)
{
return 1 << (Integer.SIZE - Integer.numberOfLeadingZeros(value - 1));
} | @Test
void shouldReturnNextPositivePowerOfTwo()
{
assertThat(findNextPositivePowerOfTwo(MIN_VALUE), is(MIN_VALUE));
assertThat(findNextPositivePowerOfTwo(MIN_VALUE + 1), is(1));
assertThat(findNextPositivePowerOfTwo(-1), is(1));
assertThat(findNextPositivePowerOfTwo(0), is(1));
... |
public HttpApiV2ProxyRequestContext getRequestContext() {
return requestContext;
} | @Test
void deserialize_fromJsonString_authorizerEmptyMap() {
try {
HttpApiV2ProxyRequest req = LambdaContainerHandler.getObjectMapper().readValue(NO_AUTH_PROXY,
HttpApiV2ProxyRequest.class);
assertNotNull(req.getRequestContext().getAuthorizer());
asser... |
@Override
protected Object getTargetObject(boolean key) {
Object targetObject;
if (key) {
// keyData is never null
if (keyData.isPortable() || keyData.isJson() || keyData.isCompact()) {
targetObject = keyData;
} else {
targetObject ... | @Test
public void testGetTargetObject_givenValueIsPortable_whenKeyFlagIsFalse_thenReturnValueData() {
Data key = serializationService.toData("indexedKey");
Portable value = new PortableEmployee(30, "peter");
QueryableEntry entry = createEntry(key, value, newExtractor());
Object targ... |
public List<String> getInfo() {
List<String> info = Lists.newArrayList();
info.add(String.valueOf(id));
info.add(name);
info.add(TimeUtils.longToTimeString(createTime));
info.add(String.valueOf(isReadOnly));
info.add(location);
info.add(storage.getBrokerName());
... | @Test
public void testGetInfo() {
repo = new Repository(10000, "repo", false, location, storage);
List<String> infos = repo.getInfo();
Assert.assertTrue(infos.size() == ShowRepositoriesStmt.TITLE_NAMES.size());
} |
public static ParameterizedType listOf(Type elementType) {
return parameterizedType(List.class, elementType);
} | @Test
public void createListType() {
ParameterizedType type = Types.listOf(Person.class);
assertThat(type.getRawType()).isEqualTo(List.class);
assertThat(type.getActualTypeArguments()).isEqualTo(new Type[] {Person.class});
} |
public static void setProtectedFieldValue(String protectedField, Object object, Object newValue) {
try {
// acgegi would silently fail to write to final fields
// FieldUtils.writeField(Object, field, true) only sets accessible on *non* public fields
// and then fails with Ill... | @Test
@Issue("JENKINS-64390")
public void setProtectedFieldValue_Should_fail_silently_to_set_public_final_fields_in_OuterClass() {
OuterClassWithPublicFinalField sut = new OuterClassWithPublicFinalField();
FieldUtils.setProtectedFieldValue("myField", sut, "test");
assertEquals("original"... |
@Override
public Server build(Environment environment) {
printBanner(environment.getName());
final ThreadPool threadPool = createThreadPool(environment.metrics());
final Server server = buildServer(environment.lifecycle(), threadPool);
final Handler applicationHandler = createAppServ... | @Test
void testDeserializeWithoutJsonAutoDetect() throws ConfigurationException, IOException {
final ObjectMapper objectMapper = Jackson.newObjectMapper()
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
assertThat(new YamlConfigurationFactory<>(
Def... |
public static Date parseDate(String dateStr, String format) throws ParseException {
if (StringUtils.isBlank(dateStr)) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(dateStr);
} | @Test
public void testParseDate() throws ParseException {
String dateStr = "2021-01-01";
Date date = DateUtil.parseDate(dateStr, "yyyy-MM-dd");
Assertions.assertNotNull(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Assertions.assertEquals(dateStr, sdf.for... |
@VisibleForTesting
CompletableFuture<Acknowledge> getBootstrapCompletionFuture() {
return bootstrapCompletionFuture;
} | @Test
void testClusterShutdownWhenApplicationFails() throws Exception {
// we're "listening" on this to be completed to verify that the cluster
// is being shut down from the ApplicationDispatcherBootstrap
final CompletableFuture<ApplicationStatus> externalShutdownFuture =
ne... |
public synchronized ResultSet fetchResults(FetchOrientation orientation, int maxFetchSize) {
long token;
switch (orientation) {
case FETCH_NEXT:
token = currentToken;
break;
case FETCH_PRIOR:
token = currentToken - 1;
... | @Test
void testFetchResultsMultipleTimesWithLimitedFetchSizeInOrientation() {
int bufferSize = data.size();
ResultFetcher fetcher =
buildResultFetcher(Collections.singletonList(data.iterator()), bufferSize);
int fetchSize = data.size() / 2;
runFetchMultipleTimes(
... |
public static InetSocketAddress parseAddress(String address, int defaultPort) {
return parseAddress(address, defaultPort, false);
} | @Test
void shouldParseAddressForIPv6WithoutPort_Strict() {
InetSocketAddress socketAddress = AddressUtils.parseAddress("[1abc:2abc:3abc::5ABC:6abc]:", 80);
assertThat(socketAddress.isUnresolved()).isFalse();
assertThat(socketAddress.getAddress().getHostAddress()).isEqualTo("1abc:2abc:3abc:0:0:0:5abc:6abc");
as... |
@Deprecated
@Override
public void init(final ProcessorContext context, final StateStore root) {
internal.init(context, root);
} | @Test
public void shouldDelegateInit() {
// init is already called in setUp()
verify(inner).init((StateStoreContext) context, store);
} |
public PushTelemetryResponse processPushTelemetryRequest(PushTelemetryRequest request, RequestContext requestContext) {
Uuid clientInstanceId = request.data().clientInstanceId();
if (clientInstanceId == null || Uuid.RESERVED.contains(clientInstanceId)) {
String msg = String.format("Invalid ... | @Test
public void testPushTelemetryClientInstanceIdInvalid() throws UnknownHostException {
// Null client instance id
PushTelemetryRequest request = new PushTelemetryRequest.Builder(
new PushTelemetryRequestData().setClientInstanceId(null), true).build();
PushTelemetryResponse r... |
public void write(final ConsumerRecord<byte[], byte[]> record) throws IOException {
if (!writable) {
throw new IOException("Write permission denied.");
}
final File dirty = dirty(file);
final File tmp = tmp(file);
// first write to the dirty copy
appendRecordToFile(record, dirty, filesyste... | @Test
public void shouldWriteMultipleRecords() throws IOException {
// Given
final ConsumerRecord<byte[], byte[]> record1= newStreamRecord("stream1");
final ConsumerRecord<byte[], byte[]> record2 = newStreamRecord("stream2");
// When
replayFile.write(record1);
replayFile.write(record2);
... |
public Optional<Integer> getTimestampFieldIndex() {
return timestampFieldIndex;
} | @Test
public void shouldGenerateCorrectTimestamp() throws IOException {
final Generator generator = new Generator(new File("./src/main/resources/pageviews_schema.avro"), new Random());
final RowGenerator rowGenerator = new RowGenerator(generator, "viewtime", Optional.of("viewtime"));
assertThat("incorrec... |
public String process(String str)
{
StringBuilder sb = new StringBuilder();
for (String line : str.split("\r?\n"))
{
if (line.startsWith("#include "))
{
String resource = line.substring(9);
if (resource.startsWith("\"") && resource.endsWith("\""))
{
resource = resource.substring(1, resourc... | @Test
public void testProcess()
{
Function<String, String> func = (String resource) ->
{
switch (resource)
{
case "file2":
return FILE2;
default:
throw new RuntimeException("unknown resource");
}
};
String out = new Template()
.add(func)
.process(FILE1);
assertEquals(RESULT,... |
public static StructType partitionType(Table table) {
Collection<PartitionSpec> specs = table.specs().values();
return buildPartitionProjectionType("table partition", specs, allFieldIds(specs));
} | @Test
public void testPartitionTypeWithSpecEvolutionInV1Tables() {
TestTables.TestTable table =
TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V1_FORMAT_VERSION);
table.updateSpec().addField(Expressions.bucket("category", 8)).commit();
assertThat(table.specs()).hasSize(2);
Struct... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(log.isWarnEnabled()) {
log.warn(String.format("Disable checksum verification for %s", file));
// Do not set che... | @Test
public void testReadRangeUnknownLength() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(P... |
@SuppressWarnings("checkstyle:npathcomplexity")
public PartitionServiceState getPartitionServiceState() {
PartitionServiceState state = getPartitionTableState();
if (state != SAFE) {
return state;
}
if (!checkAndTriggerReplicaSync()) {
return REPLICA_NOT_SYN... | @Test
public void shouldNotBeSafe_whenUnknownReplicaOwnerPresent_whileNotActive() throws UnknownHostException {
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory();
HazelcastInstance hz = factory.newHazelcastInstance();
HazelcastInstance hz2 = factory.newHazelcastInstance... |
@Override
public boolean add(E element) {
return add(element, element.hashCode());
} | @Test(expected = NullPointerException.class)
public void testAddNull() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
set.add(null);
} |
public boolean isCheckpointPending() {
return !pendingCheckpoints.isEmpty();
} | @Test
void testNoFastPathWithChannelFinishedDuringCheckpoints() throws Exception {
BufferOrEvent[] sequence = {
createBarrier(1, 0), createEndOfPartition(0), createBarrier(1, 1)
};
ValidatingCheckpointHandler validator = new ValidatingCheckpointHandler();
inputGate = cre... |
public void close()
{
if (!isClosed)
{
isClosed = true;
unmapAndCloseChannel();
}
} | @Test
void shouldThrowExceptionAfterFailureOnPageStraddle() throws Exception
{
final long newRecordingId = newRecording();
final File segmentFile = new File(archiveDir, segmentFileName(newRecordingId, 0));
try (FileChannel log = FileChannel.open(segmentFile.toPath(), READ, WRITE, CREATE)... |
@Override
public void setSystemState(ClusterStateBundle stateBundle, NodeInfo node, Waiter<SetClusterStateRequest> externalWaiter) {
RPCSetClusterStateWaiter waiter = new RPCSetClusterStateWaiter(externalWaiter);
ClusterState baselineState = stateBundle.getBaselineClusterState();
Target con... | @Test
void setSystemState_v3_sends_distribution_states_rpc() {
var f = new Fixture<SetClusterStateRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
var sentBundle = ClusterStateBundleUtil.makeBundle("distributor:3 storage:3");
f.c... |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \... | @Test
void testInvokeByPassingNullValue() {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr... |
@Override
public void collect(MetricsEmitter metricsEmitter) {
for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) {
MetricKey metricKey = entry.getKey();
KafkaMetric metric = entry.getValue();
try {
collectMetric(metricsEmitter, metricKey... | @Test
public void testCollectMetricsWithExcludeLabels() {
collector = new KafkaMetricsCollector(
metricNamingStrategy,
time,
Collections.singleton("tag2")
);
tags = new HashMap<>();
tags.put("tag1", "value1");
tags.put("tag2", "value2");
... |
@Override
public int compareTo(Delayed o) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
@SuppressWarnings("ConstantConditions")
public void compareTo() {
ScheduledFuture<Integer> future = new DelegatingScheduledFutureStripper<>(
scheduler.schedule(new SimpleCallableTestTask(), 0, TimeUnit.SECONDS));
future.compar... |
public Timestamp parseToTimestamp(final String text) {
return new Timestamp(parse(text));
} | @Test
public void shouldParseToTimestamp() {
assertThat(parser.parseToTimestamp("2017-11-13T23:59:58").getTime(), is(1510617598000L));
assertThat(parser.parseToTimestamp("2017-11-13T23:59:58.999-0100").getTime(), is(1510621198999L));
} |
public void append(AbortedTxn abortedTxn) throws IOException {
lastOffset.ifPresent(offset -> {
if (offset >= abortedTxn.lastOffset())
throw new IllegalArgumentException("The last offset of appended transactions must increase sequentially, but "
+ abortedTxn.lastO... | @Test
public void testLastOffsetMustIncrease() throws IOException {
index.append(new AbortedTxn(1L, 5, 15, 13));
assertThrows(IllegalArgumentException.class, () -> index.append(new AbortedTxn(0L, 0,
15, 11)));
} |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldFailForComplexTypeComparison() {
// Given:
final Expression expression = new ComparisonExpression(Type.GREATER_THAN, MAPCOL, ADDRESS);
// When:
final KsqlStatementException e = assertThrows(
KsqlStatementException.class,
() -> expressionTypeManager.getExpressio... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testServletRequestPattern() throws Exception {
JmxCollector jc =
new JmxCollector(
"\n---\nrules:\n- pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]),\n name=([-a-zA-Z0-9+/$%~_-|!.]*), ... |
@Override
public boolean matches(T objectUnderTest) {
boolean matches = super.matches(objectUnderTest);
describedAs(buildVerboseDescription(objectUnderTest, matches));
return matches;
} | @Test
public void multiple_matches_should_not_change_description() {
VERBOSE_CONDITION.matches("foooo");
assertThat(VERBOSE_CONDITION).hasToString("shorter than 4 but length was 5");
VERBOSE_CONDITION.matches("foooo");
VERBOSE_CONDITION.matches("foooo");
assertThat(VERBOSE_CONDITION).hasToString("... |
public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize)
{
// sort ranges by start offset
List<DiskRange> ranges = new ArrayList<>(diskRanges);
Collections.sort(ranges, new Comparator<DiskRange>()
{
... | @Test
public void testMergeAdjacent()
{
List<DiskRange> diskRanges = mergeAdjacentDiskRanges(
ImmutableList.of(new DiskRange(100, 100), new DiskRange(200, 100), new DiskRange(300, 100)),
new DataSize(0, BYTE),
new DataSize(1, GIGABYTE));
assertEqua... |
@Override
public void dropPartition(ObjectPath tablePath, CatalogPartitionSpec catalogPartitionSpec, boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
if (!tableExists(tablePath)) {
if (ignoreIfNotExists) {
return;
} else {
throw new PartitionNotExi... | @Test
public void testDropPartition() throws Exception {
ObjectPath tablePath = new ObjectPath(TEST_DEFAULT_DATABASE, "tb1");
// create table
catalog.createTable(tablePath, EXPECTED_CATALOG_TABLE, true);
CatalogPartitionSpec partitionSpec = new CatalogPartitionSpec(new HashMap<String, String>() {
... |
public static <K, V> Read<K, V> read() {
return new AutoValue_KafkaIO_Read.Builder<K, V>()
.setTopics(new ArrayList<>())
.setTopicPartitions(new ArrayList<>())
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES)
... | @Test
public void testUnboundedSourceRawSizeMetric() {
final String readStep = "readFromKafka";
final int numElements = 1000;
final int numPartitionsPerTopic = 10;
final int recordSize = 12; // The size of key and value is defined in ConsumerFactoryFn.
List<String> topics = ImmutableList.of("test... |
public static String readAllBytes(InputStream input, Charset charset) throws IOException {
if (charset == null) {
input = ensureMarkSupport(input);
input.mark(4);
byte[] buffer = new byte[4];
int bytesRead = fillBuffer(input, buffer);
input.reset();
charset = detectUtfCharset0(b... | @Test
void validateTextConversionFromStreams() throws IOException {
assertEquals("A",
UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("EFBBBF41")), StandardCharsets.UTF_8));
assertEquals("A", UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("EFBBBF41")), null));
assertEqual... |
@PUT
@Path("/{connector}/config")
@Operation(summary = "Create or reconfigure the specified connector")
public Response putConnectorConfig(final @PathParam("connector") String connector,
final @Context HttpHeaders headers,
final @... | @Test
public void testPutConnectorConfigNameMismatch() {
Map<String, String> connConfig = new HashMap<>(CONNECTOR_CONFIG);
connConfig.put(ConnectorConfig.NAME_CONFIG, "mismatched-name");
assertThrows(BadRequestException.class, () -> connectorsResource.putConnectorConfig(CONNECTOR_NAME,
... |
@Override
public boolean isMatchedWithFilter(SAPropertyFilter filter) {
return "Android".equals(filter.getEventJson(SAPropertyFilter.LIB).optString("$lib"));
} | @Test
public void isMatchedWithFilter() {
InternalCustomPropertyPlugin customPropertyPlugin = new InternalCustomPropertyPlugin();
SAPropertyFilter propertyFilter = new SAPropertyFilter();
JSONObject libProperty = new JSONObject();
try {
libProperty.put("$lib", "Android");... |
void format(FSNamesystem fsn, String clusterId, boolean force)
throws IOException {
long fileCount = fsn.getFilesTotal();
// Expect 1 file, which is the root inode
Preconditions.checkState(fileCount == 1,
"FSImage.format should be called with an uninitialized namesystem, has " +
fileCo... | @Test
public void testZeroBlockSize() throws Exception {
final Configuration conf = new HdfsConfiguration();
String tarFile = System.getProperty("test.cache.data", "build/test/cache")
+ "/" + HADOOP_2_7_ZER0_BLOCK_SIZE_TGZ;
String testDir = PathUtils.getTestDirName(getClass());
File dfsDir = new... |
@Override
public void execute(final ConnectionSession connectionSession) {
String databaseName = sqlStatement.getFromDatabase().map(schema -> schema.getDatabase().getIdentifier().getValue()).orElseGet(connectionSession::getUsedDatabaseName);
queryResultMetaData = createQueryResultMetaData(databaseNa... | @Test
void assertShowTablesExecutorWithUpperCase() throws SQLException {
MySQLShowTablesStatement showTablesStatement = new MySQLShowTablesStatement();
ShowFilterSegment showFilterSegment = mock(ShowFilterSegment.class);
when(showFilterSegment.getLike()).thenReturn(Optional.of(new ShowLikeSe... |
@Override
public Object[] toArray() {
Object[] array = new Object[size];
for (int i = 0; i < size; i++) {
array[i] = i;
}
return array;
} | @Test
public void toArray1() throws Exception {
RangeSet rs = new RangeSet(4);
Object[] array = rs.toArray(new Integer[4]);
assertEquals(4, array.length);
assertEquals(0, array[0]);
assertEquals(1, array[1]);
assertEquals(2, array[2]);
assertEquals(3, array[3]);
} |
@Override
public int hashCode() {
return Objects.hash(instanceType, filterDatabaseName(this));
} | @Test
void assertHashCodeEqualsForJdbcMode() {
PipelineContextKey contextKey1 = new PipelineContextKey("logic_db", InstanceType.JDBC);
PipelineContextKey contextKey2 = new PipelineContextKey("sharding_db", InstanceType.JDBC);
assertThat(contextKey1.hashCode(), not(contextKey2.hashCode()));
... |
static void handleDisable(Namespace namespace, Admin adminClient) throws TerseException {
FeatureUpdate.UpgradeType upgradeType = downgradeType(namespace);
Map<String, FeatureUpdate> updates = new HashMap<>();
List<String> features = namespace.getList("feature");
if (features != null) {... | @Test
public void testHandleDisable() {
Map<String, Object> namespace = new HashMap<>();
namespace.put("feature", Arrays.asList("foo.bar", "metadata.version", "quux"));
namespace.put("dry_run", false);
String disableOutput = ToolsTestUtils.captureStandardOut(() -> {
Throw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.