focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Config getConfig(
Configuration configuration, @Nullable HostAndPort externalAddress) {
return getConfig(
configuration,
externalAddress,
null,
PekkoUtils.getForkJoinExecutorConfig(
ActorSystemBoots... | @Test
void getConfigNormalizesHostName() {
final Configuration configuration = new Configuration();
final String hostname = "AbC123foOBaR";
final int port = 1234;
final Config config = PekkoUtils.getConfig(configuration, new HostAndPort(hostname, port));
assertThat(config.g... |
public static Map<?, ?> convertToMap(Schema schema, Object value) {
return convertToMapInternal(MAP_SELECTOR_SCHEMA, value);
} | @Test
public void shouldFailToParseStringOfMapWithIntValuesWithBlankEntry() {
assertThrows(DataException.class,
() -> Values.convertToMap(Schema.STRING_SCHEMA, " { \"foo\" : 1234567890 ,, \"bar\" : 0, \"baz\" : -987654321 } "));
} |
public FlowWithSource importFlow(String tenantId, String source) {
return this.importFlow(tenantId, source, false);
} | @Test
void importFlow() {
String source = """
id: import
namespace: some.namespace
tasks:
- id: task
type: io.kestra.plugin.core.log.Log
message: Hello""";
Flow importFlow = flowService.importFlow("my-tenant", source);
... |
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
if ("img".equals(localName) && attributes.getValue("alt") != null) {
String nfo = "[image: " + a... | @Test
public void aTagTest() throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
XHTMLContentHandler xhtml = new XHTMLContentHandler(new RichTextContentHandler(
new OutputStreamWriter(buffer, UTF_8)), new Metadata());
xhtml.startDocument();
... |
public QueueOperationResponse deleteMessage(final Exchange exchange) {
ObjectHelper.notNull(exchange, MISSING_EXCHANGE);
final String messageId = configurationOptionsProxy.getMessageId(exchange);
final String popReceipt = configurationOptionsProxy.getPopReceipt(exchange);
final Duration... | @Test
public void testDeleteMessage() {
// mocking
final HttpHeaders httpHeaders = new HttpHeaders().set("x-test-header", "123");
when(client.deleteMessage(any(), any(), any())).thenReturn(new ResponseBase<>(null, 200, httpHeaders, null, null));
final QueueOperations operations = ne... |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof HttpQueryParams)) {
return false;
}
HttpQueryParams hqp2 = (HttpQueryParams) obj;
return Iterables.elementsEqual(delegate.entries(), hqp2.del... | @Test
void testEquals() {
HttpQueryParams qp1 = new HttpQueryParams();
qp1.add("k1", "v1");
qp1.add("k2", "v2");
HttpQueryParams qp2 = new HttpQueryParams();
qp2.add("k1", "v1");
qp2.add("k2", "v2");
assertEquals(qp1, qp2);
} |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testEqualToNaN() {
String col = "col";
NamedReference namedReference = FieldReference.apply(col);
LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType);
org.apache.spark.sql.connector.expressions.Expression[] attrAndValue =
new org.apache.spark.sql.connector.... |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testUpdateFetchPositionNoOpWithPositionSet() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 5L);
offsetFetcher.resetPositionsIfNeeded();
assertFalse(client.hasInFlightRequests());
assertTrue(subscriptions.isFetchable(tp0))... |
protected boolean initNextRecordReader() throws IOException {
if (curReader != null) {
curReader.close();
curReader = null;
if (idx > 0) {
progress += split.getLength(idx-1); // done processing so far
}
}
// if all chunks have been processed, nothing more to do.
if (... | @SuppressWarnings("unchecked")
@Test
public void testInitNextRecordReader() throws IOException{
JobConf conf = new JobConf();
Path[] paths = new Path[3];
long[] fileLength = new long[3];
File[] files = new File[3];
LongWritable key = new LongWritable(1);
Text value = new Text();
try {
... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertDatetime() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE)
.build();
BasicTypeDefine typeDefine = SapHanaTypeConverter.INSTAN... |
private GenericRow unnestCollection(GenericRow record, String column) {
Object value = record.getValue(GenericRow.MULTIPLE_RECORDS_KEY);
if (value == null) {
List<GenericRow> list = new ArrayList<>();
unnestCollection(record, column, list);
record.putValue(GenericRow.MULTIPLE_RECORDS_KEY, list... | @Test
public void testUnnestCollection() {
// unnest root level collection
// {
// "array":[
// {
// "a":"v1"
// },
// {
// "a":"v2"
// }
// ]}
// ->
// [{
// "array.a":"v1"
// },
// {
// "a... |
@Override
public void broadcastOnIssueChange(List<DefaultIssue> issues, Collection<QGChangeEvent> changeEvents, boolean fromAlm) {
if (listeners.isEmpty() || issues.isEmpty() || changeEvents.isEmpty()) {
return;
}
try {
broadcastChangeEventsToBranches(issues, changeEvents, fromAlm);
} cat... | @Test
public void broadcastOnIssueChange_calls_listener_for_each_component_uuid_with_at_least_one_QGChangeEvent() {
// branch has multiple issues
BranchDto component2 = newBranchDto(project1Uuid + "2");
DefaultIssue[] component2Issues = {newDefaultIssue(component2.getUuid()), newDefaultIssue(component2.ge... |
public Integer remove(final Object key)
{
return valOrNull(remove((int)key));
} | @Test
void removeShouldReturnMissing()
{
assertEquals(MISSING_VALUE, map.remove(1));
} |
public static byte[] encode(String s) {
return s == null ? new byte[0] : s.getBytes(RpcConstants.DEFAULT_CHARSET);
} | @Test
public void encode() {
Assert.assertTrue(StringSerializer.encode("11").length == 2);
Assert.assertTrue(StringSerializer.encode("").length == 0);
Assert.assertTrue(StringSerializer.encode(null).length == 0);
} |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldReportMisconfigurationsOfPartitionCount() {
setupTopicInMockAdminClient(topic1, repartitionTopicConfig());
setupTopicInMockAdminClient(topic2, repartitionTopicConfig());
setupTopicInMockAdminClient(topic3, repartitionTopicConfig());
final InternalTopicConfig i... |
@Override
@Cacheable(value = RedisKeyConstants.ROLE, key = "#id",
unless = "#result == null")
public RoleDO getRoleFromCache(Long id) {
return roleMapper.selectById(id);
} | @Test
public void testGetRoleFromCache() {
// mock 数据(缓存)
RoleDO roleDO = randomPojo(RoleDO.class);
roleMapper.insert(roleDO);
// 参数准备
Long id = roleDO.getId();
// 调用
RoleDO dbRoleDO = roleService.getRoleFromCache(id);
// 断言
assertPojoEquals(r... |
public static <K, V> WriteRecords<K, V> writeRecords() {
return new AutoValue_KafkaIO_WriteRecords.Builder<K, V>()
.setProducerConfig(WriteRecords.DEFAULT_PRODUCER_PROPERTIES)
.setEOS(false)
.setNumShards(0)
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setBa... | @Test
public void testSinkToMultipleTopics() throws Exception {
// Set different output topic names
int numElements = 1000;
try (MockProducerWrapper producerWrapper = new MockProducerWrapper(new LongSerializer())) {
ProducerSendCompletionThread completionThread =
new ProducerSendCompleti... |
@Override
public ProcessingResult process(ReplicationTask task) {
try {
EurekaHttpResponse<?> httpResponse = task.execute();
int statusCode = httpResponse.getStatusCode();
Object entity = httpResponse.getEntity();
if (logger.isDebugEnabled()) {
... | @Test
public void testBatchableTaskPermanentFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
InstanceInfo instanceInfoFromPeer = InstanceInfoGenerator.takeOne();
replicationClient.withNetworkStatusCode(200);
replicationClient.wi... |
Map<Address, int[]> getRemotePartitionAssignment() {
return remotePartitionAssignment;
} | @Test
public void testRemotePartitionAssignment() {
assertEquals(2, a.getRemotePartitionAssignment().size()); // only remote members are included
assertArrayEquals(new int[]{2, 4}, a.getRemotePartitionAssignment().get(a1));
assertArrayEquals(new int[]{1, 5}, a.getRemotePartitionAssignment().... |
@Override
public boolean addAggrConfigInfo(final String dataId, final String group, String tenant, final String datumId,
String appName, final String content) {
String appNameTmp = StringUtils.isBlank(appName) ? StringUtils.EMPTY : appName;
String tenantTmp = StringUtils.isBlank(tenant) ... | @Test
void testAddAggrConfigInfoOfUpdateNotEqualContent() {
String dataId = "dataId111";
String group = "group";
String tenant = "tenant";
String datumId = "datumId";
String appName = "appname1234";
String content = "content1234";
//mock query datumId... |
public static String getMasterForEntry(JournalEntry entry) {
if (entry.hasAddMountPoint()
|| entry.hasAsyncPersistRequest()
|| entry.hasAddSyncPoint()
|| entry.hasActiveSyncTxId()
|| entry.hasCompleteFile()
|| entry.hasDeleteFile()
|| entry.hasDeleteMountPoint()
... | @Test
public void testEntries() {
for (JournalEntry entry : ENTRIES) {
assertNotNull(JournalEntryAssociation.getMasterForEntry(entry));
}
} |
@Override
public boolean removeAll(Collection<?> c) {
boolean changed = false;
Iterator<?> iter = c.iterator();
while (iter.hasNext()) {
changed |= remove(iter.next());
}
return changed;
} | @Test
public void testRemoveAll() {
LOG.info("Test remove all");
for (Integer i : list) {
assertTrue(set.add(i));
}
for (int i = 0; i < NUM; i++) {
assertTrue(set.remove(list.get(i)));
}
// the deleted elements should not be there
for (int i = 0; i < NUM; i++) {
assertFal... |
public SchemaMapping fromParquet(MessageType parquetSchema) {
List<Type> fields = parquetSchema.getFields();
List<TypeMapping> mappings = fromParquet(fields);
List<Field> arrowFields = fields(mappings);
return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings);
} | @Test
public void testParquetInt64TimestampMillisToArrow() {
MessageType parquet = Types.buildMessage()
.addField(Types.optional(INT64)
.as(LogicalTypeAnnotation.timestampType(true, MILLIS))
.named("a"))
.named("root");
Schema expected = new Schema(asList(field("a", new... |
public static void warn(Logger logger, String msg, Throwable e) {
if (logger == null) {
return;
}
if (logger.isWarnEnabled()) {
logger.warn(msg, e);
}
} | @Test
void testWarn() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isWarnEnabled()).thenReturn(true);
LogHelper.warn(logger, "warn");
verify(logger).warn("warn");
Throwable t = new RuntimeException();
LogHelper.warn(logger, t);
verify(logger).warn... |
@Description("F cdf given the numerator degrees of freedom (df1), denominator degrees of freedom (df2) parameters, and value")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double fCdf(
@SqlType(StandardTypes.DOUBLE) double df1,
@SqlType(StandardTypes.DOUBLE) double df... | @Test
public void testFCdf()
{
assertFunction("round(f_cdf(2.0, 5.0, 0.7988), 4)", DOUBLE, 0.5);
assertFunction("round(f_cdf(2.0, 5.0, 3.7797), 4)", DOUBLE, 0.9);
assertInvalidFunction("f_cdf(0, 3, 0.5)", "fCdf Function: numerator df must be greater than 0");
assertInvalidFuncti... |
@Udf
public String lpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldPadInputString() {
final String result = udf.lpad("foo", 7, "Bar");
assertThat(result, is("BarBfoo"));
} |
public void calculate(IThrowableProxy tp) {
while (tp != null) {
populateFrames(tp.getStackTraceElementProxyArray());
IThrowableProxy[] suppressed = tp.getSuppressed();
if (suppressed != null) {
for (IThrowableProxy current : suppressed) {
... | @Test
public void smoke() throws Exception {
Throwable t = new Throwable("x");
ThrowableProxy tp = new ThrowableProxy(t);
PackagingDataCalculator pdc = tp.getPackagingDataCalculator();
pdc.calculate(tp);
verify(tp);
tp.fullDump();
} |
public void start() {
configService.addListener(configListener);
interfaceService.addListener(interfaceListener);
setUpConnectivity();
} | @Test
public void testNullInterfaces() {
reset(interfaceService);
interfaceService.addListener(anyObject(InterfaceListener.class));
expectLastCall().anyTimes();
expect(interfaceService.getInterfaces()).andReturn(
Sets.newHashSet()).anyTimes();
expect(interfac... |
public static Builder newBuilder() {
return new Builder();
} | @Test void localEndpointDefaults() {
Tracing tracing = Tracing.newBuilder().build();
assertThat(tracing).extracting("tracer.pendingSpans.defaultSpan.localServiceName")
.isEqualTo("unknown");
assertThat(tracing).extracting("tracer.pendingSpans.defaultSpan.localIp")
.isEqualTo(Platform.get().linkL... |
public static String getVersionDesc(int value) {
int length = Version.values().length;
if (value >= length) {
return Version.values()[length - 1].name();
}
return Version.values()[value].name();
} | @Test
public void testGetVersionDesc() throws Exception {
String desc = "V3_0_0_SNAPSHOT";
assertThat(MQVersion.getVersionDesc(0)).isEqualTo(desc);
} |
@Nullable String getCollectionName(BsonDocument command, String commandName) {
if (COMMANDS_WITH_COLLECTION_NAME.contains(commandName)) {
String collectionName = getNonEmptyBsonString(command.get(commandName));
if (collectionName != null) {
return collectionName;
}
}
// Some other ... | @Test void getCollectionName_emptyStringCommandArgument() {
assertThat(
listener.getCollectionName(new BsonDocument("find", new BsonString(" ")), "find")).isNull();
} |
public synchronized static HealthCheckRegistry setDefault(String name) {
final HealthCheckRegistry registry = getOrCreate(name);
return setDefault(name, registry);
} | @Test
public void unableToSetCustomDefaultRegistryTwice() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Default health check registry is already set.");
SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry());
SharedHe... |
public AuthenticationType getType() {
if (type != null) {
// use the user provided type
return type;
}
final boolean hasPassword = ObjectHelper.isNotEmpty(password);
final boolean hasRefreshToken = ObjectHelper.isNotEmpty(refreshToken);
final boolean hasK... | @Test
public void shouldDetermineProperAuthenticationType() {
assertEquals(AuthenticationType.USERNAME_PASSWORD, usernamePassword.getType());
assertEquals(AuthenticationType.REFRESH_TOKEN, refreshToken.getType());
assertEquals(AuthenticationType.JWT, jwt.getType());
} |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
return createFromImage(document, image, 0.75f);
} | @Test
void testCreateFromImageRGB() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(JPEGFactoryTest.class.getResourceAsStream("jpeg.jpg"));
assertEquals(3, image.getColorModel().getNumComponents());
PDImageXObject ximage = JPEGFacto... |
@NonNull
public static String encode(@NonNull String s) {
try {
boolean escaped = false;
StringBuilder out = new StringBuilder(s.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter w = new OutputStreamWriter(buf, StandardCh... | @Test
public void testEncodeSpaces() {
final String urlWithSpaces = "http://hudson/job/Hudson Job";
String encoded = Util.encode(urlWithSpaces);
assertEquals("http://hudson/job/Hudson%20Job", encoded);
} |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitSm[] submitSms = createSubmitSm(exchange);
List<String> messageIDs = new ArrayList<>(submitSms.length);
String messageID = null;
for (int i = 0; i < submitSms.length; i++) {
SubmitSm submitSm =... | @Test
public void alphabetUpdatesDataCoding() throws Exception {
final byte incorrectDataCoding = (byte) 0x00;
byte[] body = { 'A', 'B', 'C' };
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND... |
public Schema sorted() {
// Create a new schema and copy over the appropriate Schema object attributes:
// {fields, uuid, options}
// Note: encoding positions are not copied over because generally they should align with the
// ordering of field indices. Otherwise, problems may occur when encoding/decodi... | @Test
public void testSorted() {
Options testOptions =
Options.builder()
.setOption("test_str_option", FieldType.STRING, "test_str")
.setOption("test_bool_option", FieldType.BOOLEAN, true)
.build();
Schema unorderedSchema =
Schema.builder()
.add... |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void testPrintExecuptionPlan() {
// Given:
final KsqlEntityList entityList = new KsqlEntityList(ImmutableList.of(
new ExecutionPlan("Test Execution Plan")
));
// When:
console.printKsqlEntityList(entityList);
// Then:
final String output = terminal.getOutputString();... |
public static Stream<DeterministicKey> generate(DeterministicKey parent, int childNumber) {
return Stream.generate(new KeySupplier(parent, childNumber));
} | @Test
public void testGenerate() {
DeterministicKey parent = new DeterministicKey(HDPath.m(), new byte[32], BigInteger.TEN,
null);
assertFalse(parent.isPubKeyOnly());
assertFalse(parent.isEncrypted());
List<DeterministicKey> keys0 = HDKeyDerivation.generate(parent, C... |
public static JSONObject getJsonObject(JSONObject jsonObject, String key, int fromIndex) {
int firstOccr = key.indexOf('.', fromIndex);
if (firstOccr == -1) {
String token = key.substring(key.lastIndexOf('.') + 1);
if (jsonObject.has(token)) {
return (JSONObject) ... | @Test(expected = ClassCastException.class)
public void testGetJsonObjectWithException() {
JSONObject json = new JSONObject(jsonStr);
// only support json object could not get string value directly from this api, exception will be threw
EsUtil.getJsonObject(json, "settings.index.bpack.partiti... |
public AggregateAnalysisResult analyze(
final ImmutableAnalysis analysis,
final List<SelectExpression> finalProjection
) {
if (!analysis.getGroupBy().isPresent()) {
throw new IllegalArgumentException("Not an aggregate query");
}
final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ... | @Test
public void shouldNotThrowOnAggregateFunctionInHavingThatReferencesColumnNotInGroupBy() {
// Given:
givenHavingExpression(AGG_FUNCTION_CALL);
// When:
analyzer.analyze(analysis, selects);
// Then: did not throw.
} |
@Override
public Expr clone() {
return new VirtualSlotRef(this);
} | @Test
public void testClone() {
Expr v = virtualSlot.clone();
Assert.assertTrue(v instanceof VirtualSlotRef);
Assert.assertTrue(((VirtualSlotRef) v).getRealSlots().get(0).equals(virtualSlot.getRealSlots().get(0)));
Assert.assertFalse(((VirtualSlotRef) v).getRealSlots().get(0) == virt... |
@Override
public double variance() {
return 2 * nu;
} | @Test
public void testVariance() {
System.out.println("variance");
ChiSquareDistribution instance = new ChiSquareDistribution(20);
instance.rand();
assertEquals(40, instance.variance(), 1E-7);
} |
@Override
@SuppressWarnings({"unchecked"})
public RestLiResponseData<PartialUpdateResponseEnvelope> buildRestLiResponseData(Request request,
RoutingResult routingResult,
... | @Test(dataProvider = "responseExceptionData")
public void testBuilderException(UpdateResponse response)
{
Map<String, String> headers = ResponseBuilderUtil.getHeaders();
PartialUpdateResponseBuilder partialUpdateResponseBuilder = new PartialUpdateResponseBuilder();
RoutingResult routingResult = getMock... |
@Override
public CheckpointStateToolset createTaskOwnedCheckpointStateToolset() {
if (fileSystem instanceof PathsCopyingFileSystem) {
return new FsCheckpointStateToolset(
taskOwnedStateDirectory, (PathsCopyingFileSystem) fileSystem);
} else {
return new No... | @Test
void testDuplicationCheckpointStateToolset() throws Exception {
CheckpointStorageAccess checkpointStorage =
new FsCheckpointStorageAccess(
new TestDuplicatingFileSystem(),
randomTempPath(),
null,
... |
@PostConstruct
public void init() {
if (!environment.getAgentStatusEnabled()) {
LOG.info("Agent status HTTP API server has been disabled.");
return;
}
InetSocketAddress address = new InetSocketAddress(environment.getAgentStatusHostname(), environment.getAgentStatusPor... | @Test
void shouldNotInitializeServerIfSettingIsTurnedOff() {
try (MockedStatic<HttpServer> mockedStaticHttpServer = mockStatic(HttpServer.class)) {
when(systemEnvironment.getAgentStatusEnabled()).thenReturn(false);
agentStatusHttpd.init();
mockedStaticHttpServer.verifyNoI... |
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 checkDigidAppSwitchError(){
when(appSessionService.getSession(any())).thenReturn(appSession);
when(appAuthenticatorService.findByUserAppId(any())).thenReturn(appAuthenticator);
when(switchService.digidAppSwitchEnabled()).thenReturn(Boolean.FALSE);
Map<String, String> resu... |
public static Throwable getRootCause(Throwable throwable) {
if (throwable == null) {
return null;
}
Throwable rootCause = throwable;
// this is to avoid infinite loops for recursive cases
final Set<Throwable> seenThrowables = new HashSet<>();
seenThrowables.add(rootCause);
while ((root... | @Test
void rootCauseIsDifferent() {
Throwable rootCause = new Exception();
Throwable e = new Exception(rootCause);
Throwable actualRootCause = ExceptionUtils.getRootCause(e);
assertThat(actualRootCause).isSameAs(rootCause);
} |
static List<String> parseEtcResolverSearchDomains() throws IOException {
return parseEtcResolverSearchDomains(new File(ETC_RESOLV_CONF_FILE));
} | @Test
public void searchDomainsWithOnlySearch(@TempDir Path tempDir) throws IOException {
File f = buildFile(tempDir, "search linecorp.local\n" +
"nameserver 127.0.0.2\n");
List<String> domains = UnixResolverDnsServerAddressStreamProvider.parseEtcResolverSearchDomains(f);
... |
String getAgentStatusReportRequestBody(JobIdentifier identifier, String elasticAgentId) {
JsonObject jsonObject = new JsonObject();
if (identifier != null) {
jsonObject.add("job_identifier", jobIdentifierJson(identifier));
}
jsonObject.addProperty("elastic_agent_id", elasticA... | @Test
public void shouldJSONizeElasticAgentStatusReportRequestBodyWhenElasticAgentIdIsProvided() throws Exception {
String elasticAgentId = "my-fancy-elastic-agent-id";
String actual = new ElasticAgentExtensionConverterV4().getAgentStatusReportRequestBody(null, elasticAgentId);
String expect... |
@Override
void toHtml() throws IOException {
writeHtmlHeader();
htmlCoreReport.toHtml();
writeHtmlFooter();
} | @Test
public void testJCache() throws IOException {
final String cacheName = "test 1";
final javax.cache.CacheManager jcacheManager = Caching.getCachingProvider()
.getCacheManager();
final MutableConfiguration<Object, Object> conf = new MutableConfiguration<>();
conf.setManagementEnabled(true);
conf.setS... |
@Override
public Map<String, ConfigChangeItem> doParse(String oldContent, String newContent, String type) {
Map<String, Object> oldMap = Collections.emptyMap();
Map<String, Object> newMap = Collections.emptyMap();
try {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()... | @Test
void testModifyKey() throws IOException {
Map<String, ConfigChangeItem> map = parser.doParse("app:\n name: rocketMQ", "app:\n name: nacos", type);
assertEquals("rocketMQ", map.get("app.name").getOldValue());
assertEquals("nacos", map.get("app.name").getNewValue());
} |
String validateElasticProfileRequestBody(Map<String, String> configuration) {
JsonObject properties = mapToJsonObject(configuration);
return new GsonBuilder().serializeNulls().create().toJson(properties);
} | @Test
public void shouldConstructValidationRequest() {
HashMap<String, String> configuration = new HashMap<>();
configuration.put("key1", "value1");
configuration.put("key2", "value2");
configuration.put("key3", null);
String requestBody = new ElasticAgentExtensionConverterV5... |
public static String hex(char ch) {
return Integer.toHexString(ch).toUpperCase();
} | @Test
public void testHex() {
Assertions.assertEquals("61", Utils.hex('a'));
Assertions.assertEquals("24", Utils.hex('$'));
} |
@Override
public void close() {
close(Duration.ofMillis(DEFAULT_CLOSE_TIMEOUT_MS));
} | @Test
void testReaperInvokedInClose() {
consumer = newConsumer();
completeUnsubscribeApplicationEventSuccessfully();
consumer.close();
verify(backgroundEventReaper).reap(backgroundEventQueue);
} |
public void validateUrl(String serverUrl) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos");
doGet("", url, body -> buildGson().fromJson(body, RepositoryList.class));
} | @Test
public void fail_validate_url_when_on_http_error() {
server.enqueue(new MockResponse().setResponseCode(500)
.setBody("something unexpected"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateUrl(serverUrl))
.isInstanceOf(IllegalArgumentException... |
public static KeyStore loadKeyStore(final String name, final char[] password) {
InputStream stream = null;
try {
stream = Config.getInstance().getInputStreamFromFile(name);
if (stream == null) {
String message = "Unable to load keystore '" + name + "', please prov... | @Test
public void testLoadInvalidKeyStore() {
try {
KeyStore keyStore = TlsUtil.loadKeyStore(INVALID_KEYSTORE_NAME, PASSWORD);
fail();
} catch (Exception e) {
Assert.assertEquals(e.getMessage(), "Unable to load stream for keystore " + INVALID_KEYSTORE_NAME);
... |
int run() {
final Map<String, String> configProps = options.getConfigFile()
.map(Ksql::loadProperties)
.orElseGet(Collections::emptyMap);
final Map<String, String> sessionVariables = options.getVariables();
try (KsqlRestClient restClient = buildClient(configProps)) {
try (Cli cli = c... | @Test
public void shouldUseSslConfigInSystemConfigInPreferenceToAnyInConfigFile() throws Exception {
// Given:
givenConfigFile(
"ssl.truststore.location=should not use" + System.lineSeparator()
+ "ssl.truststore.password=should not use"
);
givenSystemProperties(
"ssl.trust... |
@VisibleForTesting
Database getDatabase( LoggingObjectInterface parentObject, PGBulkLoaderMeta pgBulkLoaderMeta ) {
DatabaseMeta dbMeta = pgBulkLoaderMeta.getDatabaseMeta();
// If dbNameOverride is present, clone the origin db meta and override the DB name
String dbNameOverride = environmentSubstitute( pg... | @Test
public void testDBNameOverridden_IfDbNameOverrideSetUp() throws Exception {
// Db Name Override is set up
PGBulkLoaderMeta pgBulkLoaderMock = getPgBulkLoaderMock( DB_NAME_OVVERRIDE );
Database database = pgBulkLoader.getDatabase( pgBulkLoader, pgBulkLoaderMock );
assertNotNull( database );
/... |
void registerColumnFamily(String columnFamilyName, ColumnFamilyHandle handle) {
boolean columnFamilyAsVariable = options.isColumnFamilyAsVariable();
MetricGroup group =
columnFamilyAsVariable
? metricGroup.addGroup(COLUMN_FAMILY_KEY, columnFamilyName)
... | @Test
void testReturnsUnsigned() throws Throwable {
RocksDBExtension localRocksDBExtension = new RocksDBExtension();
localRocksDBExtension.before();
SimpleMetricRegistry registry = new SimpleMetricRegistry();
GenericMetricGroup group =
new GenericMetricGroup(
... |
public int getConnectionRequestTimeout() {
return connectionRequestTimeout;
} | @Test
void testGetConnectionRequestTimeout() {
HttpClientConfig config = HttpClientConfig.builder().setConnectionRequestTimeout(5000).build();
assertEquals(5000, config.getConnectionRequestTimeout());
} |
@Override
public Health check() {
Platform.Status platformStatus = platform.status();
if (platformStatus == Platform.Status.UP
&& VALID_DATABASEMIGRATION_STATUSES.contains(migrationState.getStatus())
&& !restartFlagHolder.isRestarting()) {
return Health.GREEN;
}
return Health.builder... | @Test
public void returns_GREEN_without_cause_if_platform_status_is_UP_migration_status_is_valid_and_SQ_is_not_restarting() {
when(platform.status()).thenReturn(Platform.Status.UP);
when(migrationState.getStatus()).thenReturn(random.nextBoolean() ? DatabaseMigrationState.Status.NONE : DatabaseMigrationState.S... |
@Override
public SecurityGroup securityGroup(String sgId) {
checkArgument(!Strings.isNullOrEmpty(sgId), ERR_NULL_SG_ID);
return osSecurityGroupStore.securityGroup(sgId);
} | @Test
public void testGetSecurityGroupById() {
createBasicSecurityGroups();
assertNotNull("Instance port did not match", target.securityGroup(SECURITY_GROUP_ID_1));
assertNotNull("Instance port did not match", target.securityGroup(SECURITY_GROUP_ID_2));
assertNull("Instance port did ... |
private Preconditions() {
} | @Test
public void testPreconditions(){
Preconditions.checkArgument(true);
try{
Preconditions.checkArgument(false);
} catch (IllegalArgumentException e){
assertNull(e.getMessage());
}
Preconditions.checkArgument(true, "Message %s here", 10);
t... |
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final ComplexKeysShardingValue<Comparable<?>> shardingValue) {
if (!shardingValue.getColumnNameAndRangeValuesMap().isEmpty()) {
ShardingSpherePreconditions.checkState(allowRangeQuery,
... | @Test
void assertDoShardingWithMultiValue() {
Properties props = PropertiesBuilder.build(new Property("algorithm-expression", "t_order_${type % 2}_${order_id % 2}"), new Property("sharding-columns", "type,order_id"));
ComplexInlineShardingAlgorithm algorithm = (ComplexInlineShardingAlgorithm) TypedS... |
public static String toUriAuthority(NetworkEndpoint networkEndpoint) {
return toHostAndPort(networkEndpoint).toString();
} | @Test
public void toUriString_withHostnameEndpoint_returnsHostname() {
NetworkEndpoint hostnameEndpoint =
NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.HOSTNAME)
.setHostname(Hostname.newBuilder().setName("localhost"))
.build();
assertThat(NetworkEndpoi... |
@Override
public void start() {
if (!PluginConfigManager.getPluginConfig(DiscoveryPluginConfig.class).isEnableRegistry()) {
return;
}
final LbConfig lbConfig = PluginConfigManager.getPluginConfig(LbConfig.class);
maxSize = lbConfig.getMaxRetryConfigCache();
defaul... | @Test
public void disableAllTimeout() {
lbConfig.setEnableSocketConnectTimeoutRetry(false);
lbConfig.setEnableTimeoutExRetry(false);
lbConfig.setEnableSocketReadTimeoutRetry(false);
lbConfig.setSpecificExceptionsForRetry(Collections.singletonList("java.lang.IllegalArgumentException")... |
@Override
public List<HasMetadata> buildAccompanyingKubernetesResources() throws IOException {
final Service service =
kubernetesJobManagerParameters
.getRestServiceExposedType()
.serviceType()
.buildUpExternalRestServic... | @Test
void testSetServiceExposedTypeWithHeadless() throws IOException {
this.flinkConfig.set(
KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE,
KubernetesConfigOptions.ServiceExposedType.Headless_ClusterIP);
final List<HasMetadata> servicesWithHeadlessClusterIP =
... |
@Override
public int hashCode() {
return Objects.hash(targetImage, imageDigest, imageId, tags, imagePushed);
} | @Test
public void testEquality_differentImageDigest() {
JibContainer container1 = new JibContainer(targetImage1, digest1, digest2, tags1, true);
JibContainer container2 = new JibContainer(targetImage1, digest2, digest2, tags1, true);
Assert.assertNotEquals(container1, container2);
Assert.assertNotEqu... |
public List<WorkflowInstance> getWorkflowInstancesWithLatestRun(
String workflowId, long startInstanceId, long endInstanceId, boolean aggregated) {
List<WorkflowInstance> instances =
withMetricLogError(
() ->
withRetryableQuery(
LATEST_RUN_WORKFLOW_INST... | @Test
public void testGetWorkflowInstanceLatestRuns() throws Exception {
initializeForGetWorkflowInstancesLatestRun();
// pagination call to get all the latest runs workflow instance id's in a particular workflow
// id, null cursor
List<WorkflowInstance> workflows =
instanceDao.getWorkflowIns... |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String... | @Test
public void testExecute() throws SubCommandException {
UpdateBrokerConfigSubCommand cmd = new UpdateBrokerConfigSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:" + listenPort(), "-c default-cluster", "-k ... |
public static AppsInfo mergeAppsInfo(ArrayList<AppInfo> appsInfo,
boolean returnPartialResult) {
AppsInfo allApps = new AppsInfo();
Map<String, AppInfo> federationAM = new HashMap<>();
Map<String, AppInfo> federationUAMSum = new HashMap<>();
for (AppInfo a : appsInfo) {
// Check if this App... | @Test
public void testMergeUAM() {
AppsInfo apps = new AppsInfo();
AppInfo app1 = new AppInfo();
app1.setAppId(APPID1.toString());
app1.setName("Test");
apps.add(app1);
// in this case the result does not change if we enable partial result
AppsInfo result = RouterWebServiceUtil.mergeApp... |
@Override
public void onMatch(RelOptRuleCall call) {
final Sort sort = call.rel(0);
final SortExchange exchange = call.rel(1);
final RelMetadataQuery metadataQuery = call.getMetadataQuery();
if (RelMdUtil.checkInputForCollationAndLimit(
metadataQuery,
exchange.getInput(),
sort... | @Test
public void shouldMatchLimitNoOffsetYesSortOnSender() {
// Given:
RelCollation collation = RelCollations.of(1);
SortExchange exchange = PinotLogicalSortExchange.create(_input, RelDistributions.SINGLETON, collation, true, false);
Sort sort = LogicalSort.create(exchange, collation, null, literal(1... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP);
if (args.isEmpty()) {
final String setting = requestPipeliningSupplier.get() ? "ON" : "OFF";
terminal.printf("Current %s configuration: %s%n", NAME, setting);
... | @Test
public void shouldPrintCurrentSettingOfOff() {
// Given:
when(settingSupplier.get()).thenReturn(false);
// When:
requestPipeliningCommand.execute(Collections.emptyList(), terminal);
// Then:
assertThat(out.toString(),
containsString(String.format("Current %s configuration: OFF"... |
public static boolean isInstanceOf(Class<?> clazz, Object object) {
return clazz.isInstance(object);
} | @Test
public void testIsInstance() {
Object object = new ZTest();
assertTrue(TypeUtil.isInstanceOf(I0Test.class, object));
assertTrue(TypeUtil.isInstanceOf("py4j.reflection.I0Test", object));
object = new ATest();
assertFalse(TypeUtil.isInstanceOf(I0Test.class, object));
assertFalse(TypeUtil.isInstanceOf("... |
public static List<ReservationAllocationState>
convertAllocationsToReservationInfo(Set<ReservationAllocation> res,
boolean includeResourceAllocations) {
List<ReservationAllocationState> reservationInfo = new ArrayList<>();
Map<ReservationInterval, Resource> requests;
for (Re... | @Test
public void testConvertAllocationsToReservationInfo() {
long startTime = new Date().getTime();
long step = 10000;
int[] alloc = {10, 10, 10};
ReservationId id = ReservationSystemTestUtil.getNewReservationId();
ReservationAllocation allocation = createReservationAllocation(
startT... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyInOrderWithFailure() {
expectFailureWhenTestingThat(asList(1, null, 3)).containsExactly(null, 1, 3).inOrder();
assertFailureKeys("contents match, but order was wrong", "expected", "but was");
assertFailureValue("expected", "[null, 1, 3]");
} |
@Override
public boolean removeServiceSubscriber(Service service) {
if (null != subscribers.remove(service)) {
MetricsMonitor.decrementSubscribeCount();
}
return true;
} | @Test
void removeServiceSubscriber() {
boolean result = abstractClient.removeServiceSubscriber(service);
assertTrue(result);
} |
public static ObjectEncoder createEncoder(Type type, ObjectInspector inspector)
{
String base = type.getTypeSignature().getBase();
switch (base) {
case BIGINT:
checkArgument(inspector instanceof PrimitiveObjectInspector);
return compose(primitive(inspector... | @Test
public void testComplexObjectEncoders()
{
ObjectInspector inspector;
ObjectEncoder encoder;
inspector = ObjectInspectors.create(new ArrayType(BIGINT), typeManager);
encoder = createEncoder(new ArrayType(BIGINT), inspector);
assertTrue(encoder instanceof ObjectEncod... |
@Override
public void open() throws Exception {
super.open();
windowSerializer = windowAssigner.getWindowSerializer(new ExecutionConfig());
internalTimerService = getInternalTimerService("window-timers", windowSerializer, this);
triggerContext = new TriggerContext();
trigge... | @Test
void testFinishBundleTriggeredByCount() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 4);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLin... |
@VisibleForTesting
String upload(Configuration config, String artifactUriStr)
throws IOException, URISyntaxException {
final URI artifactUri = PackagedProgramUtils.resolveURI(artifactUriStr);
if (!"local".equals(artifactUri.getScheme())) {
return artifactUriStr;
}
... | @Test
void testUploadOverwrite() throws Exception {
File jar = getFlinkKubernetesJar();
String localUri = "local://" + jar.getAbsolutePath();
Files.createFile(tmpDir.resolve(jar.getName()));
config.set(KubernetesConfigOptions.LOCAL_UPLOAD_OVERWRITE, true);
artifactUploader.u... |
public String encode(long... numbers) {
if (numbers.length == 0) {
return "";
}
for (final long number : numbers) {
if (number < 0) {
return "";
}
if (number > MAX_NUMBER) {
throw new IllegalArgumentException("numbe... | @Test
public void test_issue32() throws Exception {
final long num_to_hash = -1;
final Hashids a = new Hashids("this is my salt");
Assert.assertEquals("", a.encode(num_to_hash));
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldApplyAssertSchemaCommands() throws Exception {
command = PARSER.parse("-v", "3");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
createMigrationFile(3, NAME, migrationsDir, ASSERT_SCHEMA_COMMANDS);
givenCurrentMigrationVersion("1");
givenAppliedMigration(1, NAME, Mig... |
public static <T> Partition<T> of(
int numPartitions,
PartitionWithSideInputsFn<? super T> partitionFn,
Requirements requirements) {
Contextful ctfFn =
Contextful.fn(
(T element, Contextful.Fn.Context c) ->
partitionFn.partitionFor(element, numPartitions, c),
... | @Test
@Category(NeedsRunner.class)
public void testOutOfBoundsPartitions() {
pipeline.apply(Create.of(-1)).apply(Partition.of(5, new IdentityFn()));
thrown.expect(RuntimeException.class);
thrown.expectMessage("Partition function returned out of bounds index: -1 not in [0..5)");
pipeline.run();
} |
public Collection<Component<?, ?>> getAllComponents() {
List<Component<?, ?>> allComponents = new ArrayList<>();
recursivelyFindAllComponents(allComponents, this);
// We need consistent ordering
Collections.sort(allComponents);
return Collections.unmodifiableCollection(allCompone... | @Test
void testThatLinguisticsIsExcludedForClusterControllerCluster() {
MockRoot root = createRoot(false);
ClusterControllerContainerCluster cluster = createClusterControllerCluster(root);
addClusterController(cluster, "host-c1", root.getDeployState());
assertFalse(contains("com.yaho... |
public static Properties getProperties(File file) throws AnalysisException {
try (BufferedReader utf8Reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
return getProperties(utf8Reader);
} catch (IOException | IllegalArgumentException e) {
throw new Analysi... | @Test
public void getProperties_should_throw_exception_for_too_large_major() throws IOException {
try {
PyPACoreMetadataParser.getProperties(new BufferedReader(new StringReader("Metadata-Version: 3.0")));
Assert.fail("Expected IllegalArgumentException for too large major in Metadata-... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testThreeMoreThanFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
history.add(3);
history.add(4);
history.add(5);
history.add(6);
int[] expectedHistorySnapshot = {4, 5, 6};
testHistory(history, expectedHistory... |
public abstract boolean exists(); | @Test
public void testApplicationFileExists() throws Exception {
assertTrue(getApplicationFile(Path.fromString("vespa-services.xml")).exists());
assertTrue(getApplicationFile(Path.fromString("searchdefinitions")).exists());
assertTrue(getApplicationFile(Path.fromString("searchdefinitions/soc... |
@Override
public boolean nullsAreSortedAtEnd() {
return false;
} | @Test
void assertNullsAreSortedAtEnd() {
assertFalse(metaData.nullsAreSortedAtEnd());
} |
@SuppressWarnings("unchecked")
public static String jobName(RunContext runContext) {
Map<String, String> flow = (Map<String, String>) runContext.getVariables().get("flow");
Map<String, String> task = (Map<String, String>) runContext.getVariables().get("task");
String name = Slugify.of(Strin... | @Test
void jobName() {
var runContext = runContext(runContextFactory, "namespace");
String jobName = ScriptService.jobName(runContext);
assertThat(jobName, startsWith("namespace-flowid-task-"));
assertThat(jobName.length(), is(27));
runContext = runContext(runContextFactory,... |
@VisibleForTesting
static Optional<String> performUpdateCheck(
Path configDir,
String currentVersion,
String versionUrl,
String toolName,
Consumer<LogEvent> log) {
Path lastUpdateCheck = configDir.resolve(LAST_UPDATE_CHECK_FILENAME);
try {
// Check time of last update chec... | @Test
public void testPerformUpdateCheck_badLastUpdateTime() throws IOException, InterruptedException {
Instant before = Instant.now();
Thread.sleep(100);
Files.write(
configDir.resolve("lastUpdateCheck"), "bad timestamp".getBytes(StandardCharsets.UTF_8));
Optional<String> message =
Up... |
@Override
protected void log(String configKey, String format, Object... args) {
// Not using SLF4J's support for parameterized messages (even though it would be more efficient)
// because it would
// require the incoming message formats to be SLF4J-specific.
if (logger.isDebugEnabled()) {
logger... | @Test
void useSpecifiedLoggerIfRequested() throws Exception {
slf4j.logLevel("debug");
slf4j.expectMessages(
"DEBUG specified.logger - [someMethod] This is my message" + System.lineSeparator());
logger = new Slf4jLogger(LoggerFactory.getLogger("specified.logger"));
logger.log(CONFIG_KEY, "Thi... |
@POST
@Path("{networkId}/devices")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualDevice(@PathParam("networkId") long networkId,
InputStream stream) {
try {
ObjectNode jsonTree = readTre... | @Test
public void testPostVirtualDevice() {
NetworkId networkId = networkId3;
DeviceId deviceId = devId2;
expect(mockVnetAdminService.createVirtualDevice(networkId, deviceId)).andReturn(vdev2);
expectLastCall();
replay(mockVnetAdminService);
WebTarget wt = target();... |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testEmptyHadoopConfDirectory() throws IOException {
setHadoopConfDirEnv();
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
assertThat(kuberne... |
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "lookupConstraints is ImmutableList")
public List<LookupConstraint> getLookupConstraints() {
return lookupConstraints;
} | @Test
public void shouldReturnKeyConstraintInt() {
// Given:
when(plannerOptions.getTableScansEnabled()).thenReturn(true);
final Expression keyExp1 = new ComparisonExpression(
Type.GREATER_THAN,
new UnqualifiedColumnReferenceExp(ColumnName.of("K")),
new IntegerLiteral(1... |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void parseAeqBandOpenBsmlCorDgtEclose() {
String query = "A = B AND ( B < C OR D > E )";
List<String> list = parser.toPrefix(query);
assertEquals(Arrays.asList("A", "B", "=", "B", "C", "<", "D", "E", ">", "OR", "AND"), list);
} |
@Override
public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets,
ListOffsetsOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future =
ListOffsetsHandler.newFuture(topicParti... | @Test
public void testListOffsetsMetadataRetriableErrors() throws Exception {
Node node0 = new Node(0, "localhost", 8120);
Node node1 = new Node(1, "localhost", 8121);
List<Node> nodes = asList(node0, node1);
List<PartitionInfo> pInfos = new ArrayList<>();
pInfos.add(new Part... |
public static int parseBytesToInt(List<Byte> data) {
return parseBytesToInt(data, 0);
} | @Test
public void parseBytesToInt_checkLists() {
int expected = 257;
List<Byte> data = toList(ByteBuffer.allocate(4).putInt(expected).array());
Assertions.assertEquals(expected, TbUtils.parseBytesToInt(data, 0, 4));
Assertions.assertEquals(expected, TbUtils.parseBytesToInt(data, 2, 2... |
public static CatalogTable of(TableIdentifier tableId, CatalogTable catalogTable) {
CatalogTable newTable = catalogTable.copy();
return new CatalogTable(
tableId,
newTable.getTableSchema(),
newTable.getOptions(),
newTable.getPartitionKeys()... | @Test
public void testCatalogTableWithIllegalFieldNames() {
CatalogTable catalogTable =
CatalogTable.of(
TableIdentifier.of("catalog", "database", "table"),
TableSchema.builder()
.column(
... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseStringsBeginningWithFalseAsStrings() {
SchemaAndValue schemaAndValue = Values.parseString("false]");
assertEquals(Type.STRING, schemaAndValue.schema().type());
assertEquals("false]", schemaAndValue.value());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.