focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Object getValueFromResultSet( ResultSet rs, ValueMetaInterface val, int index ) throws KettleDatabaseException {
Object data;
try {
if ( val.getType() == ValueMetaInterface.TYPE_BINARY ) {
data = rs.getString( index + 1 );
} else {
return super.getValueFromResultSe... | @Test(expected = KettleDatabaseException.class)
public void testGetValueFromResultSetWhenExceptionIsComing() throws SQLException, KettleDatabaseException {
ResultSet rs = mock( ResultSet.class );
Mockito.when( rs.getString( 3 ) ).thenThrow( SQLException.class );
ValueMetaString ts = new ValueMetaString( "... |
static Object parseCell(String cell, Schema.Field field) {
Schema.FieldType fieldType = field.getType();
try {
switch (fieldType.getTypeName()) {
case STRING:
return cell;
case INT16:
return Short.parseShort(cell);
case INT32:
return Integer.parseInt(c... | @Test
public void givenCellUnsupportedType_throws() {
String counting = "[one,two,three]";
Schema schema =
Schema.builder()
.addField("an_array", Schema.FieldType.array(Schema.FieldType.STRING))
.addStringField("a_string")
.build();
UnsupportedOperationException... |
@Override
public int read() throws IOException {
Preconditions.checkState(!closed, "Cannot read: already closed");
singleByteBuffer.position(0);
pos += 1;
channel.read(singleByteBuffer);
readBytes.increment();
readOperations.increment();
return singleByteBuffer.array()[0] & 0xFF;
} | @Test
public void testReadSingle() throws Exception {
BlobId uri = BlobId.fromGsUtilUri("gs://bucket/path/to/read.dat");
int i0 = 1;
int i1 = 255;
byte[] data = {(byte) i0, (byte) i1};
writeGCSData(uri, data);
try (SeekableInputStream in =
new GCSInputStream(storage, uri, null, gcpPr... |
@Override
protected MemberData memberData(Subscription subscription) {
// Always deserialize ownedPartitions and generation id from user data
// since StickyAssignor is an eager rebalance protocol that will revoke all existing partitions before joining group
ByteBuffer userData = subscriptio... | @Test
public void testMemberDataWillHonorUserData() {
List<String> topics = topics(topic);
List<TopicPartition> ownedPartitions = partitions(tp(topic1, 0), tp(topic2, 1));
int generationIdInUserData = generationId - 1;
Subscription subscription = new Subscription(topics, generateUse... |
public List<ColumnMatchResult<?>> getMismatchedColumns(List<Column> columns, ChecksumResult controlChecksum, ChecksumResult testChecksum)
{
return columns.stream()
.flatMap(column -> columnValidators.get(column.getCategory()).get().validate(column, controlChecksum, testChecksum).stream())
... | @Test
public void testRow()
{
List<Column> columns = ImmutableList.of(ROW_COLUMN);
ChecksumResult controlChecksum = new ChecksumResult(ROW_COLUMN_CHECKSUMS.size(), ROW_COLUMN_CHECKSUMS);
assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, controlChecksum).isEmpty... |
@Override
public PageResult<TenantDO> getTenantPage(TenantPageReqVO pageReqVO) {
return tenantMapper.selectPage(pageReqVO);
} | @Test
public void testGetTenantPage() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> { // 等会查询到
o.setName("芋道源码");
o.setContactName("芋艿");
o.setContactMobile("15601691300");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
... |
@Override
public String toString() {
return channel.toString();
} | @Test
void toStringTest() {
Assertions.assertEquals(header.toString(), channel.toString());
} |
@Override
public void persistInstance(final InstanceEntity instance) {
try {
Instance inst = new Instance();
inst.setWeight(1.0d);
inst.setEphemeral(true);
inst.setIp(instance.getHost());
inst.setPort(instance.getPort());
inst.setInstan... | @Test
public void testPersistInstance() {
InstanceEntity data = InstanceEntity.builder()
.appName("shenyu-test")
.host("shenyu-host")
.port(9195)
.build();
final String key = "shenyu-test-group";
repository.persistInstance(data... |
public static void main(String[] args) {
LOGGER.info("Start Game Application using Data-Locality pattern");
var gameEntity = new GameEntity(NUM_ENTITIES);
gameEntity.start();
gameEntity.update();
} | @Test
void shouldExecuteGameApplicationWithoutException() {
assertDoesNotThrow(() -> Application.main(new String[]{}));
} |
public void replay(
long recordOffset,
long producerId,
OffsetCommitKey key,
OffsetCommitValue value
) {
final String groupId = key.group();
final String topic = key.topic();
final int partition = key.partition();
if (value != null) {
// T... | @Test
public void testReplay() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
verifyReplay(context, "foo", "bar", 0, new OffsetAndMetadata(
0L,
100L,
OptionalInt.empty(),
"small",
conte... |
@Override
protected void route(List<SendingMailbox> destinations, TransferableBlock block)
throws Exception {
int destinationIdx = _rand.apply(destinations.size());
sendBlock(destinations.get(destinationIdx), block);
} | @Test
public void shouldRouteRandomly()
throws Exception {
// Given:
ImmutableList<SendingMailbox> destinations = ImmutableList.of(_mailbox1, _mailbox2);
// When:
new RandomExchange(destinations, size -> 1, TransferableBlockUtils::splitBlock).route(destinations, _block);
ArgumentCaptor<Tra... |
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 shouldFormatDescribeSource() {
// Given:
final Statement statement = parseSingle("DESCRIBE ORDERS;");
// When:
final String result = SqlFormatter.formatSql(statement);
// Then:
assertThat(result, is("DESCRIBE ORDERS"));
} |
@Override
public ResultSet getSuperTypes(final String catalog, final String schemaPattern, final String typeNamePattern) {
return null;
} | @Test
void assertGetSuperTypes() {
assertNull(metaData.getSuperTypes("", "", ""));
} |
public static String humanize(String s) {
String[] strings = StringUtils.splitByCharacterTypeCamelCase(s);
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
strings[i] = string.toLowerCase();
}
return StringUtils.join(strings, " ");
} | @Test
public void shouldHumanize() throws Exception {
assertThat(humanize("camelCase"), is("camel case"));
assertThat(humanize("camel"), is("camel"));
assertThat(humanize("camelCaseForALongString"), is("camel case for a long string"));
} |
@Override
public ProcessContinuation run() {
// Read any available data.
for (Optional<SequencedMessage> next = subscriber.peek();
next.isPresent();
next = subscriber.peek()) {
SequencedMessage message = next.get();
Offset messageOffset = Offset.of(message.getCursor().getOffset());... | @Test
public void create() {
SubscriptionPartitionProcessor processor = newProcessor();
assertEquals(ProcessContinuation.resume(), processor.run());
InOrder order = inOrder(subscriber);
order.verify(subscriber).fetchOffset();
order.verify(subscriber).rebuffer();
} |
public long getChecksum() {
return this.checksum;
} | @Test
public void testChecksum() {
byte[] bytes1 = new byte[5];
byte[] bytes2 = new byte[10];
initBytes(bytes1);
initBytes(bytes2);
ByteBuffer buffer1 = ByteBuffer.wrap(bytes1);
ByteBuffer buffer2 = ByteBuffer.wrap(bytes2);
buffer2.limit(bytes1.length);
long checksum1 = BufferData.g... |
public IcebergRecordObjectInspector(
Types.StructType structType, List<ObjectInspector> objectInspectors) {
Preconditions.checkArgument(structType.fields().size() == objectInspectors.size());
this.structFields = Lists.newArrayListWithExpectedSize(structType.fields().size());
int position = 0;
f... | @Test
public void testIcebergRecordObjectInspector() {
Schema schema =
new Schema(
required(1, "integer_field", Types.IntegerType.get()),
required(
2,
"struct_field",
Types.StructType.of(
Types.NestedField.required... |
@Override
public Mono<UserDetails> findByUsername(String username) {
return userService.getUser(username)
.onErrorMap(UserNotFoundException.class,
e -> new BadCredentialsException("Invalid Credentials"))
.flatMap(user -> {
var name = user.getMetadata()... | @Test
void shouldFindHaloUserDetailsWith2faEnabledWhen2faEnabledAndTotpConfigured() {
var fakeUser = createFakeUser();
fakeUser.getSpec().setTwoFactorAuthEnabled(true);
fakeUser.getSpec().setTotpEncryptedSecret("fake-totp-encrypted-secret");
when(userService.getUser("faker")).thenRet... |
public static <F extends Future<Void>> Mono<Void> deferFuture(Supplier<F> deferredFuture) {
return new DeferredFutureMono<>(deferredFuture);
} | @Test
void raceTestDeferredFutureMono() {
for (int i = 0; i < 1000; i++) {
final TestSubscriber subscriber = new TestSubscriber();
final ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE;
final Promise<Void> promise = eventExecutor.newPromise();
final Supplier<Promise<Void>> promiseS... |
static void activateHttpAndHttpsProxies(Settings settings, SettingsDecrypter decrypter)
throws MojoExecutionException {
List<Proxy> proxies = new ArrayList<>(2);
for (String protocol : ImmutableList.of("http", "https")) {
if (areProxyPropertiesSet(protocol)) {
continue;
}
setting... | @Test
public void testActivateHttpAndHttpsProxies_dontOverwriteUserHttp()
throws MojoExecutionException {
System.setProperty("http.proxyHost", "host");
MavenSettingsProxyProvider.activateHttpAndHttpsProxies(
mixedProxyEncryptedSettings, settingsDecrypter);
Assert.assertNull(System.getProper... |
@Override
public Object get(PropertyKey key) {
return get(key, ConfigurationValueOptions.defaults());
} | @Test
public void sitePropertiesNotLoadedInTest() throws Exception {
Properties props = new Properties();
props.setProperty(PropertyKey.LOGGER_TYPE.toString(), "TEST_LOGGER");
File propsFile = mFolder.newFile(Constants.SITE_PROPERTIES);
props.store(new FileOutputStream(propsFile), "ignored header");
... |
public static Read read() {
return Read.create();
} | @Test
public void testReadWithoutValidate() {
final String table = "fooTable";
BigtableIO.Read read =
BigtableIO.read()
.withBigtableOptions(BIGTABLE_OPTIONS)
.withTableId(table)
.withoutValidation();
// validate() will throw if withoutValidation() isn't workin... |
public static boolean validatePlugin(PluginLookup.PluginType type, Class<?> pluginClass) {
switch (type) {
case INPUT:
return containsAllMethods(inputMethods, pluginClass.getMethods());
case FILTER:
return containsAllMethods(filterMethods, pluginClass.getM... | @Ignore("Test failing on windows for many weeks. See https://github.com/elastic/logstash/issues/10926")
@Test
public void testInvalidInputPlugin() throws IOException {
Path tempJar = null;
try {
tempJar = Files.createTempFile("pluginValidationTest", "inputPlugin.jar");
fi... |
public void validatePositionsIfNeeded() {
Map<TopicPartition, SubscriptionState.FetchPosition> partitionsToValidate =
offsetFetcherUtils.getPartitionsToValidate();
validatePositionsAsync(partitionsToValidate);
} | @Test
public void testOffsetValidationSkippedForOldResponse() {
// Old responses may provide unreliable leader epoch,
// so we should skip offset validation and not send the request.
buildFetcher();
assignFromUser(singleton(tp0));
Map<String, Integer> partitionCounts = new H... |
@ScalarOperator(GREATER_THAN)
@SqlType(StandardTypes.BOOLEAN)
public static boolean greaterThan(@SqlType("unknown") boolean left, @SqlType("unknown") boolean right)
{
throw new AssertionError("value of unknown type should all be NULL");
} | @Test
public void testGreaterThan()
{
assertFunction("NULL > NULL", BOOLEAN, null);
} |
public static String fromJavaPropertyToEnvVariable(String property) {
return property.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
} | @Test
public void fromJavaPropertyToEnvVariable() {
String output = SettingFormatter.fromJavaPropertyToEnvVariable("some.randomProperty-123.test");
assertThat(output).isEqualTo("SOME_RANDOMPROPERTY_123_TEST");
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final BoxApiClient client = new BoxApiClient(session.getClient());
final HttpGet request = new HttpGet(String.format("%s/files/%s/cont... | @Test
public void testReadRange() throws Exception {
final BoxFileidProvider fileid = new BoxFileidProvider(session);
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final byte[] content = R... |
@Override
public <I, K, V> Map<K, V> mapToPair(List<I> data, SerializablePairFunction<I, K, V> func, Integer parallelism) {
return data.stream().parallel().map(throwingMapToPairWrapper(func)).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
} | @Test
public void testMapToPair() {
List<String> mapList = Arrays.asList("spark_hudi", "flink_hudi");
Map<String, String> resultMap = context.mapToPair(mapList, x -> {
String[] splits = x.split("_");
return new ImmutablePair<>(splits[0], splits[1]);
}, 2);
Assertions.assertEquals(resultM... |
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
} | @Test
public void testTime() {
RedisClusterNode master = getFirstMaster();
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
} |
@Override
public boolean equals(Object object)
{
if (this == object)
{
return true;
}
if (object == null || getClass() != object.getClass())
{
return false;
}
CollectionResult<?, ?> that = (CollectionResult<?, ?>) object;
return Objects.equals(_elements, that._elements)
... | @Test(dataProvider = "testEqualsDataProvider")
public void testEquals
(
boolean shouldEquals,
@Nonnull CollectionResult<TestRecordTemplateClass.Foo, TestRecordTemplateClass.Bar> collectionResult,
@Nullable Object compareObject
)
{
assertEquals(collectionResult.equals(co... |
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.DOUBLE) double value)
{
try {
return Shorts.checkedCast(DoubleMath.roundToInt(value, HALF_UP));
}
catch (ArithmeticException | IllegalArgumentException e) {
... | @Test
public void testCastToSmallInt()
{
assertFunction("cast(" + (0x1.0p15 - 0.6) + " as smallint)", SMALLINT, Short.MAX_VALUE);
assertInvalidFunction("cast(DOUBLE '" + 0x1.0p15 + "' as smallint)", INVALID_CAST_ARGUMENT);
assertInvalidFunction("cast(9.2E9 as smallint)", INVALID_CAST_ARG... |
@Override
public SingleRuleConfiguration buildToBeCreatedRuleConfiguration(final LoadSingleTableStatement sqlStatement) {
SingleRuleConfiguration result = new SingleRuleConfiguration();
if (null != rule) {
result.getTables().addAll(rule.getConfiguration().getTables());
}
... | @Test
void assertBuild() {
LoadSingleTableStatement sqlStatement = new LoadSingleTableStatement(Collections.singletonList(new SingleTableSegment("ds_0", null, "foo")));
SingleRule rule = mock(SingleRule.class);
when(rule.getConfiguration()).thenReturn(new SingleRuleConfiguration());
... |
@Override
public boolean match(Message msg, StreamRule rule) {
Double msgVal = getDouble(msg.getField(rule.getField()));
if (msgVal == null) {
return false;
}
Double ruleVal = getDouble(rule.getValue());
if (ruleVal == null) {
return false;
}
... | @Test
public void testMissedInvertedMatchMissingField() {
StreamRule rule = getSampleRule();
rule.setValue("42");
rule.setInverted(true);
Message msg = getSampleMessage();
msg.addField("someother", "30");
StreamRuleMatcher matcher = getMatcher(rule);
assertF... |
static String buildUserPreferenceConfigMapName(String username) {
return "user-preferences-" + username;
} | @Test
void buildUserPreferenceConfigMapName() {
var preferenceConfigMapName = UserNotificationPreferenceServiceImpl
.buildUserPreferenceConfigMapName("guqing");
assertEquals("user-preferences-guqing", preferenceConfigMapName);
} |
Object getEventuallyWeightedResult(Object rawObject, MULTIPLE_MODEL_METHOD multipleModelMethod,
double weight) {
switch (multipleModelMethod) {
case MAJORITY_VOTE:
case MODEL_CHAIN:
case SELECT_ALL:
case SELECT_FIRST:
... | @Test
void getEventuallyWeightedResultNotImplemented() {
NOT_IMPLEMENTED_METHODS.forEach(multipleModelMethod -> {
try {
evaluator.getEventuallyWeightedResult("OBJ", multipleModelMethod, 34.2);
fail(multipleModelMethod + " is supposed to throw exception because not... |
@Udf(schema = "ARRAY<STRUCT<K STRING, V DOUBLE>>")
public List<Struct> entriesDouble(
@UdfParameter(description = "The map to create entries from") final Map<String, Double> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
return... | @Test
public void shouldComputeDoubleEntries() {
final Map<String, Double> map = createMap(Double::valueOf);
shouldComputeEntries(map, () -> entriesUdf.entriesDouble(map, false));
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
if(file.isPlaceholder()) {
final DescriptiveUrl link = new DriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http);
if(DescriptiveUrl.... | @Test
public void testReadWhitespace() throws Exception {
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path file = new DriveTouchFeature(session, fileid).touch(new Path(DriveHomeFinderService.MYDRIVE_FOLDER, String.format("t %s", new AlphanumericRandomStringService().ra... |
public String toJson(final Object object) {
return GSON.toJson(object);
} | @Test
public void testToJson() {
TestObject testObject = generateTestObject();
JsonElement expectedJson = JsonParser.parseString(EXPECTED_JSON);
JsonElement objectJson = JsonParser.parseString(GsonUtils.getInstance().toJson(testObject));
assertEquals(expectedJson, objectJson);
} |
@Override
public Optional<DispatchEvent> build(final DataChangedEvent event) {
if (Strings.isNullOrEmpty(event.getValue())) {
return Optional.empty();
}
Optional<QualifiedDataSource> qualifiedDataSource = QualifiedDataSourceNode.extractQualifiedDataSource(event.getKey());
... | @Test
void assertCreateDisabledQualifiedDataSourceChangedEvent() {
Optional<DispatchEvent> actual = new QualifiedDataSourceDispatchEventBuilder().build(
new DataChangedEvent("/nodes/qualified_data_sources/replica_query_db.readwrite_ds.replica_ds_0", "state: DISABLED\n", Type.DELETED));
... |
@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);
} |
private Map<String, Object> augmentAndFilterConnectorConfig(String connectorConfigs) throws IOException {
return augmentAndFilterConnectorConfig(connectorConfigs, instanceConfig, secretsProvider,
componentClassLoader, componentType);
} | @Test(dataProvider = "component")
public void testInterpolatingEnvironmentVariables(FunctionDetails.ComponentType componentType) throws Exception {
final Map<String, Object> parsedConfig = JavaInstanceRunnable.augmentAndFilterConnectorConfig(
"""
{
... |
@Override
public MepLbCreate decode(ObjectNode json, CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
JsonNode loopbackNode = json.get(LOOPBACK);
JsonNode remoteMepIdNode = loopbackNode.get(REMOTE_MEP_ID);
JsonNode remoteMepMacNode ... | @Test
public void testDecodeMepLbCreateMepMac() throws JsonProcessingException, IOException {
String loopbackString = "{\"loopback\": { " +
"\"remoteMepMac\": \"AA:BB:CC:DD:EE:FF\" }}";
InputStream input = new ByteArrayInputStream(
loopbackString.getBytes(StandardC... |
@Override
public OAuth2AccessTokenDO getAccessToken(String accessToken) {
// 优先从 Redis 中获取
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken);
if (accessTokenDO != null) {
return accessTokenDO;
}
// 获取不到,从 MySQL 中获取
accessToken... | @Test
public void testCheckAccessToken_success() {
// mock 数据(访问令牌)
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class)
.setExpiresTime(LocalDateTime.now().plusDays(1));
oauth2AccessTokenMapper.insert(accessTokenDO);
// 准备参数
String access... |
public static void removeDupes(
final List<CharSequence> suggestions, List<CharSequence> stringsPool) {
if (suggestions.size() < 2) return;
int i = 1;
// Don't cache suggestions.size(), since we may be removing items
while (i < suggestions.size()) {
final CharSequence cur = suggestions.get(i... | @Test
public void testRemoveDupesDupeIsNotFirst() throws Exception {
ArrayList<CharSequence> list =
new ArrayList<>(
Arrays.<CharSequence>asList("typed", "something", "duped", "duped", "something"));
IMEUtil.removeDupes(list, mStringPool);
Assert.assertEquals(3, list.size());
Asser... |
public static String buildCallPluginMethod(Class pluginClass, String method, String... paramValueAndType) {
return buildCallPluginMethod("getClass().getClassLoader()", pluginClass, method, paramValueAndType);
} | @Test
public void testBuildCallPluginMethod() throws Exception {
SimplePlugin plugin = new SimplePlugin();
registerPlugin(plugin);
// plugin.init(PluginManager.getInstance());
String s = PluginManagerInvoker.buildCallPluginMethod(plugin.getClass(),
"callPluginMethod",... |
public static void setFieldValue(Object target, Field field, Object fieldValue)
throws IllegalArgumentException, SecurityException {
if (target == null) {
throw new IllegalArgumentException("target must be not null");
}
while (true) {
if (!field.isAccessible(... | @Test
public void testSetFieldValue() throws NoSuchFieldException {
BranchDO branchDO = new BranchDO("xid123123", 123L, 1, 2.2, new Date());
ReflectionUtil.setFieldValue(branchDO, "xid", "xid456");
Assertions.assertEquals("xid456", branchDO.getXid());
} |
public User getUser(String username) throws UserNotFoundException {
if (username == null) {
throw new UserNotFoundException("Username cannot be null");
}
// Make sure that the username is valid.
username = username.trim().toLowerCase();
User user = userCache.get(usern... | @Test
public void canGetUserByUserNameForExistingUsers() throws Exception{
final User result = userManager.getUser(USER_ID);
assertThat(result.getUsername(), is(USER_ID));
assertThat(result.getEmail(), is("test-email@example.com"));
assertThat(result.getName(), is("Test User Name"));
... |
public RowMetaAndData getRow() {
RowMetaAndData r = new RowMetaAndData();
r.addValue(
new ValueMetaString(
BaseMessages.getString( PKG, "DatabaseImpact.RowDesc.Label.Type" ) ),
getTypeDesc() );
r.addValue( new ValueMetaString(
BaseMessages.getString( PKG, "DatabaseImpact.RowDesc.La... | @Test
public void testGetRow() throws KettleValueException {
DatabaseImpact testObject =
new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_READ, "myTrans", "aStep", "ProdDB", "DimCustomer",
"Customer_Key", "MyValue", "Calculator 2", "SELECT * FROM dimCustomer", "Some remarks" );
RowMetaAndDat... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
try {
final IRODSFileSystemAO fs = session.getClient();
final IRODSFileFactory factory = fs.getIRODSFileFactory();... | @Test
public void testRead() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/iRODS (iPlant Collaborat... |
@Override
@MethodNotAvailable
public Map<K, Object> executeOnEntries(com.hazelcast.map.EntryProcessor entryProcessor) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testExecuteOnEntries() {
adapter.executeOnEntries(new IMapReplaceEntryProcessor("value", "newValue"));
} |
@Override
public ApplicationInstanceStatus getApplicationInstanceStatus(ApplicationId appId) throws ApplicationIdNotFoundException {
ApplicationInstanceReference reference = OrchestratorUtil.toApplicationInstanceReference(appId, serviceMonitor);
return statusService.getApplicationInstanceStatus(refe... | @Test
public void application_has_initially_no_remarks() throws Exception {
assertEquals(NO_REMARKS, orchestrator.getApplicationInstanceStatus(app1));
} |
@Override
public boolean contains(K name) {
return false;
} | @Test
public void testContainsWithValue() {
assertFalse(HEADERS.contains("name1", "value1"));
} |
@ConstantFunction(name = "bitor", argTypes = {TINYINT, TINYINT}, returnType = TINYINT)
public static ConstantOperator bitorTinyInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createTinyInt((byte) (first.getTinyInt() | second.getTinyInt()));
} | @Test
public void bitorTinyInt() {
assertEquals(10, ScalarOperatorFunctions.bitorTinyInt(O_TI_10, O_TI_10).getTinyInt());
} |
public static Write write() {
return new AutoValue_SnsIO_Write.Builder().build();
} | @Test
public void testDataWritesToSNS() {
final PublishRequest request1 = createSampleMessage("my_first_message");
final PublishRequest request2 = createSampleMessage("my_second_message");
final TupleTag<PublishResult> results = new TupleTag<>();
final AmazonSNS amazonSnsSuccess = getAmazonSnsMockSuc... |
static SQLViewRepresentation fromJson(String json) {
return JsonUtil.parse(json, SQLViewRepresentationParser::fromJson);
} | @Test
public void testParseSqlViewRepresentation() {
String requiredFields =
"{\"type\":\"sql\", \"sql\": \"select * from foo\", \"dialect\": \"spark-sql\"}";
SQLViewRepresentation viewRepresentation =
ImmutableSQLViewRepresentation.builder()
.sql("select * from foo")
.... |
@Override
public Optional<EventProcessorSchedulerConfig> toJobSchedulerConfig(EventDefinition eventDefinition, JobSchedulerClock clock) {
final DateTime now = clock.nowUTC();
// We need an initial timerange for the first execution of the event processor
final AbsoluteRange timerange;
... | @Test
@MongoDBFixtures("aggregation-processors.json")
public void toJobSchedulerConfig() {
final EventDefinitionDto dto = dbService.get("54e3deadbeefdeadbeefaffe").orElse(null);
assertThat(dto).isNotNull();
assertThat(dto.config().toJobSchedulerConfig(dto, clock)).isPresent().get().sat... |
public Map<String, String> confirm(RdaConfirmRequest params) {
AppSession appSession = appSessionService.getSession(params.getAppSessionId());
AppAuthenticator appAuthenticator = appAuthenticatorService.findByUserAppId(appSession.getUserAppId());
if(!checkSecret(params, appSession) || !checkAcc... | @Test
void checkErrorError(){
rdaConfirmRequest.setError("CANCELLED");
when(appSessionService.getSession(any())).thenReturn(appSession);
when(appAuthenticatorService.findByUserAppId(any())).thenReturn(appAuthenticator);
Map<String, String> result = rdaService.confirm(rdaConfirmRequ... |
@VisibleForTesting
static UUnionType create(UExpression... typeAlternatives) {
return create(ImmutableList.copyOf(typeAlternatives));
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UUnionType.create(
UClassIdent.create("java.lang.IllegalArgumentException"),
UClassIdent.create("java.lang.IllegalStateException")));
} |
@Override
public ClusterInfo clusterGetClusterInfo() {
RFuture<Map<String, String>> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO);
Map<String, String> entries = syncFuture(f);
Properties props = new Properties();
for (Entry<String, Str... | @Test
public void testClusterGetClusterInfo() {
ClusterInfo info = connection.clusterGetClusterInfo();
assertThat(info.getSlotsFail()).isEqualTo(0);
assertThat(info.getSlotsOk()).isEqualTo(MasterSlaveConnectionManager.MAX_SLOT);
assertThat(info.getSlotsAssigned()).isEqualTo(MasterSla... |
public static InstanceAssignmentConfig getInstanceAssignmentConfig(TableConfig tableConfig,
InstancePartitionsType instancePartitionsType) {
Preconditions.checkState(allowInstanceAssignment(tableConfig, instancePartitionsType),
"Instance assignment is not allowed for the given table config");
// ... | @Test
public void testGetInstanceAssignmentConfigWhenInstanceAssignmentConfigIsNotPresentAndPartitionColumnNotPresent() {
TagOverrideConfig tagOverrideConfig = new TagOverrideConfig("broker", "Server");
Map<InstancePartitionsType, String> instancePartitionsTypeStringMap = new HashMap<>();
instancePartit... |
static double evaluateRaw(boolean isCaseSensitive,
boolean tokenize,
String term,
String text,
String wordSeparatorCharacterRE,
LOCAL_TERM_WEIGHTS localTermWeights,
... | @Test
void evaluateRawTokenize() {
LevenshteinDistance levenshteinDistance = new LevenshteinDistance(2);
double frequency = 3.0;
double logarithmic = Math.log10(1 + frequency);
int maxFrequency = 2;
double augmentedNormalizedTermFrequency = 0.5 * (1 + (frequency / (double) ma... |
String getUrl() {
return "http://" + this.httpServer.getInetAddress().getHostAddress() + ":" + this.httpServer.getLocalPort();
} | @Test
public void action_is_matched_on_exact_URL() throws IOException {
Response response = call(underTest.getUrl() + "/pompom");
assertIsPomPomResponse(response);
} |
public SourceWithMetadata lookupSource(int globalLineNumber, int sourceColumn)
throws IncompleteSourceWithMetadataException {
LineToSource lts = this.sourceReferences().stream()
.filter(lts1 -> lts1.includeLine(globalLineNumber))
.findFirst()
.orElseTh... | @Test(expected = IllegalArgumentException.class)
public void testSourceAndLineRemapping_pipelineDefinedMInMultipleFiles_dontmatch() throws IncompleteSourceWithMetadataException {
final SourceWithMetadata[] parts = {
new SourceWithMetadata("file", "/tmp/input", 0, 0, PIPELINE_CONFIG_PART_1),
... |
public static OAuthBearerValidationResult validateScope(OAuthBearerToken token, List<String> requiredScope) {
final Set<String> tokenScope = token.scope();
if (requiredScope == null || requiredScope.isEmpty())
return OAuthBearerValidationResult.newSuccess();
for (String requiredScope... | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void validateScope() {
long nowMs = TIME.milliseconds();
double nowClaimValue = ((double) nowMs) / 1000;
final List<String> noScope = Collections.emptyList();
final List<String> scope1 = Collections.singletonList("scope1")... |
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava3CircuitBreakerAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava3CircuitBreakerAspectExt.canHandleReturnType(Single.class)).isTrue();
} |
private <T> RestResponse<T> get(final String path, final Class<T> type) {
return executeRequestSync(HttpMethod.GET,
path,
null,
r -> deserialize(r.getBody(), type),
Optional.empty());
} | @Test
public void shouldPostQueryRequest_chunkHandler_exception() {
ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST,
Collections.emptyMap(), RequestOptions.DEFAULT_TIMEOUT);
executor.submit(this::expectPostQueryRequestChunkHandler);
assertThatEventually(re... |
public static ByteString encodeDoubleDistribution(
long count, double sum, double min, double max) {
ByteStringOutputStream output = new ByteStringOutputStream();
try {
VARINT_CODER.encode(count, output);
DOUBLE_CODER.encode(sum, output);
DOUBLE_CODER.encode(min, output);
DOUBLE_CO... | @Test
public void testDoubleDistributionEncoding() {
ByteString payload = encodeDoubleDistribution(1L, 2.0, 3.0, 4.0);
assertEquals(
ByteString.copyFrom(
new byte[] {
1, 64, 0, 0, 0, 0, 0, 0, 0, 64, 8, 0, 0, 0, 0, 0, 0, 64, 16, 0, 0, 0, 0, 0, 0
}),
payload... |
@Nullable
@Override
public Message decode(@Nonnull final RawMessage rawMessage) {
final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
final String json = gelfMessage.getJSON(decompressSizeLimit, charset);
final JsonNode node;
... | @Test
public void decodeSucceedsWithValidTimestampAsStringIssue4027() throws Exception {
// https://github.com/Graylog2/graylog2-server/issues/4027
final String json = "{"
+ "\"version\": \"1.1\","
+ "\"short_message\": \"A short message that helps you identify what i... |
private Function<KsqlConfig, Kudf> getUdfFactory(
final Method method,
final UdfDescription udfDescriptionAnnotation,
final String functionName,
final FunctionInvoker invoker,
final String sensorName
) {
return ksqlConfig -> {
final Object actualUdf = FunctionLoaderUtils.instan... | @Test
public void shouldLoadFunctionWithListReturnType() {
// Given:
final UdfFactory toList = FUNC_REG.getUdfFactory(FunctionName.of("tolist"));
// When:
final List<SqlArgument> args = Collections.singletonList(SqlArgument.of(SqlTypes.STRING));
final KsqlScalarFunction function
= toList.... |
@Override
public void open(int taskNumber, int numTasks) throws IOException {
Preconditions.checkState(
numTasks == 1, "SavepointOutputFormat should only be executed with parallelism 1");
targetLocation = createSavepointLocation(savepointPath);
} | @Test(expected = IllegalStateException.class)
public void testSavepointOutputFormatOnlyWorksWithParallelismOne() throws Exception {
Path path = new Path(temporaryFolder.newFolder().getAbsolutePath());
SavepointOutputFormat format = createSavepointOutputFormat(path);
format.open(0, 2);
} |
@Override
public Object getDefaultValue() {
return defaultValue;
} | @Test
public void testGetDefaultValue() throws Exception {
TextField f = new TextField("test", "Name", "default", "description");
assertEquals("default", f.getDefaultValue());
} |
public boolean isSatisfy(DistributionSpec spec) {
if (spec.type.equals(DistributionType.ANY)) {
return true;
}
return spec instanceof RoundRobinDistributionSpec;
} | @Test
void isSatisfy() {
DistributionSpec rr = new RoundRobinDistributionSpec();
assertTrue(rr.isSatisfy(AnyDistributionSpec.INSTANCE));
assertTrue(rr.isSatisfy(new RoundRobinDistributionSpec()));
assertFalse(rr.isSatisfy(new ReplicatedDistributionSpec()));
} |
@Override
public String resolve(Method method, Object[] arguments, String spelExpression) {
if (StringUtils.isEmpty(spelExpression)) {
return spelExpression;
}
if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) {
return stringValueReso... | @Test
public void beanMethodSpelTest() throws Exception {
String testExpression = "@dummySpelBean.getBulkheadName(#parameter)";
String testMethodArg = "argg";
String bulkheadName = "sgt. bulko";
DefaultSpelResolverTest target = new DefaultSpelResolverTest();
Method testMethod... |
CompletableFuture<String> stopWithSavepoint(
@Nullable final String targetDirectory,
boolean terminate,
SavepointFormatType formatType) {
final ExecutionGraph executionGraph = getExecutionGraph();
StopWithSavepointTerminationManager.checkSavepointActionPreconditions(... | @Test
void testTransitionToStopWithSavepointState() throws Exception {
try (MockExecutingContext ctx = new MockExecutingContext()) {
CheckpointCoordinator coordinator =
new CheckpointCoordinatorTestingUtils.CheckpointCoordinatorBuilder()
.build(EXE... |
public static String[] concat(String[] array1, String[] array2) {
if (array1.length == 0) {
return array2;
}
if (array2.length == 0) {
return array1;
}
String[] resultArray = new String[array1.length + array2.length];
System.arraycopy(array1, 0, re... | @Test
void concatArrays() {
String[] array1 = new String[] {"A", "B", "C", "D", "E", "F", "G"};
String[] array2 = new String[] {"1", "2", "3"};
assertThat(ArrayUtils.concat(array1, array2))
.isEqualTo(new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3"});
... |
@Override
public int chown(String path, long uid, long gid) {
return AlluxioFuseUtils.call(LOG, () -> chownInternal(path, uid, gid),
FuseConstants.FUSE_CHOWN, "path=%s,uid=%d,gid=%d", path, uid, gid);
} | @Test
@DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu",
comment = "waiting on security metadata to be implemented in Dora")
@Ignore
public void chownWithoutValidGid() throws Exception {
Optional<Long> uid = AlluxioFuseUtils.getUid(System.getProperty("user.name"));
assertTrue(... |
@VisibleForTesting
OutputBufferMemoryManager getMemoryManager()
{
return memoryManager;
} | @Test
public void testSharedBufferBlockingNoBlockOnFull()
{
SettableFuture<?> blockedFuture = SettableFuture.create();
MockMemoryReservationHandler reservationHandler = new MockMemoryReservationHandler(blockedFuture);
AggregatedMemoryContext memoryContext = newRootAggregatedMemoryContext... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldThrowOnAlterCAS() {
// Given:
givenCreateStream();
cmdExec.execute(SQL_TEXT, createStream, true, NO_QUERY_SOURCES);
alterSource = new AlterSourceCommand(STREAM_NAME, DataSourceType.KSTREAM.getKsqlType(), NEW_COLUMNS);
// When:
final KsqlException e = assertThrows(KsqlE... |
boolean hasProjectionMaskApi(JClass definedClass, ClassTemplateSpec templateSpec)
{
return _hasProjectionMaskCache.computeIfAbsent(definedClass, (jClass) ->
{
try
{
final Class<?> clazz = _classLoader.loadClass(jClass.fullName());
return Arrays.stream(clazz.getClasses()).anyMatch(
... | @Test
public void testHasProjectionMaskApiClassFoundWithProjectionMask() throws Exception
{
ProjectionMaskApiChecker projectionMaskApiChecker = new ProjectionMaskApiChecker(
_templateSpecGenerator, _sourceFiles, _classLoader);
Mockito.when(_nestedTypeSource.getAbsolutePath()).thenReturn(pegasusDir ... |
@Override
public void write(String key, InputStream data) {
checkNotNull(data);
try {
write(key, data.readAllBytes());
} catch (IOException e) {
throw new IllegalStateException("Failed to read sensor write cache data", e);
}
} | @Test
public void dont_write_if_its_pull_request() {
byte[] b1 = new byte[] {1, 2, 3};
when(branchConfiguration.isPullRequest()).thenReturn(true);
writeCache.write("key1", b1);
writeCache.write("key2", new ByteArrayInputStream(b1));
assertThatCacheContains(Map.of());
} |
public static byte[] signMessage(
final RawPrivateTransaction privateTransaction, final Credentials credentials) {
final byte[] encodedTransaction = encode(privateTransaction);
final Sign.SignatureData signatureData =
Sign.signMessage(encodedTransaction, credentials.getEcKeyP... | @Test
public void testSign1559Transaction() {
final String expected =
"0x02f8d48207e2800101832dc6c094627306090abab3a6e1400e9345bc60c78a8bef57808001a0c4b5ae238eaa5cb154788d675ff61946e6886bfcc007591042d6a7daf14cbd6fa047f417ac1923e7e6adc77b3384dc1dd3bdf9208e4f1e5436775d56e5f595e249a0035695b4cc4... |
public static <T> AsList<T> asList() {
return new AsList<>(null, false);
} | @Test
@Category(ValidatesRunner.class)
public void testEmptyListSideInput() throws Exception {
final PCollectionView<List<Integer>> view =
pipeline.apply("CreateEmptyView", Create.empty(VarIntCoder.of())).apply(View.asList());
PCollection<Integer> results =
pipeline
.apply("Cre... |
@Override
public Space get() throws BackgroundException {
try {
final AccountSettingsApi account = new AccountSettingsApi(session.getClient());
final AccountStorage quota = account.accountSettingsGetAccountStorage();
return new Space(quota.getUsed(), quota.getAvailable())... | @Test
public void get() throws Exception {
final Quota.Space quota = new StoregateQuotaFeature(session, new StoregateIdProvider(session)).get();
assertNotNull(quota.available);
assertNotNull(quota.used);
assertNotEquals(0L, quota.available, 0L);
assertNotEquals(0L, quota.used... |
public ProcessContinuation run(
PartitionRecord partitionRecord,
RestrictionTracker<StreamProgress, StreamProgress> tracker,
OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator)
throws IOException {
BytesThroughputEstimator<... | @Test
public void testCloseStreamWritesContinuationTokens() throws IOException {
// Force lock fail because CloseStream should not depend on locking
when(metadataTableDao.doHoldLock(partition, uuid)).thenReturn(false);
ChangeStreamContinuationToken tokenAB =
ChangeStreamContinuationToken.create(By... |
@Override
public V fetch(final K key,
final long time) {
return getValueOrNull(inner.fetch(key, time));
} | @Test
public void shouldReturnPlainKeyValuePairsOnRangeFetchLongParameters() {
when(mockedKeyValueWindowTimestampIterator.next())
.thenReturn(KeyValue.pair(
new Windowed<>("key1", new TimeWindow(21L, 22L)),
ValueAndTimestamp.make("value1", 22L)))
.then... |
public PiPreReplica(PortNumber egressPort, int instanceId) {
this.egressPort = checkNotNull(egressPort);
this.instanceId = instanceId;
} | @Test
public void testPiPreReplica() {
assertThat("Invalid port", replica1of1.egressPort(), is(port1));
assertThat("Invalid instance ID", replica1of1.instanceId(), is(instanceId1));
assertThat("Invalid port", replica1of2.egressPort(), is(port2));
assertThat("Invalid instance ID", rep... |
static void quoteExternalName(StringBuilder sb, String externalName) {
List<String> parts = splitByNonQuotedDots(externalName);
for (int i = 0; i < parts.size(); i++) {
String unescaped = unescapeQuotes(parts.get(i));
String unquoted = unquoteIfQuoted(unescaped);
DIAL... | @Test
public void quoteExternalName_with_space() {
String externalName = "schema with space.table with space";
StringBuilder sb = new StringBuilder();
MappingHelper.quoteExternalName(sb, externalName);
assertThat(sb.toString()).isEqualTo("\"schema with space\".\"table with space\"");... |
public static long getImmunityTime(String checkImmunityTimeStr, long transactionTimeout) {
long checkImmunityTime = 0;
try {
checkImmunityTime = Long.parseLong(checkImmunityTimeStr) * 1000;
} catch (Throwable ignored) {
}
//If a custom first check time is set, the m... | @Test
public void testGetImmunityTime() {
long transactionTimeout = 6 * 1000;
String checkImmunityTimeStr = "1";
long immunityTime = TransactionalMessageUtil.getImmunityTime(checkImmunityTimeStr, transactionTimeout);
Assert.assertEquals(6 * 1000, immunityTime);
checkImmunit... |
public FloatArrayAsIterable usingExactEquality() {
return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_containsAtLeast_primitiveFloatArray_failure() {
expectFailureWhenTestingThat(array(1.1f, 2.2f, 3.3f))
.usingExactEquality()
.containsAtLeast(array(2.2f, 99.99f));
assertFailureKeys(
"value of",
"missing (1)",
"---",
"expected... |
public PageListResponse<IndexSetFieldTypeSummary> getIndexSetFieldTypeSummary(final Set<String> streamIds,
final String fieldName,
final Predicate<String> i... | @Test
void testDoesNotReturnResultsForIndexSetsIfUserMissesPriviledges() {
Predicate<String> indexSetPermissionPredicateAlwaysReturningFalse = x -> false;
doReturn(Set.of("index_set_id")).when(streamService).indexSetIdsByIds(Set.of("stream_id"));
final PageListResponse<IndexSetFieldTypeSumma... |
@Override
public void accept(Props props) {
if (isClusterEnabled(props)) {
checkClusterProperties(props);
}
} | @Test
@UseDataProvider("validIPv4andIPv6Addresses")
public void accept_throws_MessageException_if_internal_property_for_startup_leader_is_configured(String host) {
TestAppSettings settings = newSettingsForAppNode(host, of("sonar.cluster.web.startupLeader", "true"));
ClusterSettings clusterSettings = new Clu... |
public String getEffectiveMainBranchName() {
return configuration.get(SONAR_PROJECTCREATION_MAINBRANCHNAME).orElse(DEFAULT_MAIN_BRANCH_NAME);
} | @Test
public void getEffectiveMainBranchName_givenDevelopInConfiguration_returnDevelop() {
Configuration config = mock(Configuration.class);
when(config.get(SONAR_PROJECTCREATION_MAINBRANCHNAME)).thenReturn(Optional.of("develop"));
DefaultBranchNameResolver defaultBranchNameResolver = new DefaultBranchNam... |
public abstract T_Sess loadRawSession(OmemoDevice userDevice, OmemoDevice contactsDevice) throws IOException; | @Test
public void loadNonExistentRawSessionReturnsNullTest() throws IOException {
T_Sess session = store.loadRawSession(alice, bob);
assertNull(session);
} |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public Long createTenant(TenantSaveReqVO createReqVO) {
// 校验租户名称是否重复
validTenantNameDuplicate(createReqVO.getName(), null);
// 校验租户域名是否重复
validTenantWebsiteDuplicate(createReqVO.getWebsite(), null);
/... | @Test
public void testCreateTenant() {
// mock 套餐 100L
TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L));
when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage);
// mock 角色 200L
when(roleService.createRole(argThat... |
public UiTopoLayout offsetY(double offsetY) {
this.offsetY = offsetY;
return this;
} | @Test
public void setYOff() {
mkOtherLayout();
layout.offsetY(2.71828);
assertEquals("wrong y-offset", 2.71828, layout.offsetY(), DELTA);
} |
public static NetworkInterface[] filterBySubnet(final InetAddress address, final int subnetPrefix)
throws SocketException
{
return filterBySubnet(NetworkInterfaceShim.DEFAULT, address, subnetPrefix);
} | @Test
void shouldFilterBySubnetAndFindMultipleIpV6ResultsOrderedByMatchLength() throws Exception
{
final NetworkInterfaceStub stub = new NetworkInterfaceStub();
stub.add("ee80:0:0:0001:0:0:0:1/64");
final NetworkInterface ifc1 = stub.add("fe80:0:0:0:0:0:0:1/16");
final NetworkIn... |
public List<String> generate(String tableName, String columnName, boolean isAutoGenerated) throws SQLException {
return generate(tableName, singleton(columnName), isAutoGenerated);
} | @Test
public void generate_for_postgres_sql_no_seq() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(dbConstraintFinder.getPostgresSqlSequence(TABLE_NAME, "id")).thenReturn(null);
when(db.getDialect()).thenReturn(POSTGRESQL);
Lis... |
public void fillMaxSpeed(Graph graph, EncodingManager em) {
// In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info,
// but now we have and can fill the country-dependent max_speed value where missing.
EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(... | @Test
public void testDifferentStates() {
ReaderWay way = new ReaderWay(0L);
way.setTag("country", Country.USA);
way.setTag("highway", "primary");
way.setTag("country_state", State.US_CA);
EdgeIteratorState edge1 = createEdge(way);
way.setTag("country_state", State.U... |
public boolean is32BitsEnough() {
switch (bitmapType) {
case EMPTY:
return true;
case SINGLE_VALUE:
return isLongValue32bitEnough(singleValue);
case BITMAP_VALUE:
return bitmap.is32BitsEnough();
case SET_VALUE: {
... | @Test
public void testIs32BitsEnough() {
BitmapValue bitmapValue = new BitmapValue();
bitmapValue.add(0);
bitmapValue.add(2);
bitmapValue.add(Integer.MAX_VALUE);
// unsigned 32-bit
long unsigned32bit = Integer.MAX_VALUE;
bitmapValue.add(unsigned32bit + 1);
... |
@Override
protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName)
throws Exception {
Message in = exchange.getIn();
MetricsTimerAction action = endpoint.getAction();
MetricsTimerAction finalAction = in.getHeader(HEADER_TI... | @Test
public void testProcessStart() throws Exception {
when(endpoint.getAction()).thenReturn(MetricsTimerAction.start);
when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class))
.thenReturn(MetricsTimerAction.start);
when(exchange.getPropert... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.