focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
while (it.hasNext()) ... | @Test
public void skipReflowLongStrings() {
assertThat(
CommandLineOptionsParser.parse(Arrays.asList("--skip-reflowing-long-strings"))
.reflowLongStrings())
.isFalse();
} |
@Override
public void subscribe(String serviceName, EventListener listener) throws NacosException {
subscribe(serviceName, new ArrayList<>(), listener);
} | @Test
void testSubscribeWithNullListener() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
//when
client.subscribe(serviceName, groupName, null);
//then
verify(changeNotifier, never()).registerListener(groupName, serviceName,
... |
@Override
public List<KsqlPartitionLocation> locate(
final List<KsqlKey> keys,
final RoutingOptions routingOptions,
final RoutingFilterFactory routingFilterFactory,
final boolean isRangeScan
) {
if (isRangeScan && keys.isEmpty()) {
throw new IllegalStateException("Query is range sc... | @Test
public void shouldThrowIfMetadataIsEmpty() {
// Given:
getActiveAndStandbyMetadata();
when(topology.describe()).thenReturn(description);
when(description.subtopologies()).thenReturn(ImmutableSet.of(sub1));
when(sub1.nodes()).thenReturn(ImmutableSet.of(source, processor));
when(source.top... |
public static void install() {
installStyle( STYLE_REGULAR );
installStyle( STYLE_ITALIC );
installStyle( STYLE_BOLD );
installStyle( STYLE_BOLD_ITALIC );
} | @Test
void testFont() {
FlatJetBrainsMonoFont.install();
testFont( FlatJetBrainsMonoFont.FAMILY, Font.PLAIN, 13 );
testFont( FlatJetBrainsMonoFont.FAMILY, Font.ITALIC, 13 );
testFont( FlatJetBrainsMonoFont.FAMILY, Font.BOLD, 13 );
testFont( FlatJetBrainsMonoFont.FAMILY, Font.BOLD | Font.ITALIC, 13 );
} |
public static boolean isValidOrigin(String sourceHost, ZeppelinConfiguration zConf)
throws UnknownHostException, URISyntaxException {
String sourceUriHost = "";
if (sourceHost != null && !sourceHost.isEmpty()) {
sourceUriHost = new URI(sourceHost).getHost();
sourceUriHost = (sourceUriHost ==... | @Test
void nullOrigin()
throws URISyntaxException, UnknownHostException {
assertFalse(CorsUtils.isValidOrigin(null,
ZeppelinConfiguration.load("zeppelin-site.xml")));
} |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void factValueIntFailNoSuchKey() {
Object unused = expectFailureWhenTestingThat(fact("foo", "the foo")).factValue("bar", 0);
assertFailureKeys("expected to contain fact", "but contained only");
assertFailureValue("expected to contain fact", "bar");
assertFailureValue("but contained only",... |
@Nonnull
public static <T> Traverser<T> traverseEnumeration(@Nonnull Enumeration<T> enumeration) {
return () -> enumeration.hasMoreElements()
? requireNonNull(enumeration.nextElement(), "Enumeration contains a null element")
: null;
} | @Test
public void when_traverseEnumeration_then_seeAllItems() {
validateTraversal(traverseEnumeration(new Vector<>(asList(1, 2)).elements()));
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldDefaultToEmitChangesForCtas() {
// Given:
final SingleStatementContext stmt =
givenQuery("CREATE TABLE X AS SELECT COUNT(1) FROM TEST1 GROUP BY ROWKEY;");
// When:
final Query result = ((QueryContainer) builder.buildStatement(stmt)).getQuery();
// Then:
assert... |
@Override
@Nullable
public Object convert(@Nullable String value) {
if (isNullOrEmpty(value)) {
return null;
}
LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone);
final DateTimeFormatter form... | @Test
public void convertUsesEnglishIfLocaleIsNull() throws Exception {
final Converter c = new DateConverter(config("dd/MMM/YYYY HH:mm:ss Z", null, null));
final DateTime dateTime = (DateTime) c.convert("11/May/2017 15:10:48 +0200");
assertThat(dateTime).isEqualTo("2017-05-11T13:10:48.000Z"... |
protected <T> Collection<String> getInvokerAddrList(List<Invoker<T>> invokers, Invocation invocation) {
String key = invokers.get(0).getUrl().getServiceKey() + "." + RpcUtils.getMethodName(invocation);
Map<String, WeightedRoundRobin> map = methodWeightMap.get(key);
if (map != null) {
... | @Test
void testNodeCacheShouldNotRecycle() {
int loop = 10000;
// tmperately add a new invoker
weightInvokers.add(weightInvokerTmp);
try {
Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(l... |
@VisibleForTesting
static void instantiateNonHeapMemoryMetrics(final MetricGroup metricGroup) {
instantiateMemoryUsageMetrics(
metricGroup, () -> ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage());
} | @Test
void testNonHeapMetricUsageNotStatic() throws Exception {
final InterceptingOperatorMetricGroup nonHeapMetrics =
new InterceptingOperatorMetricGroup();
MetricUtils.instantiateNonHeapMemoryMetrics(nonHeapMetrics);
@SuppressWarnings("unchecked")
final Gauge<Long... |
void appendValuesClause(StringBuilder sb) {
sb.append("VALUES ");
appendValues(sb, jdbcTable.dbFieldNames().size());
} | @Test
void testAppendValuesClause() {
PostgresUpsertQueryBuilder builder = new PostgresUpsertQueryBuilder(jdbcTable, dialect);
StringBuilder sb = new StringBuilder();
builder.appendValuesClause(sb);
String valuesClause = sb.toString();
assertThat(valuesClause).isEqualTo("VAL... |
public URLNormalizer removeDotSegments() {
String path = toURL().getPath().trim();
// (Bulleted comments are from RFC3986, section-5.2.4)
// 1. The input buffer is initialized with the now-appended path
// components and the output buffer is initialized to the empty
// ... | @Test
public void testRemoveDotSegments() {
s = "http://www.example.com/../a/b/../c/./d.html";
t = "http://www.example.com/a/c/d.html";
assertEquals(t, n(s).removeDotSegments().toString());
s = "http://www.example.com/a/../b/../c/./d.html";
t = "http://www.example.com/c/d.htm... |
@Override
public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) {
StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES");
String[] queryParams = null;
switch (scope.type()) {
case ROOT:
// account-level listing
baseQuery.append(" IN ACCOUNT");
... | @SuppressWarnings("unchecked")
@Test
public void testListIcebergTablesSQLExceptionWithoutErrorCode()
throws SQLException, InterruptedException {
Exception injectedException = new SQLException("Fake SQL exception");
when(mockClientPool.run(any(ClientPool.Action.class))).thenThrow(injectedException);
... |
public void stop() {
LOGGER.info("Stop game.");
isRunning = false;
} | @Test
void testStop() {
world.stop();
assertFalse(world.isRunning);
} |
public static ConfigResponse fromJson(String json) {
return JsonUtil.parse(json, ConfigResponseParser::fromJson);
} | @Test
public void unknownFields() {
ConfigResponse actual = ConfigResponseParser.fromJson("{\"x\": \"val\", \"y\": \"val2\"}");
ConfigResponse expected = ConfigResponse.builder().build();
// ConfigResponse doesn't implement hashCode/equals
assertThat(actual.defaults()).isEqualTo(expected.defaults()).i... |
@Override
public synchronized void close() throws IOException {
mCloser.close();
} | @Test
public void createClose() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
mFileSystem.createFile(ufsPath).close();
assertFalse(mFileSystem.getStatus(ufsPath).isFolder());
assertEquals(0L, mFileSystem.getStatus(ufsPath).getLength());
} |
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
return index(keyFunction, Function.identity());
} | @Test
public void index_with_valueFunction_returns_ListMultimap() {
ListMultimap<Integer, String> multimap = LIST.stream().collect(index(MyObj::getId, MyObj::getText));
assertThat(multimap.size()).isEqualTo(3);
Map<Integer, Collection<String>> map = multimap.asMap();
assertThat(map.get(1)).containsOn... |
@GET
@Produces(MediaType.TEXT_HTML)
public Response auth(
@QueryParam("scope") String scope,
@QueryParam("state") String state,
@QueryParam("response_type") String responseType,
@QueryParam("client_id") String clientId,
@QueryParam("redirect_uri") String redirectUri,
@QueryParam(... | @Test
void auth_success_passParams() {
var sessionId = IdGenerator.generateID();
var authService = mock(AuthService.class);
when(authService.auth(any())).thenReturn(new AuthorizationResponse(List.of(), sessionId));
var sut = new AuthEndpoint(authService);
var scope = "openid";
var state = UU... |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testRpcInvocation() throws Exception {
// For a proxy method should return true
final UnreliableInterface unreliable = (UnreliableInterface)
RetryProxy.create(UnreliableInterface.class, unreliableImpl, RETRY_FOREVER);
assertTrue(RetryInvocationHandler.isRpcInvocation(unreliable));
... |
@Override
public void checkBeforeUpdate(final CreateMaskRuleStatement sqlStatement) {
ifNotExists = sqlStatement.isIfNotExists();
if (!ifNotExists) {
checkDuplicatedRuleNames(sqlStatement);
}
checkAlgorithms(sqlStatement);
} | @Test
void assertCheckSQLStatementWithInvalidAlgorithm() {
assertThrows(ServiceProviderNotFoundException.class, () -> executor.checkBeforeUpdate(createSQLStatement(false, "INVALID_TYPE")));
} |
public void isNotIn(@Nullable Iterable<?> iterable) {
checkNotNull(iterable);
if (Iterables.contains(iterable, actual)) {
failWithActual("expected not to be any of", iterable);
}
} | @Test
public void isNotIn() {
assertThat("x").isNotIn(oneShotIterable("a", "b", "c"));
} |
static Map<String, SerializableFunction<Map<String, Object>, Double>> getPredictorTermsMap(final List<PredictorTerm> predictorTerms) {
predictorsArity.set(0);
return predictorTerms.stream()
.map(predictorTerm -> {
int arity = predictorsArity.addAndGet(1);
... | @Test
void getPredictorTermsMap() {
final List<PredictorTerm> predictorTerms = IntStream.range(0, 3).mapToObj(index -> {
String predictorName = "predictorName-" + index;
double coefficient = 1.23 * index;
String fieldRef = "fieldRef-" + index;
return PMMLModel... |
@Override
protected void processOptions(LinkedList<String> args)
throws IOException {
CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE,
OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN,
OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE,
OPTION_MTIME, OPTION_SIZE, OPTION_A... | @Test(expected = UnsupportedOperationException.class)
public void processPathDirDisplayECPolicyWhenUnsupported()
throws IOException {
TestFile testFile = new TestFile("testDirectory", "testFile");
TestFile testDir = new TestFile("", "testDirectory");
testDir.setIsDir(true);
testDir.addContents(t... |
@Override
public List<QueueTimeSpan> queryConsumeTimeSpan(final String topic,
final String group) throws InterruptedException, MQBrokerException,
RemotingException, MQClientException {
return this.defaultMQAdminExtImpl.queryConsumeTimeSpan(topic, group);
} | @Test
public void testQueryConsumeTimeSpan() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
List<QueueTimeSpan> result = defaultMQAdminExt.queryConsumeTimeSpan("unit-test", "default-broker-group");
assertThat(result.size()).isEqualTo(0);
} |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testStringNotStartsWith() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, notStartsWith("required", "a"), true).eval(FILE);
assertThat(shouldRead).as("Should read: no stats").isTrue();
shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, notStartsWith("require... |
public static <T extends Serializable> CacheableOptional<T> of(final T value) {
return new CacheableOptional<>(value);
} | @Test
public void equalsIsAppropriate() {
assertThat(CacheableOptional.of("my-test"), is(CacheableOptional.of("my-test")));
assertThat(CacheableOptional.of("my-test"), is(not(CacheableOptional.of("not-my-test"))));
} |
public static GenericSchemaImpl of(SchemaInfo schemaInfo) {
return of(schemaInfo, true);
} | @Test
public void testGenericAvroSchema() {
Schema<Foo> encodeSchema = Schema.AVRO(Foo.class);
GenericSchema decodeSchema = GenericSchemaImpl.of(encodeSchema.getSchemaInfo());
testEncodeAndDecodeGenericRecord(encodeSchema, decodeSchema);
} |
public static List<AclEntry> filterDefaultAclEntries(
List<AclEntry> existingAcl) throws AclException {
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
for (AclEntry existingEntry: existingAcl) {
if (existingEntry.getScope() == DEFAULT) {
// Default entries sort... | @Test
public void testFilterDefaultAclEntries() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", READ_WRITE))
.add(aclEntry(ACCESS, GROUP, READ_EXECUTE))
.add(aclEntry(ACCESS, GROUP,... |
public final void containsKey(@Nullable Object key) {
check("keySet()").that(checkNotNull(actual).keySet()).contains(key);
} | @Test
public void containsKey_failsWithSameToString() {
expectFailureWhenTestingThat(
ImmutableMultimap.of(1L, "value1a", 1L, "value1b", 2L, "value2", "1", "value3"))
.containsKey(1);
assertFailureKeys(
"value of",
"expected to contain",
"an instance of",
"b... |
public int getScale() {
return scale;
} | @Test
public void default_precision_is_20() {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.setPrecision(30)
.setIsNullable(true)
.build();
assertThat(def.getScale()).isEqualTo(20);
} |
public static void writeFully(OutputStream outputStream, ByteBuffer buffer) throws IOException {
if (!buffer.hasRemaining()) {
return;
}
byte[] chunk = new byte[WRITE_CHUNK_SIZE];
while (buffer.hasRemaining()) {
int chunkSize = Math.min(chunk.length, buffer.remaining());
buffer.get(chu... | @Test
public void testWriteFully() throws Exception {
byte[] input = Strings.repeat("Welcome to Warsaw!\n", 12345).getBytes(StandardCharsets.UTF_8);
InMemoryOutputFile outputFile = new InMemoryOutputFile();
try (PositionOutputStream outputStream = outputFile.create()) {
IOUtil.writeFully(outputStrea... |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldCoerceToBigInts() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of(
new IntegerLiteral(10),
new LongLiteral(1234567890),
new StringLiteral("\t -100 \t"),
BIGINT_EXPRESSION,
INT_EXPRESSION
);
// When:
final R... |
public void setScmId(String scmId) {
this.scmId = scmId;
} | @Test
public void shouldAddErrorWhenAssociatedSCMPluginIsMissing() {
PipelineConfigSaveValidationContext configSaveValidationContext = mock(PipelineConfigSaveValidationContext.class);
when(configSaveValidationContext.findScmById(anyString())).thenReturn(mock(SCM.class));
SCM scmConfig = mock... |
@Override
public void subscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("subscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("subscribe listener == null");
}
if (logger... | @Test
void testSubscribeIfListenerNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
URL url = new ServiceCon... |
public ConfigurationProperty getProperty(final String key) {
return stream().filter(item -> item.getConfigurationKey().getName().equals(key)).findFirst().orElse(null);
} | @Test
void shouldGetConfigPropertyForGivenKey() {
ConfigurationProperty property1 = new ConfigurationProperty(new ConfigurationKey("key1"), new ConfigurationValue("value1"), null, null);
ConfigurationProperty property2 = new ConfigurationProperty(new ConfigurationKey("key2"), new ConfigurationValue(... |
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
TemporalAccessor parsed = FEEL_TIME.parse(val);
i... | @Test
void invokeTimeUnitsParamsNoOffsetWithNanoseconds() {
FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, BigDecimal.valueOf(15.154), null), LocalTime.of(10,
43,
... |
public void updateMetrics(String stepName, List<MonitoringInfo> monitoringInfos) {
getMetricsContainer(stepName).update(monitoringInfos);
updateMetrics(stepName);
} | @Test
void testCounterMonitoringInfoUpdate() {
MonitoringInfo userMonitoringInfo =
new SimpleMonitoringInfoBuilder()
.setUrn(MonitoringInfoConstants.Urns.USER_SUM_INT64)
.setLabel(MonitoringInfoConstants.Labels.NAMESPACE, DEFAULT_NAMESPACE)
... |
public static String escapeLuceneQuery(final CharSequence text) {
if (text == null) {
return null;
}
final int size = text.length() << 1;
final StringBuilder buf = new StringBuilder(size);
appendEscapedLuceneQuery(buf, text);
return buf.toString();
} | @Test
public void testEscapeLuceneQuery_null() {
CharSequence text = null;
String expResult = null;
String result = LuceneUtils.escapeLuceneQuery(text);
assertEquals(expResult, result);
} |
private void validateHmsUri(String catalogHmsUri) {
if (catalogHmsUri == null) {
return;
}
Configuration conf = SparkSession.active().sessionState().newHadoopConf();
String envHmsUri = conf.get(HiveConf.ConfVars.METASTOREURIS.varname, null);
if (envHmsUri == null) {
return;
}
P... | @Test
public void testValidateHmsUri() {
// HMS uris match
Assert.assertTrue(
spark
.sessionState()
.catalogManager()
.v2SessionCatalog()
.defaultNamespace()[0]
.equals("default"));
// HMS uris doesn't match
spark.sessionState().cata... |
public static Object typeConvert(String tableName ,String columnName, String value, int sqlType, String mysqlType) {
if (value == null
|| (value.equals("") && !(isText(mysqlType) || sqlType == Types.CHAR || sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR))) {
return null;
... | @Test
public void typeConvertInputNotNullNotNullNotNullPositiveNotNullOutputFalse() {
// Arrange
final String tableName = "?????????";
final String columnName = "?";
final String value = "0";
final int sqlType = 16;
final String mysqlType = "bigint\u046bunsigned";
// Act
final Object... |
@Override
protected String processLink(IExpressionContext context, String link) {
if (link == null || !linkInSite(externalUrlSupplier.get(), link)) {
return link;
}
if (StringUtils.isBlank(link)) {
link = "/";
}
if (isAssetsRequest(link)) {
... | @Test
void processNullLink() {
ThemeLinkBuilder themeLinkBuilder =
new ThemeLinkBuilder(getTheme(false), externalUrlSupplier);
String link = null;
String processed = themeLinkBuilder.processLink(null, link);
assertThat(processed).isEqualTo(null);
// empty link
... |
public void shutdownConfigRetriever() {
retriever.shutdown();
} | @Disabled("because logAndDie is impossible(?) to verify programmatically")
@Test
void manually_verify_what_happens_when_first_graph_contains_component_that_throws_exception_in_ctor() {
writeBootstrapConfigs("thrower", ComponentThrowingExceptionInConstructor.class);
Container container = newConta... |
@Override
public long read() {
return gaugeSource.read();
} | @Test
public void whenNotVisitedWithCachedValueReadsDefault() {
DynamicMetricsProvider concreteProvider = (descriptor, context) ->
context.collect(descriptor.withPrefix("foo"), "longField", INFO, COUNT, 42);
metricsRegistry.registerDynamicMetricsProvider(concreteProvider);
Lo... |
@Override
public List<MailTemplateDO> getMailTemplateList() {return mailTemplateMapper.selectList();} | @Test
public void testGetMailTemplateList() {
// mock 数据
MailTemplateDO dbMailTemplate01 = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTemplate01);
MailTemplateDO dbMailTemplate02 = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTempla... |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void useDefaultParallelismFromContextStreaming() {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(TestFlinkRunner.class);
StreamExecutionEnvironment sev =
FlinkExecutionEnvironments.createStreamExecutionEnvironment(options);
assertThat(sev, instanc... |
@KeyboardExtension.KeyboardExtensionType
public int getExtensionType() {
return mExtensionType;
} | @Test
public void testGetCurrentKeyboardExtensionExtensionDefault() throws Exception {
KeyboardExtension extension =
AnyApplication.getKeyboardExtensionFactory(getApplicationContext()).getEnabledAddOn();
Assert.assertNotNull(extension);
Assert.assertEquals("6f1ecea0-dee2-11e0-9572-0800200c9a66", e... |
@Override
public Cursor<byte[]> scan(RedisClusterNode node, ScanOptions options) {
return new ScanCursor<byte[]>(0, options) {
private RedisClient client = getEntry(node);
@Override
protected ScanIteration<byte[]> doScan(long cursorId, ScanOptions options) {... | @Test
public void testScan() {
for (int i = 0; i < 1000; i++) {
connection.set(("" + i).getBytes(StandardCharsets.UTF_8), ("" + i).getBytes(StandardCharsets.UTF_8));
}
Cursor<byte[]> b = connection.scan(ScanOptions.scanOptions().build());
int counter = 0;
while (... |
public static String unhash(int port)
{
return unhash(new StringBuilder(), port, 'z').toString();
} | @Test
public void testUnhash()
{
// theoretically up to 65535 but let's be greedy and waste 10 ms
for (int port = 0; port < 100_000; ++port) {
String hash = Utils.unhash(port);
assertThat(hash, notNullValue());
assertThat(hash.hashCode(), is(port));
}
... |
@Override
public ObjectName createName(String type, String domain, MetricName metricName) {
String name = metricName.getKey();
try {
ObjectName objectName = new ObjectName(domain, "name", name);
if (objectName.isPattern()) {
objectName = new ObjectName(domain, "name", ObjectName.quote(name));
}
... | @Test
public void createsObjectNameWithDomainInInput() {
DefaultObjectNameFactory f = new DefaultObjectNameFactory();
ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots"));
assertThat(on.getDomain()).isEqualTo("com.domain");
} |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the fe... | @Test
void testApplyTransforms_la_e_la_e()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(67, 108, 369, 101, 94);
// when
List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("কল্লোল"));
// then
assertEquals(glyphsAfterGsub, result);... |
public T setEnableSource(boolean enableSource) {
attributes.put("_source", ImmutableSortedMap.of(ENABLED, enableSource));
return castThis();
} | @Test
@UseDataProvider("indexWithAndWithoutRelations")
public void index_without_source(Index index) {
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
newIndex.setEnableSource(false);
assertThat(getAttributeAsMap(newIndex, "_source")).containsExactl... |
@Override
public boolean compareAndSet(long expect, long update) {
return get(compareAndSetAsync(expect, update));
} | @Test
public void testCompareAndSet() {
RAtomicLong al = redisson.getAtomicLong("test");
Assertions.assertFalse(al.compareAndSet(-1, 2));
Assertions.assertEquals(0, al.get());
Assertions.assertTrue(al.compareAndSet(0, 2));
Assertions.assertEquals(2, al.get());
} |
int nextAvailableBaseport(int numPorts) {
int range = 0;
int port = BASE_PORT;
for (; port < BASE_PORT + MAX_PORTS && (range < numPorts); port++) {
if (!isFree(port)) {
range = 0;
continue;
}
range++;
}
return ra... | @Test
void next_available_baseport_is_BASE_PORT_when_no_ports_have_been_reserved() {
HostPorts host = new HostPorts("myhostname");
assertThat(host.nextAvailableBaseport(1), is(HostPorts.BASE_PORT));
} |
public SpringComponentContainer createChild() {
return new SpringComponentContainer(this);
} | @Test
public void createChild_method_should_spawn_a_child_container(){
SpringComponentContainer parent = new SpringComponentContainer();
SpringComponentContainer child = parent.createChild();
assertThat(child).isNotEqualTo(parent);
assertThat(child.parent).isEqualTo(parent);
assertThat(parent.chil... |
public List<String> getStringValue() {
return stringValue;
} | @Test
public void getStringValue() {
JobScheduleParam jobScheduleParam = mock( JobScheduleParam.class );
when( jobScheduleParam.getStringValue() ).thenCallRealMethod();
List<String> stringValue = new ArrayList<>();
stringValue.add( "hitachi" );
ReflectionTestUtils.setField( jobScheduleParam, "stri... |
public static Matcher<? super Object> hasJsonPath(String jsonPath) {
return describedAs("has json path %0",
isJson(withJsonPath(jsonPath)),
jsonPath);
} | @Test
public void shouldNotMatchInvalidJsonWithPathAndValue() {
assertThat(INVALID_JSON, not(hasJsonPath("$.path", anything())));
assertThat(new Object(), not(hasJsonPath("$.path", anything())));
assertThat(null, not(hasJsonPath("$.message", anything())));
} |
@Override
@Deprecated
public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransf... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullValueTransformerSupplierOnFlatTransformValuesWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues(
(org.apache.kafka... |
void recordRecordsFetched(int records) {
recordsFetched.record(records);
} | @Test
public void testRecordsFetched() {
shareFetchMetricsManager.recordRecordsFetched(7);
time.sleep(metrics.config().timeWindowMs() + 1);
shareFetchMetricsManager.recordRecordsFetched(9);
assertEquals(9, (double) getMetric(shareFetchMetricsRegistry.recordsPerRequestMax).metricValu... |
@SuppressWarnings("unchecked")
public SchemaKTable<?> aggregate(
final List<ColumnName> nonAggregateColumns,
final List<FunctionCall> aggregations,
final Optional<WindowExpression> windowExpression,
final FormatInfo valueFormat,
final Stacker contextStacker
) {
final ExecutionStep<... | @Test
public void shouldReturnKTableWithOutputSchema() {
// When:
final SchemaKTable result = schemaGroupedStream.aggregate(
NON_AGGREGATE_COLUMNS,
ImmutableList.of(AGG),
Optional.empty(),
valueFormat.getFormatInfo(),
queryContext
);
// Then:
assertThat(res... |
@Override
public MetadataStore create(String metadataURL, MetadataStoreConfig metadataStoreConfig,
boolean enableSessionWatcher) throws MetadataStoreException {
return new EtcdMetadataStore(metadataURL, metadataStoreConfig, enableSessionWatcher);
} | @Test
public void testCluster() throws Exception {
@Cleanup
EtcdCluster etcdCluster = EtcdClusterExtension.builder().withClusterName("test-cluster").withNodes(3)
.withSsl(false).build().cluster();
etcdCluster.start();
EtcdConfig etcdConfig = EtcdConfig.builder().useT... |
public static void validate(BugPattern pattern) throws ValidationException {
if (pattern == null) {
throw new ValidationException("No @BugPattern provided");
}
// name must not contain spaces
if (CharMatcher.whitespace().matchesAnyOf(pattern.name())) {
throw new ValidationException("Name mu... | @Test
public void linkTypeNoneAndNoLink() throws Exception {
@BugPattern(
name = "LinkTypeNoneAndNoLink",
summary = "linkType none and no link",
explanation = "linkType none and no link",
severity = SeverityLevel.ERROR,
linkType = LinkType.NONE)
final class BugPatternTe... |
static JavaClasses of(Iterable<JavaClass> classes) {
Map<String, JavaClass> mapping = new HashMap<>();
for (JavaClass clazz : classes) {
mapping.put(clazz.getName(), clazz);
}
JavaPackage defaultPackage = !Iterables.isEmpty(classes)
? getRoot(classes.iterator(... | @Test
public void javaClasses_of_iterable() {
ImmutableSet<JavaClass> iterable = ImmutableSet.of(importClassWithContext(JavaClassesTest.class), importClassWithContext(JavaClass.class));
JavaClasses classes = JavaClasses.of(iterable);
assertThat(ImmutableSet.copyOf(classes)).isEqualTo(iterab... |
@Override
public void copyFrom( FileObject file, FileSelector selector ) throws FileSystemException {
requireResolvedFileObject().copyFrom( file, selector );
} | @Test
public void testDelegatesCopyFrom() throws FileSystemException {
FileObject fromFileObject = mock( FileObject.class );
FileSelector fileSelector = mock( FileSelector.class );
fileObject.copyFrom( fromFileObject, fileSelector );
verify( resolvedFileObject, times( 1 ) ).copyFrom( fromFileObject,... |
public static HealthStateScope forStage(String pipelineName, String stageName) {
return new HealthStateScope(ScopeType.STAGE, pipelineName + "/" + stageName);
} | @Test
public void shouldHaveUniqueScopeForStages() {
HealthStateScope scope1 = HealthStateScope.forStage("blahPipeline", "blahStage");
HealthStateScope scope2 = HealthStateScope.forStage("blahPipeline", "blahStage");
HealthStateScope scope25 = HealthStateScope.forStage("blahPipeline", "blahO... |
public ReferenceBuilder<T> protocol(String protocol) {
this.protocol = protocol;
return getThis();
} | @Test
void protocol() {
ReferenceBuilder builder = new ReferenceBuilder();
builder.protocol("protocol");
Assertions.assertEquals("protocol", builder.build().getProtocol());
} |
public boolean matchStage(StageConfigIdentifier stageIdentifier, StageEvent event) {
return this.event.include(event) && appliesTo(stageIdentifier.getPipelineName(), stageIdentifier.getStageName());
} | @Test
void shouldMatchBrokenStage() {
NotificationFilter filter = new NotificationFilter("cruise", "dev", StageEvent.Breaks, false);
assertThat(filter.matchStage(new StageConfigIdentifier("cruise", "dev"), StageEvent.Breaks)).isTrue();
} |
@Override
public int length() {
return 2;
} | @Test
public void testLength() {
System.out.println("length");
LogNormalDistribution instance = new LogNormalDistribution(1.0, 1.0);
instance.rand();
assertEquals(2, instance.length());
} |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void testMetadataVersionIsOlderThanKafkaVersionWithLongVersion() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withVersion(KafkaVersionTestUtils.LATEST_KAFKA_VERSION)
.withMetadataVersion(Kaf... |
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final Object options, final PasswordCallback callback) throws BackgroundException {
final Host bookmark = session.getHost();
final StringBuilder request = new StringBuilder(String.format("https://%s%s/apps/files_shar... | @Test
public void testToDownloadUrlPassword() throws Exception {
final Path home = new NextcloudHomeFeature(session.getHost()).find();
final Path file = new DAVTouchFeature(new NextcloudWriteFeature(session)).touch(new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.f... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName ... | @Test
public void testAggregateMultiStatsWhenOnlySomeAvailable() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3", "part4");
long[] values1 = { DATE_1.getDaysSinceEpoch(), DATE_2.getDaysSinceEpoch(), DATE_3.getDaysSinceEpoch() };
ColumnStatisticsData data1 = new Co... |
@Override
public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception {
this.config = config;
this.sourceContext = sourceContext;
this.intermediateTopicName = SourceConfigUtils.computeBatchSourceIntermediateTopicName(sourceContext.getTenant(),
sourceContext.getNamespac... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp =
"Bad config passed to TestTriggerer")
public void testWithoutRightTriggererConfig() throws Exception {
Map<String, Object> badConfig = new HashMap<>();
badConfig.put("something", "else");
testBatchConfig... |
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir)))
.map(GitScmProvider::extractAbsoluteFilePaths)
.orElse(null);
} | @Test
public void branchChangedFiles_should_return_null_when_branch_nonexistent() {
assertThat(newScmProvider().branchChangedFiles("nonexistent", worktree)).isNull();
} |
boolean isUpstreamDefinite() {
if (upstreamDefinite == null) {
upstreamDefinite = isRoot() || prev.isTokenDefinite() && prev.isUpstreamDefinite();
}
return upstreamDefinite;
} | @Test
public void is_upstream_definite_in_complex_case() {
assertThat(makePathReturningTail(makePPT("foo"), makePPT("bar"), makePPT("baz")).isUpstreamDefinite()).isTrue();
assertThat(makePathReturningTail(makePPT("foo"), new WildcardPathToken()).isUpstreamDefinite()).isTrue();
assertThat(m... |
public List<QueuedCommand> getRestoreCommands(final Duration duration) {
if (commandTopicBackup.commandTopicCorruption()) {
log.warn("Corruption detected. "
+ "Use backup to restore command topic.");
return Collections.emptyList();
}
return getAllCommandsInCommandTopic(
command... | @Test
public void shouldGetRestoreCommandsCorrectly() {
// Given:
when(commandConsumer.poll(any(Duration.class)))
.thenReturn(someConsumerRecords(
record1,
record2))
.thenReturn(someConsumerRecords(
record3));
when(commandConsumer.endOffsets(any())).then... |
public static Duration parse(final String text) {
try {
final String[] parts = text.split("\\s");
if (parts.length != 2) {
throw new IllegalArgumentException("Expected 2 tokens, got: " + parts.length);
}
final long size = parseNumeric(parts[0]);
return buildDuration(size, part... | @Test
public void shouldSupportNanos() {
assertThat(DurationParser.parse("27 NANOSECONDS"), is(Duration.ofNanos(27)));
} |
boolean isWriteEnclosureForFieldName( ValueMetaInterface v, String fieldName ) {
return ( isWriteEnclosed( v ) )
|| isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( fieldName.getBytes() );
} | @Test
public void testWriteEnclosureForFieldName() {
TextFileOutputData data = new TextFileOutputData();
data.binarySeparator = new byte[1];
data.binaryEnclosure = new byte[1];
data.writer = new ByteArrayOutputStream();
TextFileOutputMeta meta = getTextFileOutputMeta();
stepMockHelper.stepMeta... |
@Override
public void prepare(ExecutorDetails exec) {
this.exec = exec;
} | @Test
public void testFillUpRackAndSpilloverToNextRack() {
INimbus iNimbus = new INimbusTest();
double compPcore = 100;
double compOnHeap = 775;
double compOffHeap = 25;
int topo1NumSpouts = 1;
int topo1NumBolts = 5;
int topo1SpoutParallelism = 100;
in... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testCursorStrategyCutWithAllTextCut() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.cursorStrategy(CUT)
.sourceField("msg")
.callback(new Callable<Result[]>() {
@Override
... |
@Override
public WebSocketClientExtension handshakeExtension(WebSocketExtensionData extensionData) {
if (!PERMESSAGE_DEFLATE_EXTENSION.equals(extensionData.name())) {
return null;
}
boolean succeed = true;
int clientWindowSize = MAX_WINDOW_SIZE;
int serverWindowS... | @Test
public void testCustomHandshake() {
WebSocketClientExtension extension;
Map<String, String> parameters;
// initialize
PerMessageDeflateClientExtensionHandshaker handshaker =
new PerMessageDeflateClientExtensionHandshaker(6, true, 10, true, true);
param... |
Plugin create(Options.Plugin plugin) {
try {
return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument());
} catch (IOException | URISyntaxException e) {
throw new CucumberException(e);
}
} | @Test
void plugin_does_not_buffer_its_output() {
PrintStream previousSystemOut = System.out;
OutputStream mockSystemOut = new ByteArrayOutputStream();
try {
System.setOut(new PrintStream(mockSystemOut));
// Need to create a new plugin factory here since we need it t... |
@Override
public DevOpsProjectCreationContext create(AlmSettingDto almSettingDto, DevOpsProjectDescriptor devOpsProjectDescriptor) {
AccessToken accessToken = getAccessToken(almSettingDto);
return createDevOpsProject(almSettingDto, devOpsProjectDescriptor, accessToken);
} | @Test
void create_whenRepoFound_createsDevOpsProject() {
AlmSettingDto almSettingDto = mockAlmSettingDto();
AlmPatDto almPatDto = mockValidAccessToken(almSettingDto);
Repository repository = mockGitHubRepository(almPatDto, almSettingDto);
DevOpsProjectCreationContext devOpsProjectCreationContext = ... |
@Override
public float floatValue()
{
return value;
} | @Test
void testVeryLargeValues() throws IOException
{
double largeValue = Float.MAX_VALUE * 10d;
assertEquals(1, Double.compare(largeValue, Float.MAX_VALUE),
"Test must be performed with a value larger than Float.MAX_VALUE.");
// 1.4012984643248171E-46
String as... |
public static String encodeString(String toEncode) {
Preconditions.checkArgument(toEncode != null, "Invalid string to encode: null");
try {
return URLEncoder.encode(toEncode, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new UncheckedIOException(
Stri... | @Test
@SuppressWarnings("checkstyle:AvoidEscapedUnicodeCharacters")
public void testOAuth2URLEncoding() {
// from OAuth2, RFC 6749 Appendix B.
String utf8 = "\u0020\u0025\u0026\u002B\u00A3\u20AC";
String expected = "+%25%26%2B%C2%A3%E2%82%AC";
assertThat(RESTUtil.encodeString(utf8)).isEqualTo(expec... |
@Bean
public TimerRegistry timerRegistry(
TimerConfigurationProperties timerConfigurationProperties,
EventConsumerRegistry<TimerEvent> timerEventConsumerRegistry,
RegistryEventConsumer<Timer> timerRegistryEventConsumer,
@Qualifier("compositeTimerCustomizer") Composite... | @Test
public void shouldConfigureInstancesUsingPredefinedDefaultConfig() {
InstanceProperties instanceProperties1 = new InstanceProperties()
.setMetricNames("resilience4j.timer.operations1");
InstanceProperties instanceProperties2 = new InstanceProperties()
.setOnFail... |
public void setContract(@Nullable Produce contract)
{
this.contract = contract;
setStoredContract(contract);
handleContractState();
} | @Test
public void cabbageContractOnionHarvestableAndCabbageHarvestable()
{
final long unixNow = Instant.now().getEpochSecond();
// Get the two allotment patches
final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773);
final FarmingPatch patch2 = farmingGuildPatches.get(Varbits.FARMING_4774)... |
public void onFailedPartitionRequest() {
inputGate.triggerPartitionStateCheck(partitionId, channelInfo);
} | @Test
void testOnFailedPartitionRequestDoesNotBlockNetworkThreads() throws Exception {
final long testBlockedWaitTimeoutMillis = 30_000L;
final PartitionProducerStateChecker partitionProducerStateChecker =
(jobId, intermediateDataSetId, resultPartitionId) ->
... |
public abstract void filter(Metadata metadata) throws TikaException; | @Test
public void testConfigExcludeFilter() throws Exception {
TikaConfig config = getConfig("TIKA-3137-exclude.xml");
Metadata metadata = new Metadata();
metadata.set("title", "title");
metadata.set("author", "author");
metadata.set("content", "content");
config.get... |
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 givenLongWithSurroundingSpaces_throws() {
Long longNum = Long.parseLong("3400000000");
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" 12 ", longNum);
Schema schema =
Schema.builder()
.addInt16Field("a_short")
.addInt32Field("an_integer")
... |
@Override
public void renameTable(TableIdentifier from, TableIdentifier to) {
// check new namespace exists
if (!namespaceExists(to.namespace())) {
throw new NoSuchNamespaceException(
"Cannot rename %s to %s because namespace %s does not exist", from, to, to.namespace());
}
// keep met... | @Test
public void testRenameTable() {
AtomicInteger counter = new AtomicInteger(1);
Map<String, String> properties = Maps.newHashMap();
properties.put(
BaseMetastoreTableOperations.TABLE_TYPE_PROP,
BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE);
Mockito.doReturn(
Ge... |
@Override
public CircuitBreaker circuitBreaker(String name) {
return circuitBreaker(name, getDefaultConfig());
} | @Test
public void testCreateCircuitBreakerWithConfigName() {
CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
circuitBreakerRegistry.addConfiguration("testConfig",
CircuitBreakerConfig.custom().slidingWindowSize(5).build());
final CircuitBreak... |
public String format(Date then)
{
if (then == null)
then = now();
Duration d = approximateDuration(then);
return format(d);
} | @Test
public void testWithinTwoHoursRounding() throws Exception
{
PrettyTime t = new PrettyTime(now);
Assert.assertEquals("2 hours ago", t.format(now.minusHours(1).minusMinutes(45)));
} |
public Query generateChecksumQuery(QualifiedName tableName, List<Column> columns, Optional<Expression> partitionPredicate)
{
ImmutableList.Builder<SelectItem> selectItems = ImmutableList.builder();
selectItems.add(new SingleColumn(new FunctionCall(QualifiedName.of("count"), ImmutableList.of())));
... | @Test
public void testValidateStringAsDoubleChecksumQuery()
{
Query checksumQuery = stringAsDoubleValidator.generateChecksumQuery(
QualifiedName.of("test:di"),
ImmutableList.of(
VARCHAR_COLUMN, VARCHAR_ARRAY_COLUMN, MAP_VARCHAR_VARCHAR_COLUMN),
... |
static void setHttp2Authority(String authority, Http2Headers out) {
// The authority MUST NOT include the deprecated "userinfo" subcomponent
if (authority != null) {
if (authority.isEmpty()) {
out.authority(EMPTY_STRING);
} else {
int start = autho... | @Test
public void setHttp2AuthorityWithEmptyAuthority() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
HttpConversionUtil.setHttp2Authority("info@", new DefaultHttp2Headers());
}
});
} |
@Override
public Map<String, String> getProperties() {
Map<String, String> properties = super.getProperties();
// For materialized view, add into session variables into properties.
if (super.getTableProperty() != null && super.getTableProperty().getProperties() != null) {
for (Ma... | @Test
public void testMaterializedViewWithHint() throws Exception {
starRocksAssert.withDatabase("test").useDatabase("test")
.withTable("CREATE TABLE test.tbl1\n" +
"(\n" +
" k1 date,\n" +
" k2 int,\n" +
... |
@Override
public List<String> tokenise(String text) {
if (text == null || text.isEmpty()) {
return new ArrayList<>();
}
text = text.replaceAll("[^\\p{L}\\p{N}\\s\\-'.]", " ").trim();
String[] parts = text.split("\\s+");
var tokenBuilder = new StringBuilder();
List<String> tokenParts =... | @Description("Tokenise, when text only has one word, then return one word")
@Test
void tokenise_WhenTextOnlyHasOneWord_ThenReturnOneToken() {
// When
var result = textTokeniser.tokenise("Glasgow");
// Then
assertThat(result).isNotEmpty().hasSize(1).contains("Glasgow");
} |
@Override
protected ConfigData<RuleData> fromJson(final JsonObject data) {
return GsonUtils.getGson().fromJson(data, new TypeToken<ConfigData<RuleData>>() {
}.getType());
} | @Test
public void testFromJson() {
ConfigData<RuleData> ruleDataConfigData = new ConfigData<>();
RuleData ruleData = new RuleData();
ruleDataConfigData.setData(Collections.singletonList(ruleData));
JsonObject jsonObject = GsonUtils.getGson().fromJson(GsonUtils.getGson().toJson(ruleDa... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
... | @Test
public void testGetFieldDefinition() {
VectorWiseDatabaseMeta nativeMeta;
nativeMeta = new VectorWiseDatabaseMeta();
nativeMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE );
assertEquals( "FOO TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true,... |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("name", (Gauge<String>) runtime::getName);
gauges.put("vendor", (Gauge<String>) () -> String.format(Locale.US,
"%s %s %s (%s)",
runtime.getVmVen... | @Test
public void autoDiscoversTheRuntimeBean() {
final Gauge<Long> gauge = (Gauge<Long>) new JvmAttributeGaugeSet().getMetrics().get("uptime");
assertThat(gauge.getValue()).isPositive();
} |
public static <T> TreeSet<Point<T>> subset(TimeWindow subsetWindow, NavigableSet<Point<T>> points) {
checkNotNull(subsetWindow);
checkNotNull(points);
//if the input collection is empty the output collection will be empty to
if (points.isEmpty()) {
return newTreeSet();
... | @Test
public void subset_returnsEmptyCollectionWhenNothingQualifies() {
Track<NopHit> t1 = createTrackFromFile(getResourceFile("Track1.txt"));
TimeWindow windowThatDoesNotOverlapWithTrack = TimeWindow.of(EPOCH, EPOCH.plusSeconds(100));
TreeSet<Point<NopHit>> subset = subset(windowThatDoes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.