focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@NonNull public static String getSysInfo(@NonNull Context context) {
StringBuilder sb = new StringBuilder();
sb.append("BRAND:").append(Build.BRAND).append(NEW_LINE);
sb.append("DEVICE:").append(Build.DEVICE).append(NEW_LINE);
sb.append("Build ID:").append(Build.DISPLAY).append(NEW_LINE);
sb.append(... | @Test
public void testGetSysInfo() {
String info = ChewbaccaUtils.getSysInfo(ApplicationProvider.getApplicationContext());
Assert.assertTrue(info.contains("BRAND:" + Build.BRAND));
Assert.assertTrue(info.contains("VERSION.SDK_INT:" + Build.VERSION.SDK_INT));
Assert.assertTrue(
info.contains(
... |
@Override
public AppResponse process(Flow flow, SessionDataRequest request) throws SharedServiceClientException {
return validateAmountOfApps(flow, appSession.getAccountId(), request)
.orElseGet(() -> validateSms(flow, appSession.getAccountId(), request.getSmscode())
.orElseGet(... | @Test
void processAccountRequestSessionDataTest() throws SharedServiceClientException {
AppAuthenticator appAuthenticatorMock = new AppAuthenticator();
appAuthenticatorMock.setAccountId(ACCOUNT_ID);
appAuthenticatorMock.setDeviceName(mockedSessionDataRequest.getDeviceName());
appAuth... |
public T fromBytes(byte[] bytes) throws IOException {
return fromJson(new String(bytes, 0, bytes.length, UTF_8));
} | @Test
public void testBadBytesRoundTrip() throws Throwable {
LambdaTestUtils.intercept(JsonParseException.class,
"token",
() -> serDeser.fromBytes(new byte[]{'a'}));
} |
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
ConfigServer[] configServers = getConfigServers();
int[] zookeeperIds = getConfigServerZookeeperIds();
if (configServers.length != zookeeperIds.length) {
throw new IllegalArgumentException(String.format("Nu... | @Test
void zookeeperConfig_self_hosted() {
final boolean hostedVespa = false;
TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(4, 2, 3), hostedVespa);
ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions);
assertZo... |
public static String prettyFormatXml(CharSequence xml) {
String xmlString = xml.toString();
StreamSource source = new StreamSource(new StringReader(xmlString));
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
try {
... | @Test
public void prettyFormatXmlTest() {
final String uglyXml = "<foo attr1='value1' attr2='value2'><inner-element attr1='value1'>Test</inner-element></foo>";
final String prettyXml = XmlUtil.prettyFormatXml(uglyXml);
assertEquals("<foo attr1=\"value1\" attr2=\"value2\">\n <inner-element... |
@Override
public int readerIndex() {
return readerIndex;
} | @Test
void initialState() {
assertEquals(CAPACITY, buffer.capacity());
assertEquals(0, buffer.readerIndex());
} |
@Override
public NativeEntity<DataAdapterDto> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
... | @Test
public void createNativeEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.LOOKUP_ADAPTER_V1)
.data(objectMapper.convertValue(LookupDataAdapterEntity.create(
ValueReference.of(DefaultEntitySc... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Version", server.getVersion());
setAttribute(protobuf, "Official Distribution", officialDistribution.ch... | @Test
public void return_official_distribution_flag() {
when(officialDistrib.check()).thenReturn(true);
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThatAttributeIs(section, "Official Distribution", true);
} |
private Map<String, Object> augmentAndFilterConnectorConfig(String connectorConfigs) throws IOException {
return augmentAndFilterConnectorConfig(connectorConfigs, instanceConfig, secretsProvider,
componentClassLoader, componentType);
} | @Test(dataProvider = "configIgnoreUnknownFields")
public void testSinkConfigIgnoreUnknownFields(boolean ignoreUnknownConfigFields,
FunctionDetails.ComponentType type) throws Exception {
NarClassLoader narClassLoader = mock(NarClassLoader.class);
fina... |
public static String colorTag(Color color)
{
return OPENING_COLOR_TAG_START + colorToHexCode(color) + OPENING_COLOR_TAG_END;
} | @Test
public void colorTag()
{
COLOR_HEXSTRING_MAP.forEach((color, hex) ->
{
assertEquals("<col=" + hex + ">", ColorUtil.colorTag(color));
});
} |
public static String format(String json) {
final StringBuilder result = new StringBuilder();
Character wrapChar = null;
boolean isEscapeMode = false;
int length = json.length();
int number = 0;
char key;
for (int i = 0; i < length; i++) {
key = json.charAt(i);
if (CharUtil.DOUBLE_QUOTES == key || ... | @Test
public void formatTest3() {
String json = "{\"id\":13,\"title\":\"《标题》\",\"subtitle\":\"副标题z'c'z'xv'c'xv\",\"user_id\":6,\"type\":0}";
String result = JSONStrFormatter.format(json);
assertNotNull(result);
} |
public static <T> Match<T> ifNotValue(T value) {
return new Match<>(value, true);
} | @Test
public void testIfNotValue() {
Match<String> m1 = Match.ifNotValue(null);
Match<String> m2 = Match.ifNotValue("foo");
assertFalse(m1.matches(null));
assertFalse(m2.matches("foo"));
} |
static JavaInput reorderModifiers(String text) throws FormatterException {
return reorderModifiers(
new JavaInput(text), ImmutableList.of(Range.closedOpen(0, text.length())));
} | @Test
public void everythingIncludingDefault() throws FormatterException {
assertThat(
ModifierOrderer.reorderModifiers(
"strictfp native synchronized volatile transient final static default abstract"
+ " private protected public")
.getText()... |
public void clean(final Date now) {
List<String> files = this.findFiles();
List<String> expiredFiles = this.filterFiles(files, this.createExpiredFileFilter(now));
for (String f : expiredFiles) {
this.delete(new File(f));
}
if (this.totalSizeCap != CoreConstants.UNBOUNDED_TOTAL_SIZE_CAP && thi... | @Test
public void keepsParentDirWhenNonEmpty() {
// Setting an expiration date of 0 would cause no files to be deleted
remover.clean(new Date(0));
verify(fileProvider, never()).deleteFile(any(File.class));
} |
@Override
public void abortCheckpointOnBarrier(long checkpointId, CheckpointException cause)
throws IOException {
if (isCurrentSyncSavepoint(checkpointId)) {
throw new FlinkRuntimeException("Stop-with-savepoint failed.");
}
subtaskCheckpointCoordinator.abortCheckpoint... | @Test
void testSavepointTerminateAborted() {
assertThatThrownBy(
() ->
testSyncSavepointWithEndInput(
(task, id) ->
task.abortCheckpointOnBarrier(
... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldThrowOnClusterAuthorizationException() {
// Given:
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
allAndPseudoColumnNames(SCHEMA),
ImmutableList.of(
new LongLiteral(1L),
new StringLiteral("str"),
new StringLite... |
public Optional<RouteContext> loadRouteContext(final OriginSQLRouter originSQLRouter, final QueryContext queryContext, final RuleMetaData globalRuleMetaData,
final ShardingSphereDatabase database, final ShardingCache shardingCache, final ConfigurationProperties props,
... | @Test
void assertCreateRouteContextWithCacheableQueryButCacheMissed() {
QueryContext queryContext =
new QueryContext(sqlStatementContext, "insert into t values (?, ?)", Arrays.asList(0, 1), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class));
when(sha... |
@Override
public int predict(double[] x) {
if (x.length != p) {
throw new IllegalArgumentException(String.format("Invalid input vector size: %d, expected: %d", x.length, p));
}
double[] wx = project(x);
int y = 0;
double nearest = Double.POSITIVE_INFINITY;
... | @Test
public void testUSPS() throws Exception {
System.out.println("USPS");
ClassificationValidation<FLD> result = ClassificationValidation.of(USPS.x, USPS.y, USPS.testx, USPS.testy, FLD::fit);
System.out.println(result);
assertEquals(262, result.metrics.error);
java.nio.f... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_object() {
registry.setDefaultDataTableEntryTransformer(TABLE_ENTRY_BY_TYPE_CONVERTER_SHOULD_NOT_BE_USED);
registry.setDefaultDataTableCellTransformer(TABLE_CELL_BY_TYPE_CONVERTER_SHOULD_NOT_BE_USED);
DataTable table = parse("",
" | | 1 | 2 | 3 |",
... |
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_reflectsStartTime() {
Track<NopHit> t1 = createTrackFromFile(getResourceFile("Track1.txt"));
//this is the time of 21st point in the track
Instant startTime = parseNopTime("07/08/2017", "14:10:45.534");
TimeWindow extractionWindow = TimeWindow.of(startTime... |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testEqualsMapWithBytesKeyFieldWorksOnReferenceEquality() throws Exception {
FieldType fieldType = FieldType.map(FieldType.BYTES, FieldType.INT32);
Schema schema = Schema.of(Schema.Field.of("f1", fieldType));
RowCoder coder = RowCoder.of(schema);
Map<byte[], Integer> map = Collection... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Un... | @Test
public void shouldVisitDecimal() {
// Given:
final SqlDecimal type = SqlTypes.decimal(10, 2);
when(visitor.visitDecimal(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitDecimal(same(type));
assertTh... |
public static Float toFloat(Object value, Float defaultValue) {
return convertQuietly(Float.class, value, defaultValue);
} | @Test
public void doubleToFloatTest() {
final double a = 0.45f;
final float b = Convert.toFloat(a);
assertEquals(a, b, 0);
} |
@Override
public void actionPerformed(ActionEvent e) {
if (this.ok.equals(e.getSource())) {
this.fileName = this.input.getText();
presenter.fileNameChanged();
presenter.confirmed();
} else if (this.cancel.equals(e.getSource())) {
presenter.cancelled();
}
} | @Test
void testActionEvent() {
assertDoesNotThrow(() ->{
FileSelectorJframe jFrame = new FileSelectorJframe();
ActionEvent action = new ActionEvent("dummy", 1, "dummy");
jFrame.actionPerformed(action);
});
} |
public String getLogChannelId() {
return log.getLogChannelId();
} | @Test
public void testTwoJobsGetSameLogChannelId() {
Repository repository = mock( Repository.class );
JobMeta meta = mock( JobMeta.class );
Job job1 = new Job( repository, meta );
Job job2 = new Job( repository, meta );
assertEquals( job1.getLogChannelId(), job2.getLogChannelId() );
} |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_cluster() {
// When
run("cluster");
// Then
String actual = captureOut();
assertContains(actual, hz.getCluster().getLocalMember().getUuid().toString());
assertContains(actual, "ACTIVE");
} |
public static String getProcessId(Path path) throws IOException {
if (path == null) {
throw new IOException("Trying to access process id from a null path");
}
LOG.debug("Accessing pid from pid file {}", path);
String processId = null;
BufferedReader bufReader = null;
try {
File file... | @Test (timeout = 30000)
public void testComplexGet() throws IOException {
String rootDir = new File(System.getProperty(
"test.build.data", "/tmp")).getAbsolutePath();
File testFile = null;
String processIdInFile = Shell.WINDOWS ?
" container_1353742680940_0002_01_000001 " :
" 23 ";
... |
List<?> apply(
final GenericRow row,
final ProcessingLogger processingLogger
) {
final Object[] args = new Object[parameterExtractors.size()];
for (int i = 0; i < parameterExtractors.size(); i++) {
args[i] = evalParam(row, processingLogger, i);
}
try {
final List<?> result = ... | @SuppressWarnings("unchecked")
@Test
public void shouldCallEvaluatorWithCorrectParams() {
// When:
applier.apply(VALUE, processingLogger);
// Then:
final ArgumentCaptor<Supplier<String>> errorMsgCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(paramExtractor)
.evaluate(eq(VALUE)... |
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
return fromVersion == 0 ?
upgradeRuleNodesWithOldPropertyToUseFetchTo(
oldConfiguration,
"addToMetadata",
... | @Test
public void givenOldConfig_whenUpgrade_thenShouldReturnTrueResultWithNewConfig() throws Exception {
var defaultConfig = new TbGetTenantDetailsNodeConfiguration().defaultConfiguration();
var node = new TbGetTenantDetailsNode();
String oldConfig = "{\"detailsList\":[],\"addToMetadata\":f... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldRegisterValueOverrideSchemaProtobuf()
throws IOException, RestClientException {
// Given:
when(schemaRegistryClient.register(anyString(), any(ParsedSchema.class))).thenReturn(1);
final SchemaAndId schemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), PROTOBUF_SCHEMA, 1);
... |
static boolean applyTags(RuleDto rule, Set<String> tags) {
for (String tag : tags) {
RuleTagFormat.validate(tag);
}
Set<String> initialTags = rule.getTags();
final Set<String> systemTags = rule.getSystemTags();
Set<String> withoutSystemTags = Sets.filter(tags, input -> input != null && !syste... | @Test
public void applyTags_remove_all_existing_tags() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Collections.emptySet());
assertThat(rule.getTags()).isEmpty();
assertThat(changed).isTrue();
} |
@Override
public ConsumerBuilder<T> maxTotalReceiverQueueSizeAcrossPartitions(int maxTotalReceiverQueueSizeAcrossPartitions) {
checkArgument(maxTotalReceiverQueueSizeAcrossPartitions >= 0,
"maxTotalReceiverQueueSizeAcrossPartitions needs to be >= 0");
conf.setMaxTotalReceiverQueueSiz... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testConsumerBuilderImplWhenMaxTotalReceiverQueueSizeAcrossPartitionsPropertyIsNegative() {
consumerBuilderImpl.maxTotalReceiverQueueSizeAcrossPartitions(-1);
} |
public static void requireNotEmpty(final String str, final String name) {
requireNotNull(str, name);
if (str.isEmpty()) {
throw new IllegalArgumentException(name + " is an empty string");
}
} | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".*foo.*")
public void testNotEmptyWithEmptyString() {
ArgumentUtil.requireNotEmpty("", "foo");
} |
public Duration cacheNegativeTimeToLive() {
return cacheNegativeTimeToLive;
} | @Test
void cacheNegativeTimeToLive() {
assertThat(builder.build().cacheNegativeTimeToLive()).isEqualTo(DEFAULT_CACHE_NEGATIVE_TIME_TO_LIVE);
Duration cacheNegativeTimeToLive = Duration.ofSeconds(5);
builder.cacheNegativeTimeToLive(cacheNegativeTimeToLive);
assertThat(builder.build().cacheNegativeTimeToLive())... |
@Override
public String[] split(String text) {
boundary.setText(text);
List<String> words = new ArrayList<>();
int start = boundary.first();
int end = boundary.next();
while (end != BreakIterator.DONE) {
String word = text.substring(start, end).trim();
... | @Test
public void testSplit() {
System.out.println("tokenize");
String text = "Good muffins cost $3.88\nin New York. Please buy "
+ "me\ntwo of them.\n\nYou cannot eat them. I gonna eat them. "
+ "Thanks. Of course, I won't. ";
String[] expResult = {"Good", ... |
public static String prependColorTag(final String str, final Color color)
{
return colorTag(color) + str;
} | @Test
public void prependColorTag()
{
COLOR_HEXSTRING_MAP.forEach((color, hex) ->
{
assertEquals("<col=" + hex + ">test", ColorUtil.prependColorTag("test", color));
assertEquals("<col=" + hex + ">", ColorUtil.prependColorTag("", color));
});
assertEquals("<col=ff0000>94<col=ffffff>/99", ColorUtil.prepe... |
public static CompilationUnit getKiePMMLModelCompilationUnit(final String className,
final String packageName,
final String javaTemplate,
... | @Test
void getKiePMMLModelCompilationUnitWithoutPackage() {
String className = "ClassName";
CompilationUnit retrieved = JavaParserUtils.getKiePMMLModelCompilationUnit(className, null, TEMPLATE_FILE, TEMPLATE_CLASS);
assertThat(retrieved).isNotNull();
assertThat(retrieved.getPackageD... |
public static String convertToString(String[] value) {
if (value == null || value.length == 0) {
return null;
}
StringBuffer result = new StringBuffer(String.valueOf(value[0]));
for (int i = 1; i < value.length; i++) {
result.append(",").append(value[i]);
... | @Test
public void testConvertToString() throws Exception {
assertEquals(null, StringArrayConverter.convertToString(null));
assertEquals(null, StringArrayConverter.convertToString(new String[]{}));
assertEquals("", StringArrayConverter.convertToString(new String[]{""}));
assertEquals(... |
public Map<String, List<String>> parameters() {
if (params == null) {
params = decodeParams(uri, pathEndIdx(), charset, maxParams, semicolonIsNormalChar);
}
return params;
} | @Test
public void testBasicUris() throws URISyntaxException {
QueryStringDecoder d = new QueryStringDecoder(new URI("http://localhost/path"));
assertEquals(0, d.parameters().size());
} |
@Override
public <KR, VR> KStream<KR, VR> flatMap(final KeyValueMapper<? super K, ? super V, ? extends Iterable<? extends KeyValue<? extends KR, ? extends VR>>> mapper) {
return flatMap(mapper, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullMapperOnFlatMap() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatMap(null));
assertThat(exception.getMessage(), equalTo("mapper can't be null"));
} |
public static KHyperLogLog merge(KHyperLogLog khll1, KHyperLogLog khll2)
{
// Return the one with smallest K so resolution is not lost. This loss would happen in the case
// one merged a smaller KHLL into a bigger one because the former's minhash struct won't
// cover all of the latter's ... | @Test
public void testMerge()
throws Exception
{
// small vs small
verifyMerge(LongStream.rangeClosed(0, 100), LongStream.rangeClosed(50, 150));
// small vs big
verifyMerge(LongStream.rangeClosed(0, 100), LongStream.rangeClosed(50, 5000));
// big vs small
... |
@Override
public Result responseMessageForCheckConnectionToRepository(String responseBody) {
return jsonResultMessageHandler.toResult(responseBody);
} | @Test
public void shouldHandleNullMessagesForCheckRepositoryConnectionResponse() throws Exception {
assertSuccessResult(messageHandler.responseMessageForCheckConnectionToRepository("{\"status\":\"success\"}"), new ArrayList<>());
assertFailureResult(messageHandler.responseMessageForCheckConnectionTo... |
@Override
public Address getCaller() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testGetCaller() {
queryCacheEventData.getCaller();
} |
@Bean
public PluginDataHandler paramMappingPluginDataHandler() {
return new ParamMappingPluginDataHandler();
} | @Test
public void testParamMappingPluginDataHandler() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ParamMappingPluginConfiguration.class, DefaultServerCodecConfigurer.class))
.withBean(ParamMappingPluginConfigurationTest.class)
.withPropertyVa... |
@Override
public ScalarOperator visitCastOperator(CastOperator operator, Void context) {
return shuttleIfUpdate(operator);
} | @Test
void visitCastOperator() {
CastOperator operator = new CastOperator(INT, new ColumnRefOperator(1, INT, "id", true));
{
ScalarOperator newOperator = shuttle.visitCastOperator(operator, null);
assertEquals(operator, newOperator);
}
{
ScalarOper... |
public static HttpResponseStatus valueOf(int code) {
HttpResponseStatus status = valueOf0(code);
return status != null ? status : new HttpResponseStatus(code);
} | @Test
public void testHttpStatusClassValueOf() {
// status scope: [100, 600).
for (int code = 100; code < 600; code ++) {
HttpStatusClass httpStatusClass = HttpStatusClass.valueOf(code);
assertNotSame(HttpStatusClass.UNKNOWN, httpStatusClass);
if (HttpStatusClass.... |
public static SQLException toSQLException(final Exception cause, final DatabaseType databaseType) {
if (cause instanceof SQLException) {
return (SQLException) cause;
}
if (cause instanceof ShardingSphereSQLException) {
return ((ShardingSphereSQLException) cause).toSQLExce... | @Test
void assertToSQLExceptionWithSQLDialectException() {
assertThat(SQLExceptionTransformEngine.toSQLException(mock(SQLDialectException.class), databaseType).getMessage(), is("Dialect exception"));
} |
public CompletableFuture<Void> waitAsync(CompletableFuture<Void> eventPubFuture,
String bundle,
UnloadDecision decision,
long timeout,
TimeU... | @Test
public void testTimeout() throws IllegalAccessException {
UnloadCounter counter = new UnloadCounter();
UnloadManager manager = new UnloadManager(counter, "mockBrokerId");
var unloadDecision =
new UnloadDecision(new Unload("broker-1", "bundle-1"), Success, Admin);
... |
public String buildSql(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain)
{
// SELECT clause
StringBuilder sql = new StringBuilder("SELECT ");
if (columns.isEmpty()) {
sql.append("' '");
}
else {
String columnNames = columns.st... | @Test
public void testDateColumn()
{
List<HiveColumnHandle> columns = ImmutableList.of(
new HiveColumnHandle("t1", HIVE_TIMESTAMP, parseTypeSignature(TIMESTAMP), 0, REGULAR, Optional.empty(), Optional.empty()),
new HiveColumnHandle("t2", HIVE_DATE, parseTypeSignature(Stan... |
@Override
public ObjectNode encode(LispListAddress address, CodecContext context) {
checkNotNull(address, "LispListAddress cannot be null");
final ObjectNode result = context.mapper().createObjectNode();
final JsonCodec<MappingAddress> addressCodec =
context.codec(MappingAd... | @Test
public void testLispListAddressEncode() {
LispListAddress address = new LispListAddress.Builder()
.withIpv4(MappingAddresses.ipv4MappingAddress(IPV4_PREFIX))
.withIpv6(MappingAddresses.ipv6MappingAddress(IPV6_PREFIX))
.build();
ObjectNode address... |
public static Builder builder() {
return new Builder();
} | @Test
public void testCanUseNullAsPropertyValue() throws JsonProcessingException {
String jsonNullValueInDefaults =
"{\"defaults\":{\"warehouse\":null},\"overrides\":{\"clients\":\"5\"}}";
assertRoundTripSerializesEquallyFrom(
jsonNullValueInDefaults,
ConfigResponse.builder()
... |
@Override
public List<Path> run(final Session<?> session) throws BackgroundException {
final Delete delete;
if(trash) {
if(null == session.getFeature(Trash.class)) {
log.warn(String.format("No trash feature available for %s", session));
delete = session.ge... | @Test
public void testCompileDefault() throws Exception {
final Session session = new NullSession(new Host(new TestProtocol())) {
@Override
@SuppressWarnings("unchecked")
public <T> T _getFeature(final Class<T> type) {
if(type == Delete.class) {
... |
@Override
public String format(Object value) {
return value == null ? EMPTY : nonNullFormat(value);
} | @Test
public void nullInput() {
assertEquals("wrong result", "", frm.format(null));
} |
@Override
public void close() throws Exception {
handlesToClose.forEach(IOUtils::closeQuietly);
handlesToClose.clear();
if (sharedResources != null) {
sharedResources.close();
}
cleanRelocatedDbLogs();
} | @Test
public void testFreeSharedResourcesAfterClose() throws Exception {
LRUCache cache = new LRUCache(1024L);
WriteBufferManager wbm = new WriteBufferManager(1024L, cache);
ForStSharedResources sharedResources = new ForStSharedResources(cache, wbm, 1024L, false);
final ThrowingRunna... |
@Override
public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) {
if (null == yamlConfig) {
return null;
}
if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) {
return new TableDataConsistencyCheckResult(TableDa... | @Test
void assertSwapToObjectWithYamlTableDataConsistencyCheckResultMatched() {
YamlTableDataConsistencyCheckResult yamlConfig = new YamlTableDataConsistencyCheckResult(true);
TableDataConsistencyCheckResult result = yamlTableDataConsistencyCheckResultSwapper.swapToObject(yamlConfig);
assert... |
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) {
Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>();
for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) {
Map<String, ... | @Test
public void testValidateAndParseInvalidOffset() {
Map<String, Object> partition = new HashMap<>();
partition.put(SinkUtils.KAFKA_TOPIC_KEY, "topic");
partition.put(SinkUtils.KAFKA_PARTITION_KEY, 10);
Map<String, Object> offset = new HashMap<>();
Map<Map<String, ?>, Map<... |
public static KTableHolder<GenericKey> build(
final KGroupedStreamHolder groupedStream,
final StreamAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedStream,
aggregate,
buildContext,
... | @Test
public void shouldReturnCorrectSerdeForWindowedAggregate() {
for (final Runnable given : given()) {
// Given:
clearInvocations(groupedStream, timeWindowedStream, sessionWindowedStream, aggregated, buildContext);
given.run();
// When:
final KTableHolder<Windowed<GenericKey>> ta... |
@Override
public RecoverableFsDataOutputStream open(Path path) throws IOException {
LOGGER.trace("Opening output stream for path {}", path);
Preconditions.checkNotNull(path);
GSBlobIdentifier finalBlobIdentifier = BlobUtils.parseUri(path.toUri());
return new GSRecoverableFsDataOutpu... | @Test(expected = IllegalArgumentException.class)
public void testOpenWithEmptyObjectName() throws IOException {
Path path = new Path("gs://foo/");
writer.open(path);
} |
public static IpAddress valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new IpAddress(Version.INET, bytes);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfShortArrayIPv4() {
IpAddress ipAddress;
byte[] value;
value = new byte[] {1, 2, 3};
ipAddress = IpAddress.valueOf(IpAddress.Version.INET, value);
} |
Optional<Integer> lastEpochSentOnCommit() {
return lastEpochSentOnCommit;
} | @Test
public void testLastEpochSentOnCommit() {
// Enable auto-commit but with very long interval to avoid triggering auto-commits on the
// interval and just test the auto-commits triggered before revocation
CommitRequestManager commitRequestManager = create(true, Integer.MAX_VALUE);
... |
public void removeBufferLinesBefore( long minTimeBoundary ) {
buffer.values().stream().filter( v -> v.getEvent().timeStamp < minTimeBoundary ).forEach( v -> buffer.remove( v.getNr() ) );
} | @Test
public void testRemoveBufferLinesBefore() {
LoggingBuffer loggingBuffer = new LoggingBuffer( 100 );
for ( int i = 0; i < 40; i++ ) {
KettleLoggingEvent event = new KettleLoggingEvent();
event.setMessage( new LogMessage( "test", LogLevel.BASIC ) );
event.setTimeStamp( i );
logging... |
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) {
return decorateTextWithHtml(text, decorationDataHolder, null, null);
} | @Test
public void returned_code_end_to_given_param() {
String javadocWithHtml =
"/**\n" +
" * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.\n" +
" * \n" +
" * This framework can used for instance in order to :\n" +
... |
@PublicAPI(usage = ACCESS)
public JavaClasses importUrl(URL url) {
return importUrls(singletonList(url));
} | @Test
public void imports_simple_local_class() throws Exception {
JavaClasses classes = new ClassFileImporter().importUrl(getClass().getResource("testexamples/innerclassimport"));
JavaClass localClass = classes.get(ClassWithInnerClass.class.getName() + "$1LocalCaller");
assertThat(localClas... |
public ByteBuffer[] getPages() {
int numPages = _pages.size();
boolean lastPageIsEmpty = _written == (numPages - 1) * (long) _pageSize;
if (lastPageIsEmpty) {
numPages--;
}
if (numPages == 0) {
return new ByteBuffer[0];
}
ByteBuffer[] result = new ByteBuffer[numPages];
for ... | @Test
void testGetPagesEmpty() {
ByteBuffer[] pages = _pagedPinotOutputStream.getPages();
assertEquals(pages.length, 0);
} |
@Override
public void setConfig(RedisClusterNode node, String param, String value) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value);
syncFuture(f);
} | @Test
public void testSetConfig() {
testInCluster(connection -> {
RedisClusterNode master = getFirstMaster(connection);
connection.setConfig(master, "timeout", "10");
});
} |
public String toString() {
StringBuilder sb = new StringBuilder();
Type prevType = null;
for (InterpreterResultMessage m : msg) {
if (prevType != null) {
sb.append("\n");
if (prevType == Type.TABLE) {
sb.append("\n");
}
}
sb.append(m.toString());
pre... | @Test
void testToString() {
assertEquals("%html hello", new InterpreterResult(InterpreterResult.Code.SUCCESS,
"%html hello").toString());
} |
@Override
public void open(Configuration parameters) throws Exception {
this.rateLimiterTriggeredCounter =
getRuntimeContext()
.getMetricGroup()
.addGroup(
TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT)
.counter(TableMain... | @Test
void testDataFileSizeInBytes() throws Exception {
TriggerManager manager =
manager(
sql.tableLoader(TABLE_NAME),
new TriggerEvaluator.Builder().dataFileSizeInBytes(3).build());
try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness =
... |
public static byte[] encode(byte[] arr, boolean lineSep) {
if (arr == null) {
return null;
}
return lineSep ?
java.util.Base64.getMimeEncoder().encode(arr) :
java.util.Base64.getEncoder().encode(arr);
} | @Test
public void issuesI5QR4WTest(){
String a = java.util.Base64.getEncoder().encodeToString("111".getBytes()); //java.util.Base64
String b = Base64.encode("111"); //cn.hutool.core.codec.Base64
assertEquals(a, b);
} |
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(d... | @Test
public void testRoadClass() {
EdgeIteratorState primary = graph.edge(0, 1).setDistance(10).
set(roadClassEnc, PRIMARY).set(avSpeedEnc, 80);
EdgeIteratorState secondary = graph.edge(1, 2).setDistance(10).
set(roadClassEnc, SECONDARY).set(avSpeedEnc, 80);
... |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
... | @Test
public void decimalToJsonWithoutSchema() {
assertThrows(
DataException.class,
() -> converter.fromConnectData(TOPIC, null, new BigDecimal(new BigInteger("156"), 2)),
"expected data exception when serializing BigDecimal without schema");
} |
public Optional<String> identityFromSignature(final String password) {
// for some generators, identity in the clear is just not a part of the password
if (!prependUsername || shouldDeriveUsername() || StringUtils.isBlank(password)) {
return Optional.empty();
}
// checking for the case of unexpect... | @Test
public void testGetIdentityFromSignatureIsTimestamp() {
final String identity = usernameIsTimestampGenerator.identityFromSignature(usernameIsTimestampCredentials.password()).orElseThrow();
assertEquals(USERNAME_TIMESTAMP, identity);
} |
@Override
public void onBufferFinished() {
Optional<Decision> decision =
spillStrategy.onBufferFinished(numUnSpillBuffers.incrementAndGet(), getPoolSize());
handleDecision(decision);
} | @Test
void testHandleEmptyDecision() throws Exception {
CompletableFuture<Void> globalDecisionFuture = new CompletableFuture<>();
HsSpillingStrategy spillingStrategy =
TestingSpillingStrategy.builder()
.setOnBufferFinishedFunction(
... |
public static Fiat parseFiat(final String currencyCode, final String str) {
try {
long val = new BigDecimal(str).movePointRight(SMALLEST_UNIT_EXPONENT).longValueExact();
return Fiat.valueOf(currencyCode, val);
} catch (ArithmeticException e) {
throw new IllegalArgumen... | @Test(expected = IllegalArgumentException.class)
public void testParseFiatOverprecise() {
Fiat.parseFiat("EUR", "0.00011");
} |
public LogicalSlot allocateLogicalSlot() {
LOG.debug("Allocating logical slot from shared slot ({})", physicalSlotRequestId);
Preconditions.checkState(
state == State.ALLOCATED, "The shared slot has already been released.");
final LogicalSlot slot =
new SingleLog... | @Test
void testAllocateLogicalSlot() {
final TestingPhysicalSlot physicalSlot = TestingPhysicalSlot.builder().build();
final SharedSlot sharedSlot =
new SharedSlot(new SlotRequestId(), physicalSlot, false, () -> {});
final LogicalSlot logicalSlot = sharedSlot.allocateLogical... |
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
if (targetClass != null && targetClass != method.getDeclaringClass() && isOverridable(method, targetClass)) {
try {
if (Modifier.isPublic(method.getModifiers())) {
try {
... | @Test
public void testGetMostSpecificPrivateMethod() throws NoSuchMethodException {
Method method = AbstractList.class.getDeclaredMethod("rangeCheckForAdd", int.class);
Method specificMethod = ClassUtils.getMostSpecificMethod(method, ArrayList.class);
assertNotEquals(ArrayList.class.getDecla... |
public Set<String> validate(String expr, Set<String> whitelistVars) throws Exception {
checkExprLength(expr);
selParser.ReInit(new ByteArrayInputStream(expr.getBytes()));
ASTExecute n = selParser.Execute();
Map<String, Boolean> vars = new HashMap<>();
n.jjtAccept(validator, vars);
Set<String> r... | @Test
public void testValidate() throws Exception {
Set<String> res = t1.validate("x.length;", new HashSet<>());
assertEquals("[x]", res.toString());
} |
public ListenableFuture<ListPluginsResponse> listPluginsWithDeadline(
ListPluginsRequest request, Deadline deadline) {
return pluginService.withDeadline(deadline).listPlugins(request);
} | @Test
public void listPlugins_returnsMultiplePlugins() throws Exception {
ListPluginsRequest request = ListPluginsRequest.getDefaultInstance();
List<PluginDefinition> plugins = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
plugins.add(createSinglePluginDefinitionWithName(String.format(PLUGIN_... |
public Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> newChannelInitializers() {
Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> channelInitializers = new HashMap<>();
Set<InetSocketAddress> addresses = new HashSet<>();
for (Map.Entry<String, Proto... | @Test
public void testNewChannelInitializersSuccess() {
ChannelInitializer<SocketChannel> i1 = mock(ChannelInitializer.class);
ChannelInitializer<SocketChannel> i2 = mock(ChannelInitializer.class);
Map<InetSocketAddress, ChannelInitializer<SocketChannel>> p1Initializers = new HashMap<>();
... |
public static TypeBuilder<Schema> builder() {
return new TypeBuilder<>(new SchemaCompletion(), new NameContext());
} | @Test
void bytes() {
Schema.Type type = Schema.Type.BYTES;
Schema simple = SchemaBuilder.builder().bytesType();
Schema expected = primitive(type, simple);
Schema built1 = SchemaBuilder.builder().bytesBuilder().prop("p", "v").endBytes();
assertEquals(expected, built1);
} |
public T divide(BigDecimal by) {
return create(value.divide(by, MAX_VALUE_SCALE, RoundingMode.DOWN));
} | @Test
void testValueScaleLimited() {
final Resource v1 = new TestResource(0.100000001);
assertTestResourceValueEquals(0.1, v1);
final Resource v2 = new TestResource(1.0).divide(3);
assertTestResourceValueEquals(0.33333333, v2);
} |
public static int jsonEscapedSizeInBytes(CharSequence v) {
boolean ascii = true;
int escapingOverhead = 0;
for (int i = 0, length = v.length(); i < length; i++) {
char c = v.charAt(i);
if (c == '\u2028' || c == '\u2029') {
escapingOverhead += 5;
} else if (c >= 0x80) {
asci... | @Test void testJsonEscapedSizeInBytes() {
assertThat(jsonEscapedSizeInBytes(new String(new char[] {0, 'a', 1})))
.isEqualTo(13);
assertThat(jsonEscapedSizeInBytes(new String(new char[] {'"', '\\', '\t', '\b'})))
.isEqualTo(8);
assertThat(jsonEscapedSizeInBytes(new String(new char[] {'\n', '\... |
public static double[] toDoubleArray(DoubleArrayList doubleArrayList) {
double[] doubleArrayListElements = doubleArrayList.elements();
return doubleArrayListElements.length == doubleArrayList.size() ? doubleArrayListElements
: doubleArrayList.toDoubleArray();
} | @Test
public void testToDoubleArray() {
// Test empty list
DoubleArrayList doubleArrayList = new DoubleArrayList();
double[] doubleArray = ArrayListUtils.toDoubleArray(doubleArrayList);
assertEquals(doubleArray.length, 0);
// Test list with one element
doubleArrayList.add(1.0);
doubleArra... |
public final boolean checkIfExecuted(String input) {
return this.validator.isExecuted(Optional.of(ByteString.copyFromUtf8(input)));
} | @Test
public void checkIfExecuted_withByteString_executesValidator() {
TestValidatorIsCalledValidator testValidator = new TestValidatorIsCalledValidator();
Payload payload = new Payload("my-payload", testValidator, PAYLOAD_ATTRIBUTES, CONFIG);
payload.checkIfExecuted(ByteString.copyFromUtf8("my-input"));... |
@VisibleForTesting
static List<String> collectColNamesFromSchema(Schema schema) {
List<String> result = new ArrayList<>();
Deque<String> visited = new LinkedList<>();
collectColNamesFromAvroSchema(schema, visited, result);
return result;
} | @Test
public void testCollectColumnNames() {
Schema simpleSchema = getSimpleSchema();
List<String> fieldNames = AvroInternalSchemaConverter.collectColNamesFromSchema(simpleSchema);
List<String> expectedOutput = getSimpleSchemaExpectedColumnNames();
assertEquals(expectedOutput.size(), fieldNames.size... |
@Override
public Graph<Entity> resolveForInstallation(Entity entity, Map<String, ValueReference> parameters, Map<EntityDescriptor, Entity> entities) {
if (entity instanceof EntityV1) {
return resolveForInstallationV1((EntityV1) entity, parameters, entities);
} else {
throw ne... | @Test
@MongoDBFixtures("EventDefinitionFacadeTest.json")
public void resolveForInstallation() {
EntityV1 eventEntityV1 = createTestEntity();
final NotificationEntity notificationEntity = NotificationEntity.builder()
.title(ValueReference.of("title"))
.description... |
@Override
protected synchronized void modifyConnectorOffsets(String connName, Map<Map<String, ?>, Map<String, ?>> offsets, Callback<Message> cb) {
if (!modifyConnectorOffsetsChecks(connName, cb)) {
return;
}
worker.modifyConnectorOffsets(connName, configState.connectorConfig(con... | @Test
public void testAlterConnectorOffsets() throws Exception {
initialize(false);
ArgumentCaptor<Callback<Message>> workerCallbackCapture = ArgumentCaptor.forClass(Callback.class);
Message msg = new Message("The offsets for this connector have been altered successfully");
doAnswer(... |
public long getBacklogBytes(String streamName, Instant countSince)
throws TransientKinesisException {
return getBacklogBytes(streamName, countSince, new Instant());
} | @Test
public void shouldNotCallCloudWatchWhenSpecifiedPeriodTooShort() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T10:00:02.000Z");
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(ba... |
@Override
public synchronized void write(int b) throws IOException {
mUfsOutStream.write(b);
mBytesWritten++;
} | @Test
public void writeOffset() throws IOException, AlluxioException {
int bytesToWrite = CHUNK_SIZE * 5 + CHUNK_SIZE / 2;
int offset = CHUNK_SIZE / 3;
AlluxioURI ufsPath = getUfsPath();
try (FileOutStream outStream = mFileSystem.createFile(ufsPath)) {
byte[] array = BufferUtils.getIncreasingByt... |
public String getName() {
return name;
} | @Test
public void testGetName() throws Exception {
assertNull( info.getName() );
info.setName( "name" );
assertEquals( "name", info.getName() );
} |
public static void boundsCheck(int capacity, int index, int length) {
if (capacity < 0 || index < 0 || length < 0 || (index > (capacity - length))) {
throw new IndexOutOfBoundsException(String.format("index=%d, length=%d, capacity=%d", index, length, capacity));
}
} | @Test(expected = IndexOutOfBoundsException.class)
public void boundsCheck_whenCapacitySmallerThanZero() {
ArrayUtils.boundsCheck(-1, 0, 0);
} |
@SuppressWarnings("unchecked")
public V replace(final int key, final V value)
{
final V val = (V)mapNullValue(value);
requireNonNull(val, "value cannot be null");
final int[] keys = this.keys;
final Object[] values = this.values;
@DoNotSub final int mask = values.length ... | @Test
void replaceThrowsNullPointerExceptionIfNewValueIsNull()
{
final NullPointerException exception =
assertThrowsExactly(NullPointerException.class, () -> intToObjectMap.replace(42, "abc", null));
assertEquals("value cannot be null", exception.getMessage());
} |
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if(!(other instanceof HollowMapSchema))
return false;
HollowMapSchema otherSchema = (HollowMapSchema)other;
if(!getName().equals(otherSchema.getName()))
return false;
... | @Test
public void testEquals() {
{
HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB");
HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeB");
Assert.assertEquals(s1, s2);
}
{
HollowMapSchema s1 = new HollowMapSche... |
public static StringBuilder appendWithBlankCheck(String str, String defaultValue, StringBuilder appender) {
if (isNotBlank(str)) {
appender.append(str);
} else {
appender.append(defaultValue);
}
return appender;
} | @Test
public void testAppendWithBlankCheck() {
Assert.assertEquals("bar", EagleEyeCoreUtils.appendWithBlankCheck(
null, "bar", new StringBuilder()).toString());
Assert.assertEquals("foo", EagleEyeCoreUtils.appendWithBlankCheck(
"foo", "bar", new StringBuilder()).toStr... |
public static void validate(final String cronEntry) throws MessageFormatException {
List<String> list = tokenize(cronEntry);
List<CronEntry> entries = buildCronEntries(list);
for (CronEntry e : entries) {
validate(e);
}
} | @Test
public void testValidate() {
try {
CronParser.validate("30 08 10 06 ? ");
CronParser.validate("30 08 ? 06 5 ");
CronParser.validate("30 08 ? 06 * ");
CronParser.validate("* * * * * ");
CronParser.validate("* * * * 1-6 ");
CronPars... |
public static <
K extends @Nullable Object,
InputT extends @Nullable Object,
AccumT extends @Nullable Object,
OutputT extends @Nullable Object>
MultiStepCombine<K, InputT, AccumT, OutputT> of(
CombineFn<InputT, AccumT, OutputT> combineFn, Coder<KV<K, OutputT>> out... | @Test
public void testMultiStepCombineTimestampCombiner() {
TimestampCombiner combiner = TimestampCombiner.LATEST;
PCollection<KV<String, Long>> combined =
pipeline
.apply(
Create.timestamped(
TimestampedValue.of(KV.of("foo", 4L), new Instant(1L)),
... |
public PointBuilder<T> latLong(LatLong latitudeAndLongitude) {
this.latitude = latitudeAndLongitude.latitude();
this.longitude = latitudeAndLongitude.longitude();
return this;
} | @Test
public void testLatLong_Double_Double_nullLong() {
assertThrows(
NullPointerException.class,
() -> Point.builder().latLong(1.23, null)
);
} |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testAppNameIsSetWhenUsingAs() {
TestPipelineOptions options = PipelineOptionsFactory.as(TestPipelineOptions.class);
assertEquals(
PipelineOptionsFactoryTest.class.getSimpleName(),
options.as(ApplicationNameOptions.class).getAppName());
} |
@Override
public Mono<UserDetails> updatePassword(UserDetails user, String newPassword) {
return userService.updatePassword(user.getUsername(), newPassword)
.map(u -> withNewPassword(user, newPassword));
} | @Test
void shouldReturnErrorWhenFailedToUpdatePassword() {
var fakeUser = createFakeUserDetails();
var exception = new RuntimeException("failed to update password");
when(userService.updatePassword("faker", "new-fake-password")).thenReturn(
Mono.error(exception)
);
... |
@Override
public boolean isInfinite() {
return this.equals(INFINITY)
|| (this.cpu == Double.POSITIVE_INFINITY)
|| (this.cpuRate == Double.POSITIVE_INFINITY);
} | @Test
public void testDefaultConstructorIsInfinite() {
BeamCostModel cost = BeamCostModel.FACTORY.makeCost(1, 1, 1);
Assert.assertTrue(cost.isInfinite());
} |
public void print(PrintStream out, String prefix)
{
print(out, prefix, data, data.length);
} | @Test
public void testPrint()
{
byte[] buf = new byte[10];
Arrays.fill(buf, (byte) 0xAA);
ZData data = new ZData(buf);
data.print(System.out, "ZData: ");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.