focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public StatementExecutorResponse execute(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext executionContext,
final KsqlSecurityContext securityContext
) {
final String commandRunnerWarningString = commandRunnerWarning.get();
if (!commandRunnerWarningString... | @Test
public void shouldNotAbortTransactionIfInitTransactionFails() {
// Given:
doThrow(TimeoutException.class).when(transactionalProducer).initTransactions();
// When:
assertThrows(
KsqlServerException.class,
() -> distributor.execute(CONFIGURED_STATEMENT, executionContext, securityC... |
@Override
public void subscribe(Collection<String> topics) {
subscribeInternal(topics, Optional.empty());
} | @Test
public void testSubscribeToNullTopicCollection() {
consumer = newConsumer();
assertThrows(IllegalArgumentException.class, () -> consumer.subscribe((List<String>) null));
} |
public static double distance(int[] a, int[] b) {
return sqrt(squaredDistance(a, b));
} | @Test
public void testDistance_doubleArr_doubleArr() {
System.out.println("distance");
double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300};
assertEquals(2.422302, MathEx.distance(x, y), 1E-6... |
public void removeTemplateNamed(CaseInsensitiveString name) {
PipelineTemplateConfig toBeRemoved = null;
for (PipelineTemplateConfig templateConfig : this) {
if (templateConfig.matches(name)) {
toBeRemoved = templateConfig;
}
}
this.remove(toBeRemo... | @Test
public void shouldRemoveATemplateByName() {
PipelineTemplateConfig template2 = template("template2");
TemplatesConfig templates = new TemplatesConfig(template("template1"), template2);
templates.removeTemplateNamed(new CaseInsensitiveString("template1"));
assertThat(templates... |
public static <T> T copy(Object origin, Class<T> destCls) {
T dest = ReflectKit.newInstance(destCls);
copy(origin, dest);
return dest;
} | @Test
public void testCopy() {
Person source = new Person("jack", "nu", 22);
Person dest = new Person();
BeanKit.copy(source, dest);
Assert.assertEquals(source.toString(), dest.toString());
Person dest2 = BeanKit.copy(source, Person.class);
Assert.assertEquals(sour... |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvWithSingleQuoteAndCharacter() {
CharSequence value = "\"f";
CharSequence expected = "\"\"\"f\"";
escapeCsv(value, expected);
} |
@Override
public Class<?> getActionReturnType()
{
if (_resourceMethod.getMethodType() == ResourceMethod.ACTION)
{
return _resourceMethod.getActionReturnType();
}
return null;
} | @Test
public void testGetActionReturnType()
{
when(resourceMethod.getMethodType()).thenReturn(ResourceMethod.ACTION);
Mockito.doReturn(String.class).when(resourceMethod).getActionReturnType();
FilterRequestContext filterContext = new FilterRequestContextInternalImpl(context, resourceMethod, null);
A... |
@Override
public void init(DatabaseMetaData metaData) {
LoggerFactory.getLogger(getClass()).warn("H2 database should be used for evaluation purpose only.");
} | @Test
public void init_logs_warning() {
underTest.init(mock(DatabaseMetaData.class));
assertThat(logs.logs(Level.WARN)).contains("H2 database should be used for evaluation purpose only.");
} |
@Override
public Job save(Job jobToSave) {
try (final Connection conn = dataSource.getConnection(); final Transaction transaction = new Transaction(conn)) {
final Job savedJob = jobTable(conn).save(jobToSave);
transaction.commit();
notifyJobStatsOnChangeListeners();
... | @Test
void saveJob() throws SQLException {
when(preparedStatement.executeUpdate()).thenReturn(1);
assertThatCode(() -> jobStorageProvider.save(anEnqueuedJob().build())).doesNotThrowAnyException();
} |
@VisibleForTesting
void validateExperienceOutRange(List<MemberLevelDO> list, Long id, Integer level, Integer experience) {
for (MemberLevelDO levelDO : list) {
if (levelDO.getId().equals(id)) {
continue;
}
if (levelDO.getLevel() < level) {
... | @Test
public void testUpdateLevel_experienceOutRange() {
// 准备参数
int level = 10;
int experience = 10;
Long id = randomLongId();
String name = randomString();
// mock 数据
memberlevelMapper.insert(randomLevelDO(o -> {
o.setLevel(level);
o... |
@Override
public void processElement(final StreamRecord<T> element) throws Exception {
final T event = element.getValue();
final long previousTimestamp =
element.hasTimestamp() ? element.getTimestamp() : Long.MIN_VALUE;
final long newTimestamp = timestampAssigner.extractTimes... | @Test
void testNegativeTimestamps() throws Exception {
OneInputStreamOperatorTestHarness<Long, Long> testHarness =
createTestHarness(
WatermarkStrategy.forGenerator((ctx) -> new NeverWatermarkGenerator())
.withTimestampAssigner((ctx) -... |
public DirectoryEntry lookUp(
File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
DirectoryEntry result = lookUp(workingDirectory, path, options, 0);
if (result == null) {
// an intermediate file in the path... | @Test
public void testLookup_absolute_intermediateSymlink_parentExists() throws IOException {
assertParentExists(lookup("/work/four/five/baz"), "foo");
assertParentExists(lookup("/work/four/six/baz"), "one");
} |
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
} | @Test(expected = EncodingException.class)
public void testParsingNull() {
MediaType.fromString(null);
} |
@Deprecated(since = "5.5", forRemoval = true)
public RestApiConfig getRestApiConfig() {
return restApiConfig;
} | @Test
public void testRestApiConfig_isNotNullByDefault() {
assertNotNull(networkConfig.getRestApiConfig());
} |
@Override
public void validTenant(Long id) {
TenantDO tenant = getTenant(id);
if (tenant == null) {
throw exception(TENANT_NOT_EXISTS);
}
if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
throw exception(TENANT_DISABLE, tenant.getName());
... | @Test
public void testValidTenant_success() {
// mock 数据
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus())
.setExpireTime(LocalDateTime.now().plusDays(1)));
tenantMapper.insert(tenant);
// 调用,并断言业务异常
... |
static String determinePackageName(Path baseDir, String basePackageName, Path classFile) {
String subPackageName = determineSubpackageName(baseDir, classFile);
return of(basePackageName, subPackageName)
.filter(value -> !value.isEmpty()) // default package
.collect(joinin... | @Test
void determinePackageNameFromComPackage() {
Path baseDir = Paths.get("path", "to", "com");
String basePackageName = "com";
Path classFile = Paths.get("path", "to", "com", "example", "app", "App.class");
String packageName = ClasspathSupport.determinePackageName(baseDir, basePac... |
public DockerInspectCommand getContainerStatus() {
super.addCommandArguments("format", STATUS_TEMPLATE);
this.commandArguments = String.format("--format=%s", STATUS_TEMPLATE);
return this;
} | @Test
public void testGetContainerStatus() throws Exception {
dockerInspectCommand.getContainerStatus();
assertEquals("inspect", StringUtils.join(",",
dockerInspectCommand.getDockerCommandWithArguments()
.get("docker-command")));
assertEquals("{{.State.Status}}", StringUtils.join(",",
... |
public int getNumberOfErrors() {
return errors.size();
} | @Test
void testErrorsEmpty() {
assertEquals(0, new JsonValidationException(null, null, new Exception()).getNumberOfErrors());
} |
public abstract byte[] encode(MutableSpan input); | @Test void specialCharsInJson_JSON_V2() {
assertThat(new String(encoder.encode(utf8Span), UTF_8))
.isEqualTo(
"{\"traceId\":\"0000000000000001\",\"id\":\"0000000000000001\",\"name\":\"\\\"\\\\\\t\\b\\n\\r\\f\",\"annotations\":[{\"timestamp\":1,\"value\":\"\\u2028 and \\u2029\"}],\"tags\":{\"\\\"... |
@Udf(description = "Returns the hyperbolic sine of an INT value")
public Double sinh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic sine of."
) final Integer value
) {
return sinh(value == null ? null : value.dou... | @Test
public void shouldHandleNull() {
assertThat(udf.sinh((Integer) null), is(nullValue()));
assertThat(udf.sinh((Long) null), is(nullValue()));
assertThat(udf.sinh((Double) null), is(nullValue()));
} |
static final String generateForFragment(RuleBuilderStep step, Configuration configuration) {
final String fragmentName = step.function();
try {
Template template = configuration.getTemplate(fragmentName);
StringWriter writer = new StringWriter();
Map<String, Object> f... | @Test
public void generateForFragmentThrowsException_WhenTemplateNotFound() {
RuleBuilderStep step = mock(RuleBuilderStep.class);
when(step.function()).thenReturn("unknown");
assertThatThrownBy(() -> ParserUtil.generateForFragment(step, configuration))
.isInstanceOf(IllegalAr... |
public boolean fileIsInAllowedPath(Path path) {
if (allowedPaths.isEmpty()) {
return true;
}
final Path realFilePath = resolveRealPath(path);
if (realFilePath == null) {
return false;
}
for (Path allowedPath : allowedPaths) {
final Pat... | @Test
public void verifyToRealPathCalled() throws IOException {
final Path permittedPath = mock(Path.class);
final Path filePath = mock(Path.class);
pathChecker = new AllowedAuxiliaryPathChecker(new TreeSet<>(Collections.singleton(permittedPath)));
when(filePath.toRealPath()).thenRe... |
@Override
@SuppressWarnings("unchecked")
public void forward(ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
if (lambdaContainerHandler == null) {
throw new IllegalStateException("Null container handler in dispatcher");
... | @Test
void forwardRequest_committedResponse_throwsIllegalStateException() throws InvalidRequestEventException {
AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/hello", "GET").build();
HttpServletRequest servletRequest = requestReader.readRequest(proxyRequest, null, new MockLambdaContext(... |
public boolean matchesBeacon(Beacon beacon) {
// All identifiers must match, or the corresponding region identifier must be null.
for (int i = mIdentifiers.size(); --i >= 0; ) {
final Identifier identifier = mIdentifiers.get(i);
Identifier beaconIdentifier = null;
if ... | @Test
public void testBeaconDoesNotMatchRegionWithDiffrentBluetoothMac() {
Beacon beacon = new AltBeacon.Builder().setId1("1").setId2("2").setId3("3").setRssi(4)
.setBeaconTypeCode(5).setTxPower(6).setBluetoothAddress("01:02:03:04:05:06").build();
Region region = new Region("myRegion... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testJsonConversionOfAJsonConvertedType() throws Exception {
SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class);
options.setString("TestValue");
options.setInteger(5);
// It is important here that our first serialization goes to our most basic
// type so that we ha... |
@Override
protected JobExceptionsInfoWithHistory handleRequest(
HandlerRequest<EmptyRequestBody> request, ExecutionGraphInfo executionGraph) {
final List<Integer> exceptionToReportMaxSizes =
request.getQueryParameter(UpperLimitExceptionParameter.class);
final int exceptio... | @Test
void testOnlyExceptionHistory()
throws HandlerRequestException, ExecutionException, InterruptedException {
final RuntimeException rootThrowable = new RuntimeException("exception #0");
final long rootTimestamp = System.currentTimeMillis();
final RootExceptionHistoryEntry roo... |
@Override
protected void doStart() throws Exception {
super.doStart();
LOG.debug("Creating connection to Azure ServiceBus");
client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(),
this::processMessage, this::processError);
... | @Test
void synchronizationDoesNotCompleteMessageWhenReceiveModeIsReceiveAndDelete() throws Exception {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) {
when(configuration.getServiceBusReceiveMode()).thenReturn(ServiceBusReceiveMode.RECEIVE_AND_DELETE);
... |
public StorageID append(String name, String value) {
if (StringUtil.isBlank(name)) {
throw new IllegalArgumentException("The name of storage ID should not be null or empty.");
}
if (sealed) {
throw new IllegalStateException("The storage ID is sealed. Can't append a new fr... | @Test
public void testEqual() {
StorageID id = new StorageID();
id.append("time_bucket", 202212141438L) //2022-12-14 14:38
.append("entity_id", "encoded-service-name");
StorageID id2 = new StorageID();
id2.append("time_bucket", 202212141438L) //2022-12-14 14:38
... |
String encode(JwtSession jwtSession) {
checkIsStarted();
return Jwts.builder()
.claims(jwtSession.getProperties())
.claim(LAST_REFRESH_TIME_PARAM, system2.now())
.id(jwtSession.getSessionTokenUuid())
.subject(jwtSession.getUserLogin())
.issuedAt(new Date(system2.now()))
.expi... | @Test
public void encode_fail_when_not_started() {
JwtSession jwtSession = new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 10).getTime());
assertThatThrownBy(() -> underTest.encode(jwtSession))
.isInstanceOf(NullPointerException.class)
.hasMessage("org.sonar.server.authentica... |
@Override
public Optional<Integer> extractIndexNumber(final String indexName) {
final int beginIndex = indexPrefixLength(indexName);
if (indexName.length() < beginIndex) {
return Optional.empty();
}
final String suffix = indexName.substring(beginIndex);
try {
... | @Test
public void testExtractIndexNumberWithMalformedFormatReturnsEmptyOptional() {
assertThat(mongoIndexSet.extractIndexNumber("graylog2_hunderttausend")).isEmpty();
} |
public long getNumEntriesScannedPostFilter() {
return _brokerResponse.has(NUM_ENTRIES_SCANNED_POST_FILTER) ? _brokerResponse.get(NUM_ENTRIES_SCANNED_POST_FILTER)
.asLong() : -1L;
} | @Test
public void testGetNumEntriesScannedPostFilter() {
// Run the test
final long result = _executionStatsUnderTest.getNumEntriesScannedPostFilter();
// Verify the results
assertEquals(10L, result);
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testReadCommittedWithCompactedTopic() {
buildFetcher(OffsetResetStrategy.EARLIEST, new StringDeserializer(),
new StringDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long pid1 = 1L;
... |
public static <InputT> KeyByBuilder<InputT> of(PCollection<InputT> input) {
return named(null).of(input);
} | @Test
public void testBuild_ImplicitName() {
final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings());
final PCollection<KV<String, Long>> reduced =
ReduceByKey.of(dataset).keyBy(s -> s).valueBy(s -> 1L).combineBy(Sums.ofLongs()).output();
final ReduceByKey reduce... |
public static RuntimeOpts mergeRuntimeOpts(RuntimeOpts oriOpts, RuntimeOpts newOpts) {
RuntimeOpts mergedOpts = oriOpts.partialDeepClone();
if (mergedOpts.getExtraLabels() == null) {
mergedOpts.setExtraLabels(new HashMap<>());
}
if (mergedOpts.getExtraAnnotations() == null) {... | @Test
public void TestMergeRuntimeOpts() {
Map<String, Object> configs = new Gson().fromJson(KubernetesRuntimeTest.createRuntimeCustomizerConfig(), HashMap.class);
BasicKubernetesManifestCustomizer customizer = new BasicKubernetesManifestCustomizer();
customizer.initialize(configs);
... |
public static void verifyGroupId(final String groupId) {
if (StringUtils.isBlank(groupId)) {
throw new IllegalArgumentException("Blank groupId");
}
if (!GROUP_ID_PATTER.matcher(groupId).matches()) {
throw new IllegalArgumentException(
"Invalid group id, it... | @Test(expected = IllegalArgumentException.class)
public void tetsVerifyGroupId3() {
Utils.verifyGroupId("1abc");
} |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testPartitionedIsNotNull() throws Exception {
createPartitionedTable(spark, tableName, "truncate(4, data)");
SparkScanBuilder builder = scanBuilder();
TruncateFunction.TruncateString function = new TruncateFunction.TruncateString();
UserDefinedScalarFunc udf = toUDF(functio... |
public static NamingHttpClientManager getInstance() {
return NamingHttpClientManagerInstance.INSTANCE;
} | @Test
void testGetInstance() {
assertNotNull(NamingHttpClientManager.getInstance());
} |
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
} | @Test
public void testTime() {
RedisClusterNode master = getFirstMaster();
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
} |
static void checkFormat(final String originalFilename) {
final List<String> fileNameSplit = Splitter.on(".").splitToList(originalFilename);
if (fileNameSplit.size() <= 1) {
throw new BadRequestException("The file format is invalid.");
}
for (String s : fileNameSplit) {
if (StringUtils.isEmp... | @Test(expected = BadRequestException.class)
public void checkFormatWithException0() {
ConfigFileUtils.checkFormat("1234+defaultes");
} |
@Override
public byte[] encode(ILoggingEvent event) {
var baos = new ByteArrayOutputStream();
try (var generator = jsonFactory.createGenerator(baos)) {
generator.writeStartObject();
// https://cloud.google.com/logging/docs/structured-logging#structured_logging_special_fields
// https://gith... | @Test
void encode_kv() {
var e = mockEvent();
when(e.getLevel()).thenReturn(Level.DEBUG);
when(e.getFormattedMessage()).thenReturn("oha, sup?");
when(e.getKeyValuePairs())
.thenReturn(
List.of(
new KeyValuePair("req", Map.of("url", "https://example.com", "method",... |
void precheckMaxResultLimitOnLocalPartitions(String mapName) {
// check if feature is enabled
if (!isPreCheckEnabled) {
return;
}
// limit number of local partitions to check to keep runtime constant
PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa... | @Test
public void testLocalPreCheckEnabledWitTwoPartitionsBelowLimit() {
int[] partitionsSizes = {849, 849};
populatePartitions(partitionsSizes);
initMocksWithConfiguration(200000, 2);
limiter.precheckMaxResultLimitOnLocalPartitions(ANY_MAP_NAME);
} |
public V get(K key) {
final WeakReference<V> currentWeakRef = lookup(key);
// resolve it, after which if not null, we have a strong reference
V strongVal = resolve(currentWeakRef);
if (strongVal != null) {
// all good.
return strongVal;
}
// here, either currentWeakRef was null, or... | @Test
public void testFactoryReturningNull() throws Throwable {
referenceMap = new WeakReferenceMap<>(
(k) -> null,
null);
intercept(NullPointerException.class, () ->
referenceMap.get(0));
} |
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存
public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) {
// 1. 无数据权限
if (CollUtil.isEmpty(rules)) {
return Collections.emptyList();
}
// 2. 未配置,则默认开启
D... | @Test
public void testGetDataPermissionRule_03() {
// 准备参数
String mappedStatementId = randomString();
// mock 方法
DataPermissionContextHolder.add(AnnotationUtils.findAnnotation(TestClass03.class, DataPermission.class));
// 调用
List<DataPermissionRule> result = dataPerm... |
public void notify(PluginJarChangeListener listener, Collection<BundleOrPluginFileDetails> knowPluginFiles, Collection<BundleOrPluginFileDetails> currentPluginFiles) {
List<BundleOrPluginFileDetails> oldPlugins = new ArrayList<>(knowPluginFiles);
subtract(oldPlugins, currentPluginFiles).forEach(listene... | @Test
void shouldNotifyWhenPluginIsUpdated() {
final PluginJarChangeListener listener = mock(PluginJarChangeListener.class);
BundleOrPluginFileDetails pluginOne = mock(BundleOrPluginFileDetails.class);
BundleOrPluginFileDetails pluginTwo = mock(BundleOrPluginFileDetails.class);
Bundl... |
@Override
public ShenyuContext decorator(final ShenyuContext shenyuContext, final MetaData metaData) {
shenyuContext.setModule(metaData.getAppName());
shenyuContext.setMethod(metaData.getServiceName());
shenyuContext.setContextPath(metaData.getContextPath());
shenyuContext.setRpcType... | @Test
public void testDecorator() {
metaData.setAppName("app");
metaData.setServiceName("service");
metaData.setContextPath("localhost");
motanShenyuContextDecorator.decorator(shenyuContext, metaData);
Assertions.assertEquals(shenyuContext.getModule(), "app");
} |
public static Split split(String regex) {
return split(Pattern.compile(regex), false);
} | @Test
@Category(NeedsRunner.class)
public void testSplitsWithEmpty() {
PCollection<String> output =
p.apply(Create.of("The quick brown fox jumps over the lazy dog"))
.apply(Regex.split("\\s", true));
PAssert.that(output)
.containsInAnyOrder(
"The", "", "quick"... |
public Record convert(final AbstractWALEvent event) {
if (filter(event)) {
return createPlaceholderRecord(event);
}
if (!(event instanceof AbstractRowEvent)) {
return createPlaceholderRecord(event);
}
PipelineTableMetaData tableMetaData = getPipelineTableM... | @Test
void assertConvertBeginTXEvent() {
BeginTXEvent beginTXEvent = new BeginTXEvent(100L, null);
beginTXEvent.setLogSequenceNumber(new PostgreSQLLogSequenceNumber(logSequenceNumber));
Record record = walEventConverter.convert(beginTXEvent);
assertInstanceOf(PlaceholderRecord.class,... |
public static void main(final String[] args) {
// VirtualDB (instead of MongoDB) was used in running the JUnit tests
// and the App class to avoid Maven compilation errors. Set flag to
// true to run the tests with MongoDB (provided that MongoDB is
// installed and socket connection is open).
boolea... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static String version() {
ensureLoaded();
return version;
} | @Test
public void testVersion() {
assertThat(IcebergBuild.version()).as("Should not use unknown version").isNotEqualTo("unknown");
} |
@Override
public void run(DiagnosticsLogWriter writer) {
metricCollector.writer = writer;
// we set the time explicitly so that for this particular rendering of the probes, all metrics have exactly
// the same timestamp
metricCollector.timeMillis = System.currentTimeMillis();
... | @Test
public void testRunWithProblematicProbe() {
metricsRegistry.registerStaticProbe(this, "broken", MANDATORY, (LongProbeFunction) source -> {
throw new RuntimeException("error");
});
plugin.run(logWriter);
assertContains("[metric=broken]=java.lang.RuntimeException:err... |
protected SuppressionRules rules() {
return rules;
} | @Test
public void updateDeviceTypeRule() {
Device.Type deviceType1 = Device.Type.ROADM;
Device.Type deviceType2 = Device.Type.SWITCH;
Set<Device.Type> deviceTypes = new HashSet<>();
deviceTypes.add(deviceType1);
cfg.deviceTypes(deviceTypes);
configEvent(NetworkConfi... |
public static <T, PartitionColumnT> ReadWithPartitions<T, PartitionColumnT> readWithPartitions(
TypeDescriptor<PartitionColumnT> partitioningColumnType) {
return new AutoValue_JdbcIO_ReadWithPartitions.Builder<T, PartitionColumnT>()
.setPartitionColumnType(partitioningColumnType)
.setNumPartit... | @Test
public void testLowerBoundIsMoreThanUpperBound() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(
"The lower bound of partitioning column is larger or equal than the upper bound");
pipeline.apply(
JdbcIO.<TestRow>readWithPartitions()
.withDataSourceC... |
public Searcher searcher() {
return new Searcher();
} | @Test
void requireThatPredicateIndexCanSearch() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no', 'se'] and gender in ['male']"));
builder.indexDocument(0x3fffffe, Predicate.fromString("country in ['no'] and gend... |
public void removeTimer(String eventName) {
synchronized (mTrackTimer) {
mTrackTimer.remove(eventName);
}
} | @Test
public void removeTimer() {
mInstance.addEventTimer("EventTimer", new EventTimer(TimeUnit.SECONDS, 10000L));
mInstance.removeTimer("EventTimer");
Assert.assertNull(mInstance.getEventTimer("EventTimer"));
} |
public static void reset(Buffer buffer) {
buffer.reset();
} | @Test
public void testReset() {
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.putInt(1);
BufferUtils.mark(byteBuffer);
Assertions.assertDoesNotThrow(() -> BufferUtils.reset(byteBuffer));
} |
@Override
public boolean supportsTransactions() {
return false;
} | @Test
void assertSupportsTransactions() {
assertFalse(metaData.supportsTransactions());
} |
public static Read<String> readStrings() {
return Read.newBuilder(
(PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8))
.setCoder(StringUtf8Coder.of())
.build();
} | @Test
public void testTopicValidationBadCharacter() throws Exception {
thrown.expect(IllegalArgumentException.class);
PubsubIO.readStrings().fromTopic("projects/my-project/topics/abc-*-abc");
} |
public static void mergeOutputDataParams(
Map<String, Parameter> allParams, Map<String, Parameter> params) {
params.forEach(
(name, param) -> {
if (!allParams.containsKey(name)) {
throw new MaestroValidationException(
"Invalid output parameter [%s], not defined in... | @Test
public void testMergeOutputDataParamsOtherParams() throws JsonProcessingException {
Map<String, Parameter> allParams =
parseParamMap(
"{\"long_array_param\":{\"evaluated_result\":[1,2,3],\"evaluated_time\":1626893775979,\"type\":\"LONG_ARRAY\",\"value\":[1,2,3]},\"long_param\":{\"evaluat... |
public LeaderAndIsr newEpoch() {
return newLeaderAndIsrWithBrokerEpoch(leader, isrWithBrokerEpoch);
} | @Test
public void testNewEpoch() {
LeaderAndIsr leaderAndIsr = new LeaderAndIsr(3, Arrays.asList(1, 2, 3));
assertEquals(0, leaderAndIsr.leaderEpoch());
LeaderAndIsr leaderWithNewEpoch = leaderAndIsr.newEpoch();
assertEquals(1, leaderWithNewEpoch.leaderEpoch());
} |
String substituteParametersInSqlString(String sql, SqlParameterSource paramSource) {
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
List<SqlParameter> declaredParams = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
if (declaredParams.isEmpty()) {
... | @Test
public void substituteParametersInSqlString_BooleanType() {
String sql = "Select * from Table Where check = :check AND mark = :mark";
String sqlToUse = "Select * from Table Where check = true AND mark = false";
ctx.addBooleanParameter("check", true);
ctx.addBooleanParameter("... |
@Override
public Response toResponse(Throwable exception) {
debugLog(exception);
if (exception instanceof WebApplicationException w) {
var res = w.getResponse();
if (res.getStatus() >= 500) {
log(w);
}
return res;
}
if (exception instanceof AuthenticationException) {... | @Test
void toResponse_withBody_seeOthers() {
// when
var res =
mapper.toResponse(
new ValidationException(
new Message("error.unsupportedScope", "https://example.com/see/other"),
URI.create("https://example.com/see/other")));
// then
assertEquals(30... |
public static MetricsReporter combine(MetricsReporter first, MetricsReporter second) {
if (null == first) {
return second;
} else if (null == second || first == second) {
return first;
}
Set<MetricsReporter> reporters = Sets.newIdentityHashSet();
if (first instanceof CompositeMetricsRe... | @Test
public void reportWithMultipleMetricsReportersOneFails() {
AtomicInteger counter = new AtomicInteger();
MetricsReporter combined =
MetricsReporters.combine(
MetricsReporters.combine(
report -> counter.incrementAndGet(),
report -> {
th... |
@Transactional(readOnly = true)
public AttendeeScheduleResponse findMySchedule(String uuid, long attendeeId) {
Meeting meeting = meetingRepository.findByUuid(uuid)
.orElseThrow(() -> new MomoException(MeetingErrorCode.NOT_FOUND_MEETING));
Attendee attendee = attendeeRepository.findB... | @DisplayName("UUID와 참가자 ID로 자신의 스케줄을 조회한다.")
@Test
void findMySchedule() {
createAttendeeSchedule(attendee);
AttendeeScheduleResponse result = scheduleService.findMySchedule(meeting.getUuid(), attendee.getId());
DateTimesResponse firstTimeResponse = result.schedules().get(0);
a... |
@SuppressWarnings("unchecked")
public static int compare(Comparable lhs, Comparable rhs) {
assert lhs != null;
assert rhs != null;
if (lhs.getClass() == rhs.getClass()) {
return lhs.compareTo(rhs);
}
if (lhs instanceof Number && rhs instanceof Number) {
... | @SuppressWarnings("ConstantConditions")
@Test(expected = Throwable.class)
public void testNullLhsInCompareThrows() {
compare(null, 1);
} |
public static TableElements parse(final String schema, final TypeRegistry typeRegistry) {
return new SchemaParser(typeRegistry).parse(schema);
} | @Test
public void shouldParseValidSchemaWithSingleHeaderKeyField() {
// Given:
final String schema = "K STRING HEADER('k1'), bar INT";
// When:
final TableElements elements = parser.parse(schema);
// Then:
assertThat(elements, contains(
new TableElement(ColumnName.of("K"), new Type(S... |
@Override
public long delete(String path) {
return get(deleteAsync(path));
} | @Test
public void testDelete() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
assertThat(al.delete()).isFalse();
TestType t = new TestType();
t.setName("name1");
al.set(t);
assertThat(al.delete()).isTrue();
} |
@Override
public Reader getCharacterStream(final int columnIndex) throws SQLException {
// TODO To be supported: encrypt, mask, and so on
return mergeResultSet.getCharacterStream(columnIndex);
} | @Test
void assertGetCharacterStreamWithColumnLabel() throws SQLException {
Reader reader = mock(Reader.class);
when(mergeResultSet.getCharacterStream(1)).thenReturn(reader);
assertThat(shardingSphereResultSet.getCharacterStream("label"), is(reader));
} |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseEmptyString() {
SchemaAndValue schemaAndValue = Values.parseString("");
assertEquals(Schema.STRING_SCHEMA, schemaAndValue.schema());
assertEquals("", schemaAndValue.value());
} |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(2.0), numOf(1.5)));
assertFalse(criterion.betterThan(numOf(1.5), numOf(2.0)));
} |
public static boolean isLocalOutputDir(String outputDirURIScheme) {
return outputDirURIScheme == null || outputDirURIScheme.startsWith("file");
} | @Test
public void testIsLocalOutputDir() {
assertTrue(MinionTaskUtils.isLocalOutputDir("file"));
assertFalse(MinionTaskUtils.isLocalOutputDir("hdfs"));
} |
public static List<String> splitStatementsAcrossBlocks(CharSequence string) {
List<String> statements = codeAwareSplitOnChar(string, false, true, ';', '\n', '{', '}');
return statements.stream()
.filter(stmt -> !(stmt.isEmpty()))
.filter(stmt -> !(stmt.startsWith("//")))
... | @Test
public void splitStatementsAcrossBlocksCommentedIfMissingEndingBrace() {
String text = "// if (true) {\n" +
" $fact.value1 = 2;\n" +
" drools.update($fact);\n" +
"//";
List<String> statements = splitStatementsAcrossBlocks(text... |
@Override
public void deletePost(Long id) {
// 校验是否存在
validatePostExists(id);
// 删除部门
postMapper.deleteById(id);
} | @Test
public void testDeletePost_success() {
// mock 数据
PostDO postDO = randomPostDO();
postMapper.insert(postDO);
// 准备参数
Long id = postDO.getId();
// 调用
postService.deletePost(id);
assertNull(postMapper.selectById(id));
} |
@Override
public void addProduct(Product product, Customer customer) throws SQLException {
var sql = "insert into PURCHASES (product_name, customer_name) values (?,?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement... | @Test
void shouldAddProductToPurchases() throws SQLException {
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource);
customerDao.addProduct(product, customer);
try (var connection = dataSource.getConnection();
var stat... |
@Override
public AppResponse process(Flow flow, AppRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
var response = new WidPollResponse(attestEnabled && Arrays.asList(allowedActions).contains(appSession.getAction()));
setValid(false);
switch (appSessi... | @Test
void processAttestEnabled() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
setupWidPolling(true);
WidPollResponse appResponse = (WidPollResponse) widPolling.process(mockedFlow, mockedAbstractAppRequest);
assertTrue(appResponse.getAttestApp());
assertE... |
public Span nextSpan(ConsumerRecord<?, ?> record) {
// Even though the type is ConsumerRecord, this is not a (remote) consumer span. Only "poll"
// events create consumer spans. Since this is a processor span, we use the normal sampler.
TraceContextOrSamplingFlags extracted =
extractAndClearTraceIdHea... | @Test void nextSpan_should_not_clear_other_headers() {
consumerRecord.headers().add("foo", new byte[0]);
kafkaTracing.nextSpan(consumerRecord);
assertThat(consumerRecord.headers().headers("foo")).isNotEmpty();
} |
@Override
public void write(ConnectionLogEntry record, OutputStream outputStream) throws IOException {
try (JsonGenerator generator = createJsonGenerator(outputStream)) {
generator.writeStartObject();
generator.writeStringField("id", record.id());
generator.writeStringFie... | @Test
void test_serialization() throws IOException {
var id = UUID.randomUUID();
var instant = Instant.parse("2021-01-13T12:12:12Z");
ConnectionLogEntry entry = ConnectionLogEntry.builder(id, instant)
.withPeerPort(1234)
.withSslHandshakeFailure(new Connectio... |
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (JoinRowsMeta) smi;
data = (JoinRowsData) sdi;
// Remove the temporary files...
if ( data.file != null ) {
for ( int i = 1; i < data.file.length; i++ ) {
if ( data.file[i] != null ) {
data.file[i].delet... | @Test
public void disposeDataFiles() throws Exception {
File mockFile1 = mock( File.class );
File mockFile2 = mock( File.class );
data.file = new File[] {null, mockFile1, mockFile2};
getJoinRows().dispose( meta, data );
verify( mockFile1, times( 1 ) ).delete();
verify( mockFile2, times( 1 ) ).... |
public static String beforeLast(String text, String before) {
if (!text.contains(before)) {
return null;
}
return text.substring(0, text.lastIndexOf(before));
} | @Test
public void testBeforeLast() {
assertEquals("Hello ", SshShellOutputStringHelper.beforeLast("Hello World", "World"));
assertEquals("Hello World ", SshShellOutputStringHelper.beforeLast("Hello World World", "World"));
assertEquals("Hello ", SshShellOutputStringHelper.beforeLast("Hello W... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
try {
callback.delete(file);
// Delete the file or folder at a given path. If... | @Test
public void testDeleteDirectory() throws Exception {
final Path folder = new DropboxDirectoryFeature(session).mkdir(
new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.volume, Path.Type.directory)), new TransferSt... |
@Override
public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? ";
return databaseOperate.queryOne(sql, new Object[] {username}, USER_ROW_MAPPER);
} | @Test
void testFindUserByUsername() {
User user = embeddedUserPersistService.findUserByUsername("username");
assertNull(user);
} |
DecodedJWT verifyJWT(PublicKey publicKey,
String publicKeyAlg,
DecodedJWT jwt) throws AuthenticationException {
if (publicKeyAlg == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new... | @Test
public void testThatUnsupportedAlgsThrowExceptions() {
Set<SignatureAlgorithm> unsupportedAlgs = new HashSet<>(Set.of(SignatureAlgorithm.values()));
Arrays.stream(supportedAlgorithms()).map(o -> (SignatureAlgorithm) o[0]).toList()
.forEach(unsupportedAlgs::remove);
unsu... |
@Override
public int run(String[] args) throws Exception {
Options opts = new Options();
opts.addOption("lnl", LIST_LABELS_CMD, false,
"List cluster node-label collection");
opts.addOption("lna", LIST_CLUSTER_ATTRIBUTES, false,
"List cluster node-attribute collection");
opts.addOp... | @Test
public void testHelp() throws Exception {
ClusterCLI cli = createAndGetClusterCLI();
int rc =
cli.run(new String[] { "cluster", "--help" });
assertEquals(0, rc);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
pw.println("us... |
private Function<KsqlConfig, Kudf> getUdfFactory(
final Method method,
final UdfDescription udfDescriptionAnnotation,
final String functionName,
final FunctionInvoker invoker,
final String sensorName
) {
return ksqlConfig -> {
final Object actualUdf = FunctionLoaderUtils.instan... | @Test
public void shouldCollectMetricsWhenMetricCollectionEnabled() {
// Given:
final UdfFactory substring = FUNC_REG_WITH_METRICS.getUdfFactory(FunctionName.of("substring"));
final KsqlScalarFunction function = substring
.getFunction(Arrays.asList(SqlArgument.of(SqlTypes.STRING), SqlArgument.of(S... |
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
RequestContext requestContext = RequestContextHolder.getContext();
try {
requestContext.getBasicContext().setRequestP... | @Test
public void testGetAppNameWithFallback() throws Exception {
when(servletRequest.getHeader(HttpHeaderConsts.APP_FILED)).thenReturn("");
MockNextFilter nextFilter = new MockNextFilter("unknown", "GBK");
filter.doFilter(servletRequest, servletResponse, new MockFilterChain(servlet, nextFil... |
@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 shouldNotAllowNullNamedOnFlatTransformValuesWithFlatValueWithKeySupplier() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues(
flatValueTransfor... |
@Override
public Ring<T> createRing(Map<T, Integer> pointsMap) {
return _ringFactory.createRing(pointsMap);
} | @Test(groups = { "small", "back-end" })
public void testFactoryWithMultiProbeAndHashMethod() {
RingFactory<String> factory = new DelegatingRingFactory<>(configBuilder("multiProbe", "uriRegex"));
Ring<String> ring = factory.createRing(buildPointsMap(10));
assertTrue(ring instanceof MPConsistentHashRing);
... |
public static <T> PCollections<T> pCollections() {
return new PCollections<>();
} | @Test
@Category(ValidatesRunner.class)
public void testFlattenWithDifferentInputAndOutputCoders2() {
// This test exists to prevent a regression in Dataflow. It tests a
// GroupByKey followed by a Flatten with an SDK-specific output coder.
PCollection<KV<String, Iterable<String>>> flattenInput =
... |
@Override
public void onText(Keyboard.Key key, CharSequence text) {
mKeyboardActionListener.onText(key, text);
if (TextUtils.isEmpty(key.label) || TextUtils.isEmpty(text)) return;
String name = String.valueOf(key.label);
String value = String.valueOf(text);
mHistoryQuickTextKey.recordUsedKey(name... | @Test
public void onTextWithText() throws Exception {
Keyboard.Key key = Mockito.mock(Keyboard.Key.class);
key.label = "testing";
mUnderTest.onText(key, "testing_value");
Mockito.verify(mKeyboardListener).onText(key, "testing_value");
Mockito.verify(mHistoryKey).recordUsedKey("testing", "testing... |
@Override
public void close() throws IOException {
close(false);
} | @Test
public void testClose() throws Exception {
this.writer.close();
Mockito.verify(this.snapshotStorage, Mockito.only()).close(this.writer, false);
} |
@Override
protected ResultSubpartitionView createSubpartitionView(
int subpartitionId, BufferAvailabilityListener availabilityListener)
throws IOException {
checkState(!isReleased(), "ResultPartition already released.");
// If data file is not readable, throw PartitionNotFou... | @Test
void testFullSpillingStrategyRegisterMultipleConsumer() throws Exception {
final int numSubpartitions = 2;
BufferPool bufferPool = globalPool.createBufferPool(2, 2);
try (HsResultPartition partition =
createHsResultPartition(
2,
... |
private ServerHttpRequestDecorator decorate(final ServerWebExchange exchange, final CachedBodyOutputMessage outputMessage) {
return new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public Flux<DataBuffer> getBody() {
return outputMessage.getBody();
... | @Test
public void testDecorate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ServerWebExchange webExchangeTextPlain =
MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost:8080")
.conten... |
public String getValue() {
if (period == null) {
final DateFormat dateFormat = I18N.createDateFormat();
return dateFormat.format(startDate) + CUSTOM_PERIOD_SEPARATOR
+ dateFormat.format(endDate);
}
return period.getCode();
} | @Test
public void testGetValue() {
assertNotNull("getValue", periodRange.getValue());
assertNotNull("getValue", customRange.getValue());
} |
@Override
public List<PostDO> getPostList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return postMapper.selectBatchIds(ids);
} | @Test
public void testGetPostList() {
// mock 数据
PostDO postDO01 = randomPojo(PostDO.class);
postMapper.insert(postDO01);
// 测试 id 不匹配
PostDO postDO02 = randomPojo(PostDO.class);
postMapper.insert(postDO02);
// 准备参数
List<Long> ids = singletonList(postD... |
public Optional<Measure> toMeasure(@Nullable LiveMeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getDataAsString();
switch (metric.getType().getValueType()) {... | @Test
public void toMeasure_should_not_loose_decimals_of_float_values() {
MetricImpl metric = new MetricImpl("42", "double", "name", Metric.MetricType.FLOAT, 5, null, false, false);
LiveMeasureDto LiveMeasureDto = new LiveMeasureDto()
.setValue(0.12345);
Optional<Measure> measure = underTest.toMeas... |
public static boolean safeRangeEquals(final Range<Comparable<?>> sourceRange, final Range<Comparable<?>> targetRange) {
Class<?> clazz = getRangeTargetNumericType(sourceRange, targetRange);
if (null == clazz) {
return sourceRange.equals(targetRange);
}
Range<Comparable<?>> ne... | @Test
void assertSafeRangeEqualsForLong() {
assertTrue(SafeNumberOperationUtils.safeRangeEquals(Range.greaterThan(1L), Range.greaterThan(BigInteger.ONE)));
} |
public static UStaticIdent create(UClassIdent classIdent, CharSequence member, UType memberType) {
return new AutoValue_UStaticIdent(classIdent, StringName.of(member), memberType);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UStaticIdent.create(
"java.lang.Integer",
"valueOf",
UMethodType.create(
UClassType.create("java.lang.Integer"), UClassType.create("java.lang.String"))))
... |
public static RuntimeException wrapIf(boolean condition, Throwable t) {
if (condition) {
return wrap(t);
}
if (t instanceof RuntimeException) {
return (RuntimeException) t;
}
return new RuntimeException(t);
} | @Test
public void testWrapIfReturnsSourceRuntimeExceptionWhenFalse() {
RuntimeException runtimeException = new RuntimeException("oh noes!");
RuntimeException wrapped = UserCodeException.wrapIf(false, runtimeException);
assertEquals(runtimeException, wrapped);
} |
public HollowHashIndexResult findMatches(Object... query) {
if (hashStateVolatile == null) {
throw new IllegalStateException(this + " wasn't initialized");
}
int hashCode = 0;
for(int i=0;i<query.length;i++) {
if(query[i] == null)
throw new Illega... | @Test
public void testIndexingFloatTypeFieldWithNullValues() throws Exception {
mapper.add(new TypeFloat(null));
mapper.add(new TypeFloat(-1.0f));
roundTripSnapshot();
HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeFloat", "", "data.value");
Assert.assert... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertUnsupported() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("aaa").dataType("aaa").build();
try {
RedshiftTypeConverter.INSTANCE.convert(typeDefine);
Assertions.fail();
} catch (Se... |
public static double find(Function func, double x1, double x2, double tol, int maxIter) {
if (tol <= 0.0) {
throw new IllegalArgumentException("Invalid tolerance: " + tol);
}
if (maxIter <= 0) {
throw new IllegalArgumentException("Invalid maximum number of iterations: " ... | @Test
public void testBrent() {
System.out.println("Brent");
double result = Root.find(x -> x * x * x + x * x - 5 * x + 3, -4, -2, 1E-7, 500);
assertEquals(-3, result, 1E-7);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.