focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
String path = ((HttpServletRequest) req).getRequestURI().replaceFirst(((HttpServletRequest) req).getContextPath(), "");
MAX_AGE_BY_PATH.entrySet().stream()
.filter(m -> pat... | @Test
public void max_age_is_set_to_five_minutes_on_css_of_static() throws Exception {
HttpServletRequest request = newRequest("/static/css/custom.css");
underTest.doFilter(request, response, chain);
verify(response).addHeader("Cache-Control", format("max-age=%s", 300));
} |
public static DefaultCryptoKeyReaderBuilder builder() {
return new DefaultCryptoKeyReaderBuilder();
} | @Test
public void testBuild() throws Exception {
Map<String, String> publicKeys = new HashMap<>();
publicKeys.put("key1", "file:///path/to/public1.key");
publicKeys.put("key2", "file:///path/to/public2.key");
Map<String, String> privateKeys = new HashMap<>();
privateKeys.put... |
public static String dataToAvroSchemaJson(DataSchema dataSchema)
{
return dataToAvroSchemaJson(dataSchema, new DataToAvroSchemaTranslationOptions());
} | @Test(dataProvider = "schemaWithNamespaceOverride")
public void testSchemaWithNamespaceOverride(String schemaText, String expected) throws IOException
{
DataToAvroSchemaTranslationOptions options = new DataToAvroSchemaTranslationOptions(JsonBuilder.Pretty.SPACES).setOverrideNamespace(true);
String avroSchem... |
public static RangeQueryBuilder rangeQuery(String name) {
return new RangeQueryBuilder(name);
} | @Test
public void testRangeQuery() throws Exception {
assertEquals("{\"range\":{\"k\":{\"lt\":123}}}",
toJson(QueryBuilders.rangeQuery("k").lt(123)));
assertEquals("{\"range\":{\"k\":{\"gt\":123}}}",
toJson(QueryBuilders.rangeQuery("k").gt(123)));
assertEquals... |
public static String getTemporaryObjectName(
GSBlobIdentifier finalBlobIdentifier, UUID temporaryObjectId) {
return getTemporaryObjectPartialName(finalBlobIdentifier) + temporaryObjectId.toString();
} | @Test
public void shouldProperlyConstructTemporaryObjectName() {
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
UUID temporaryObjectId = UUID.fromString("f09c43e5-ea49-4537-a406-0586f8f09d47");
String partialName = BlobUtils.getTemporaryObjectName(identifier, temporaryObj... |
int maxCongestionWindow()
{
return maxCwnd;
} | @Test
void shouldSetWindowLengthFromContext()
{
final CubicCongestionControl cubicCongestionControl = new CubicCongestionControl(
0, channelWithoutWindow, 0, 0, bigTermLength, MTU_LENGTH, null, null, nanoClock, context, countersManager);
assertEquals(CONTEXT_RECEIVER_WINDOW_LENGTH /... |
public static double getSquaredDistanceToLine(
final double pFromX, final double pFromY,
final double pAX, final double pAY, final double pBX, final double pBY
) {
return getSquaredDistanceToProjection(pFromX, pFromY, pAX, pAY, pBX, pBY,
getProjectionFactorToLine(pFro... | @Test
public void test_getSquareDistanceToLine() {
final int xA = 100;
final int yA = 200;
final int deltaX = 10;
final int deltaY = 20;
Assert.assertEquals(0,
Distance.getSquaredDistanceToLine(xA, yA, xA, yA, xA, yA), mDelta);
Assert.assertEquals(delt... |
public static Long jsToInteger( Object value, Class<?> clazz ) {
if ( Number.class.isAssignableFrom( clazz ) ) {
return ( (Number) value ).longValue();
} else {
String classType = clazz.getName();
if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
return ( new Long( (String) val... | @Test( expected = NumberFormatException.class )
public void jsToInteger_String_Unparseable() throws Exception {
JavaScriptUtils.jsToInteger( "q", String.class );
} |
public long getFailedSyncCount() {
final AtomicLong result = new AtomicLong();
distroRecords.forEach((s, distroRecord) -> result.addAndGet(distroRecord.getFailedSyncCount()));
return result.get();
} | @Test
void testGetFailedSyncCount() {
DistroRecordsHolder.getInstance().getRecord("testGetFailedSyncCount");
Optional<DistroRecord> actual = DistroRecordsHolder.getInstance().getRecordIfExist("testGetFailedSyncCount");
assertTrue(actual.isPresent());
assertEquals(0, DistroRecordsHold... |
@Override
public int compareTo(Resource other) {
checkArgument(other != null && getClass() == other.getClass() && name.equals(other.name));
return value.compareTo(other.value);
} | @Test
void testCompareToFailDifferentType() {
// initialized as different anonymous classes
final Resource resource1 = new TestResource(0.0) {};
final Resource resource2 = new TestResource(0.0) {};
assertThatThrownBy(() -> resource1.compareTo(resource2))
.isInstanceOf... |
@Override
public Processor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>> get() {
return new ContextualProcessor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>>() {
private KT... | @Test
public void shouldPropagateNullIfNoFKAvailableV1() {
final MockProcessorContext<String, SubscriptionResponseWrapper<String>> context = new MockProcessorContext<>();
processor.init(context);
final SubscriptionWrapper<String> newValue = new SubscriptionWrapper<>(
new long[]{... |
public ReliableTopicConfig setStatisticsEnabled(boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
return this;
} | @Test
public void setStatisticsEnabled() {
ReliableTopicConfig config = new ReliableTopicConfig("foo");
boolean newValue = !DEFAULT_STATISTICS_ENABLED;
config.setStatisticsEnabled(newValue);
assertEquals(newValue, config.isStatisticsEnabled());
} |
public static PulsarLogCollectClient getPulsarLogCollectClient() {
return PULSAR_LOG_COLLECT_CLIENT;
} | @Test
public void testGetPulsarLogCollectClient() {
Assertions.assertEquals(LoggingPulsarPluginDataHandler.getPulsarLogCollectClient().getClass(), PulsarLogCollectClient.class);
} |
@Override
public GetApplicationAttemptsResponse getApplicationAttempts(
GetApplicationAttemptsRequest request) throws YarnException, IOException {
ApplicationId appId = request.getApplicationId();
UserGroupInformation callerUGI = getCallerUgi(appId,
AuditConstants.GET_APP_ATTEMPTS);
RMApp ap... | @Test
public void testGetApplicationAttempts() throws YarnException, IOException {
ClientRMService rmService = createRMService();
GetApplicationAttemptsRequest request = recordFactory
.newRecordInstance(GetApplicationAttemptsRequest.class);
ApplicationAttemptId attemptId = ApplicationAttemptId.new... |
public static <K, E> Collector<E, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) {
return unorderedIndex(keyFunction, Function.identity());
} | @Test
public void unorderedIndex_fails_if_key_function_is_null() {
assertThatThrownBy(() -> unorderedIndex(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Key function can't be null");
} |
@Override
public ClusterInfo getClusterInfo() {
try {
long startTime = Time.now();
Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters();
Class[] argsClasses = new Class[]{};
Object[] args = new Object[]{};
ClientMethod remoteMethod = new ClientMethod... | @Test
public void testGetClusterInfo() {
ClusterInfo clusterInfos = interceptor.getClusterInfo();
Assert.assertNotNull(clusterInfos);
Assert.assertTrue(clusterInfos instanceof FederationClusterInfo);
FederationClusterInfo federationClusterInfos =
(FederationClusterInfo) (clusterInfos);
L... |
public static void addThreadBlockedTimeMetric(final String threadId,
final StreamThreadTotalBlockedTime blockedTime,
final StreamsMetricsImpl streamsMetrics) {
streamsMetrics.addThreadLevelMutableMetric(
... | @Test
public void shouldAddTotalBlockedTimeMetric() {
// Given:
final double startTime = 123.45;
final StreamThreadTotalBlockedTime blockedTime = mock(StreamThreadTotalBlockedTime.class);
when(blockedTime.compute()).thenReturn(startTime);
// When:
ThreadMetrics.addTh... |
public static void updateTmpDirectoriesInConfiguration(
Configuration configuration, @Nullable String defaultDirs) {
if (configuration.contains(CoreOptions.TMP_DIRS)) {
LOG.info(
"Overriding Flink's temporary file directories with those "
+... | @Test
void testShouldNotUpdateTmpDirectoriesInConfigurationIfNoValueConfigured() {
Configuration config = new Configuration();
BootstrapTools.updateTmpDirectoriesInConfiguration(config, null);
assertThat(CoreOptions.TMP_DIRS.defaultValue()).isEqualTo(config.get(CoreOptions.TMP_DIRS));
} |
public MetaString(
String string, Encoding encoding, char specialChar1, char specialChar2, byte[] bytes) {
this.string = string;
this.encoding = encoding;
this.specialChar1 = specialChar1;
this.specialChar2 = specialChar2;
this.bytes = bytes;
if (encoding != Encoding.UTF_8) {
Precond... | @Test(dataProvider = "specialChars")
public void testMetaString(char specialChar1, char specialChar2) {
MetaStringEncoder encoder = new MetaStringEncoder(specialChar1, specialChar2);
for (int i = 1; i < 128; i++) {
try {
String str = createString(i, specialChar1, specialChar2);
MetaStrin... |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = RealtimeToOfflineSegmentsTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
String realtimeTableName = tableConfig.getTabl... | @Test
public void testGenerateTasksCheckConfigs() {
ClusterInfoAccessor mockClusterInfoProvide = mock(ClusterInfoAccessor.class);
when(mockClusterInfoProvide.getTaskStates(RealtimeToOfflineSegmentsTask.TASK_TYPE)).thenReturn(new HashMap<>());
SegmentZKMetadata segmentZKMetadata =
getSegmentZKMeta... |
@Udf(description = "Returns a new string encoded using the outputEncoding ")
public String encode(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The input encoding."
+ " If null, the... | @Test
public void shouldEncodeHexToBase64() {
assertThat(udf.encode("4578616d706c6521", "hex", "base64"), is("RXhhbXBsZSE="));
assertThat(udf.encode("506c616e74207472656573", "hex", "base64"), is("UGxhbnQgdHJlZXM="));
assertThat(udf.encode("31202b2031203d2031", "hex", "base64"), is("MSArIDEgPSAx"));
a... |
public static byte[] compress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
ZipEntry entry = new ZipEntry("zip... | @Test
public void test_compress() {
Assertions.assertThrows(NullPointerException.class, () -> {
ZipUtil.compress(null);
});
} |
public static List<Column> generateReferencedColumns(
String projectionExpression, @Nullable String filterExpression, List<Column> columns) {
if (isNullOrWhitespaceOnly(projectionExpression)) {
return new ArrayList<>();
}
Set<String> referencedColumnNames = new HashSet<>... | @Test
public void testGenerateReferencedColumns() {
List<Column> testColumns =
Arrays.asList(
Column.physicalColumn("id", DataTypes.INT(), "id"),
Column.physicalColumn("name", DataTypes.STRING(), "string"),
Column.physic... |
public Column getColumn(String value) {
Matcher m = PATTERN.matcher(value);
if (!m.matches()) {
throw new IllegalArgumentException("value " + value + " is not a valid column definition");
}
String name = m.group(1);
String type = m.group(6);
type = type == nu... | @Test
public void testGetLongArrayColumn() {
ColumnFactory f = new ColumnFactory();
Column column = f.getColumn("column: Long[]");
assertThat(column instanceof ArrayColumn).isTrue();
assertThat(column.getName()).isEqualTo("column");
assertThat(column.getCellType()).isEqualTo(... |
public IndexerDirectoryInformation parse(Path path) {
if (!Files.exists(path)) {
throw new IndexerInformationParserException("Path " + path + " does not exist.");
}
if (!Files.isDirectory(path)) {
throw new IndexerInformationParserException("Path " + path + " is not a di... | @Test
void testElasticsearch7() throws URISyntaxException {
final URI uri = getClass().getResource("/indices/elasticsearch7").toURI();
final IndexerDirectoryInformation result = parser.parse(Path.of(uri));
Assertions.assertThat(result.nodes())
.hasSize(1)
.all... |
@VisibleForTesting
public void validateNoticeExists(Long id) {
if (id == null) {
return;
}
NoticeDO notice = noticeMapper.selectById(id);
if (notice == null) {
throw exception(NOTICE_NOT_FOUND);
}
} | @Test
public void testValidateNoticeExists_success() {
// 插入前置数据
NoticeDO dbNotice = randomPojo(NoticeDO.class);
noticeMapper.insert(dbNotice);
// 成功调用
noticeService.validateNoticeExists(dbNotice.getId());
} |
@Override
public String toString() {
return new ReflectionToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).toString();
} | @Test
void testToString() {
PurgeableAnalysisDto dto = new PurgeableAnalysisDto().setAnalysisUuid("u3");
assertThat(dto.toString()).isNotEmpty();
} |
@Override
public void bind() {
server.bind();
} | @Test
public void bind() throws IOException {
ServerSupport support = new ServerSupport(RandomPort::getSafeRandomPort);
support.bind();
while (!support.isActive()) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100L));
}
Assert.assertTrue(support.isActive()... |
public <E extends Enum> E getEnum(HazelcastProperty property, Class<E> enumClazz) {
String value = getString(property);
for (E enumConstant : enumClazz.getEnumConstants()) {
if (equalsIgnoreCase(enumConstant.name(), value)) {
return enumConstant;
}
}
... | @Test
public void getEnum() {
config.setProperty(ClusterProperty.HEALTH_MONITORING_LEVEL.getName(), "NOISY");
HazelcastProperties properties = new HazelcastProperties(config.getProperties());
HealthMonitorLevel healthMonitorLevel = properties
.getEnum(ClusterProperty.HEALTH_M... |
@Override
public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath,
String managementContextPath, Integer managementPort) {
if (isRandom(managementPort)) {
return null;
}
if (managementPort == null && isRandom(serverPort)) {
return null;
}
String heal... | @Test
void serverPortIsRandomAndManagementPortIsNull() {
int serverPort = 0;
String serverContextPath = "/";
String managementContextPath = null;
Integer managementPort = null;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath,
managementPort);
ass... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
try {
final ResourceCreationRepresentationArrayInner resourceCreationRepresentation = new ResourceCreationRepresentationArrayInner();
final String path = StringUtils.removeStart(f... | @Test
public void testAttributes() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final TransferStatus status = new TransferStatus();
final Path directory = new EueDirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringServic... |
List<AttributeKvEntry> filterChangedAttr(List<AttributeKvEntry> currentAttributes, List<AttributeKvEntry> newAttributes) {
if (currentAttributes == null || currentAttributes.isEmpty()) {
return newAttributes;
}
Map<String, AttributeKvEntry> currentAttrMap = currentAttributes.stream(... | @Test
void testFilterChangedAttr_whenCurrentAttributesEmpty_thenReturnNewAttributes() {
List<AttributeKvEntry> newAttributes = new ArrayList<>();
List<AttributeKvEntry> filtered = node.filterChangedAttr(Collections.emptyList(), newAttributes);
assertThat(filtered).isSameAs(newAttributes);
... |
@JsonIgnore
public LongParamDefinition getCompletedByTsParam() {
if (completedByTs != null) {
return ParamDefinition.buildParamDefinition(PARAM_NAME, completedByTs);
}
if (completedByHour != null) {
String timeZone = tz == null ? "WORKFLOW_CRON_TIMEZONE" : String.format("'%s'", tz);
retu... | @Test
public void testGetCompletedByTsParam() {
Tct tct = new Tct();
tct.setCompletedByTs(123L);
tct.setTz("UTC");
LongParamDefinition expected =
LongParamDefinition.builder().name("completed_by_ts").value(123L).build();
LongParamDefinition actual = tct.getCompletedByTsParam();
assert... |
@Override
public CreateAclsRequestData data() {
return data;
} | @Test
public void shouldThrowOnV0IfNotLiteral() {
assertThrows(UnsupportedVersionException.class, () -> new CreateAclsRequest(data(PREFIXED_ACL1), V0));
} |
public String getFilePath() {
return this.filePath;
} | @Test
public void testGetFilePath() {
Dependency instance = new Dependency();
String expResult = "file.tar";
instance.setFilePath(expResult);
String result = instance.getFilePath();
assertEquals(expResult, result);
} |
public Collection<ServerPluginInfo> loadPlugins() {
Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>();
for (ServerPluginInfo bundled : getBundledPluginsMetadata()) {
failIfContains(bundledPluginsByKey, bundled,
plugin -> MessageException.of(format("Found two versions of the... | @Test
public void fail_if_plugin_does_not_support_plugin_api_version() throws Exception {
when(sonarRuntime.getApiVersion()).thenReturn(org.sonar.api.utils.Version.parse("1.0"));
copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir());
assertThatThrownBy(() -> underTest.loadPlugins())
... |
public static TbMathArgumentValue fromMessageMetadata(TbMathArgument arg, String argKey, TbMsgMetaData metaData) {
Double defaultValue = arg.getDefaultValue();
if (metaData == null) {
return defaultOrThrow(defaultValue, "Message metadata is empty!");
}
var value = metaData.ge... | @Test
public void test_fromMessageMetadata_then_valueEmpty() {
TbMathArgument tbMathArgument = new TbMathArgument(TbMathArgumentType.MESSAGE_BODY, "TestKey");
Throwable thrown = assertThrows(RuntimeException.class, () -> TbMathArgumentValue.fromMessageMetadata(tbMathArgument, tbMathArgument.getKey()... |
public static boolean isSvgEnabled() {
return true;
} | @Test
public void testIsSvgEnabled() throws Exception {
assertTrue( SvgSupport.isSvgEnabled() );
} |
public static MulticastMappingInstruction multicastPriority(int priority) {
return new MulticastMappingInstruction.PriorityMappingInstruction(
MulticastType.PRIORITY, priority);
} | @Test
public void testMulticastPriorityMethod() {
final MappingInstruction instruction = MappingInstructions.multicastPriority(2);
final MulticastMappingInstruction.PriorityMappingInstruction priorityMappingInstruction =
checkAndConvert(instruction,
Mu... |
public static String formatHostnameForHttp(InetSocketAddress addr) {
String hostString = NetUtil.getHostname(addr);
if (NetUtil.isValidIpV6Address(hostString)) {
if (!addr.isUnresolved()) {
hostString = NetUtil.toAddressString(addr.getAddress());
} else if (hostSt... | @Test
public void testIpv6() throws Exception {
InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName("::1"), 8080);
assertEquals("[::1]", HttpUtil.formatHostnameForHttp(socketAddress));
} |
public static <K, V> AsMultimap<K, V> asMultimap() {
return new AsMultimap<>(false);
} | @Test
public void testViewUnboundedAsMultimapDirect() {
testViewUnbounded(pipeline, View.asMultimap());
} |
@Override
public synchronized void write(int b) throws IOException {
checkNotClosed();
file.writeLock().lock();
try {
if (append) {
pos = file.sizeWithoutLocking();
}
file.write(pos++, (byte) b);
file.setLastModifiedTime(fileSystemState.now());
} finally {
file.... | @Test
public void testWrite_partialArray() throws IOException {
JimfsOutputStream out = newOutputStream(false);
out.write(new byte[] {1, 2, 3, 4, 5, 6}, 1, 3);
assertStoreContains(out, 2, 3, 4);
} |
@SuppressWarnings("unused") // Required for automatic type inference
public static <K> Builder0<K> forClass(final Class<K> type) {
return new Builder0<>();
} | @Test
public void shouldNotThrowOnDuplicateHandler1() {
HandlerMaps.forClass(BaseType.class).withArgType(String.class)
.put(LeafTypeA.class, handler1_1)
.put(LeafTypeB.class, handler1_1);
} |
public SSLParametersConfiguration getParameters() {
if (parameters == null) {
parameters = new SSLParametersConfiguration();
}
return parameters;
} | @Test
public void testParameters() throws Exception {
assertNotNull(configuration.getParameters());
} |
static void cleanStackTrace(Throwable throwable) {
new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet());
} | @Test
public void allFramesAboveSubjectCleaned() {
Throwable throwable =
createThrowableWithStackTrace(
"com.google.random.Package",
"com.google.common.base.collection.ImmutableMap",
"com.google.common.truth.StringSubject",
"com.google.example.SomeClass");
... |
protected static SimpleDateFormat getLog4j2Appender() {
Optional<Appender> log4j2xmlAppender =
configuration.getAppenders().values().stream()
.filter( a -> a.getName().equalsIgnoreCase( log4J2Appender ) ).findFirst();
if ( log4j2xmlAppender.isPresent() ) {
ArrayList<String> matchesArray = ne... | @Test
public void testGetLog4j2UsingAppender10() {
// Testing adding TimeZone GMT+0
KettleLogLayout.log4J2Appender = "pdi-execution-appender-test-10";
Assert.assertEquals( "MMM dd,yyyy HH:mm:ss",
KettleLogLayout.getLog4j2Appender().toPattern() );
} |
public void startCluster() throws ClusterEntrypointException {
LOG.info("Starting {}.", getClass().getSimpleName());
try {
FlinkSecurityManager.setFromConfiguration(configuration);
PluginManager pluginManager =
PluginUtils.createPluginManagerFromRootFolder(co... | @Test
public void testWorkingDirectoryIsSetupWhenStartingTheClusterEntrypoint() throws Exception {
final File workingDirBase = TEMPORARY_FOLDER.newFolder();
final ResourceID resourceId = new ResourceID("foobar");
configureWorkingDirectory(flinkConfig, workingDirBase, resourceId);
f... |
@Override
public void start(
final KsqlModuleType moduleType,
final Properties ksqlProperties) {
final BaseSupportConfig ksqlVersionCheckerConfig =
new PhoneHomeConfig(ksqlProperties, "ksql");
if (!ksqlVersionCheckerConfig.isProactiveSupportEnabled()) {
log.warn(legalDisclaimerProac... | @Test
@SuppressWarnings("unchecked")
public void shouldCreateKsqlVersionCheckerWithCorrectActivenessStatusSupplier() {
// When:
ksqlVersionCheckerAgent.start(KsqlModuleType.SERVER, properties);
// Then:
verify(versionCheckerFactory).create(any(), any(), anyBoolean(), activenessCaptor.capture());
... |
@Override
public SelType binaryOps(SelOp op, SelType rhs) {
if (rhs.type() == SelTypes.NULL && (op == SelOp.EQUAL || op == SelOp.NOT_EQUAL)) {
return rhs.binaryOps(op, this);
}
if (rhs.type() == SelTypes.DOUBLE) {
SelDouble lhs = SelDouble.of(this.val);
return lhs.binaryOps(op, rhs);
... | @Test
public void testBinaryOps() {
SelType obj = SelLong.of(2);
SelType res = orig.binaryOps(SelOp.EQUAL, obj);
assertEquals("BOOLEAN: false", res.type() + ": " + res);
res = orig.binaryOps(SelOp.NOT_EQUAL, obj);
assertEquals("BOOLEAN: true", res.type() + ": " + res);
res = orig.binaryOps(Sel... |
public boolean hasNoLeaderInformation() {
return leaderInformationPerComponentId.isEmpty();
} | @Test
void hasNoLeaderInformation() {
LeaderInformationRegister register = LeaderInformationRegister.empty();
assertThat(register.hasNoLeaderInformation()).isTrue();
register = LeaderInformationRegister.of("component-id", LeaderInformation.empty());
assertThat(register.hasNoLeaderIn... |
public static OffsetBasedPagination forStartRowNumber(int startRowNumber, int pageSize) {
checkArgument(startRowNumber >= 1, "startRowNumber must be >= 1");
checkArgument(pageSize >= 1, "page size must be >= 1");
return new OffsetBasedPagination(startRowNumber - 1, pageSize);
} | @Test
void forStartRowNumber_whenStartRowNumberLowerThanOne_shouldfailsWithIAE() {
assertThatThrownBy(() -> OffsetBasedPagination.forStartRowNumber(0, 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("startRowNumber must be >= 1");
} |
public static EncryptionPluginManager instance() {
return INSTANCE;
} | @Test
void testInstance() {
EncryptionPluginManager instance = EncryptionPluginManager.instance();
assertNotNull(instance);
} |
@Override
public V replace(K key, V newValue) {
begin();
V oldValue = transactionalMap.replace(key, newValue);
commit();
return oldValue;
} | @Test
public void testReplace() {
map.put(42, "oldValue");
String oldValue = adapter.replace(42, "newValue");
assertEquals("oldValue", oldValue);
assertEquals("newValue", map.get(42));
} |
@Inject
public FileMergeCacheManager(
CacheConfig cacheConfig,
FileMergeCacheConfig fileMergeCacheConfig,
CacheStats stats,
ExecutorService cacheFlushExecutor,
ExecutorService cacheRemovalExecutor,
ScheduledExecutorService cacheSizeCalculateExe... | @Test(timeOut = 30_000)
public void testQuota()
throws InterruptedException, ExecutionException, IOException
{
TestingCacheStats stats = new TestingCacheStats();
CacheManager cacheManager = fileMergeCacheManager(stats);
byte[] buffer = new byte[10240];
CacheQuota cac... |
@Operation(summary = "Get SAML metadata")
@GetMapping(value = "/idp/metadata", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public String metadata() throws MetadataException {
logger.debug("Receive SAML metadata request!");
return idpMetadataService.getMetadata();
} | @Test
public void idpMetadataTest() throws MetadataException {
String idpMetadata = "idpMetadata";
when(idpMetadataServiceMock.getMetadata()).thenReturn(idpMetadata);
String result = metadataControllerMock.metadata();
assertNotNull(result);
assertEquals(idpMetadata, result)... |
public static String getParent(String filePath, int level) {
final File parent = getParent(file(filePath), level);
try {
return null == parent ? null : parent.getCanonicalPath();
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | @Test
public void getParentTest() {
// 只在Windows下测试
if (FileUtil.isWindows()) {
File parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 0);
assertEquals(FileUtil.file("d:\\aaa\\bbb\\cc\\ddd"), parent);
parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 1);
assertEquals(FileUt... |
private String toStringBoolean() {
// Code was removed from this method as ValueBoolean
// did not store length, so some parts could never be
// called.
String retval;
if ( value == null ) {
return null;
}
if ( isNull() ) {
retval = Const.NULL_BOOLEAN;
} else {
retval ... | @Test
public void testToStringBoolean() {
String result = null;
Value vs = new Value( "Name", Value.VALUE_TYPE_BOOLEAN );
vs.setValue( true );
result = vs.toString( true );
assertEquals( "true", result );
Value vs1 = new Value( "Name", Value.VALUE_TYPE_BOOLEAN );
vs1.setValue( false );
... |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldThrowXsdValidationException_When2RepositoriesInSameConfigElement() {
assertThatThrownBy(() -> xmlLoader.loadConfigHolder(configWithConfigRepos(
"""
<config-repos>
<config-repo pluginId="myplugin">
... |
Future<Boolean> canRollController(int nodeId) {
LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId);
return describeMetadataQuorum().map(info -> {
boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info);
if (!canRoll) {
... | @Test
public void cannotRollController2NodeQuorumFollowerBehind(VertxTestContext context) {
Map<Integer, OptionalLong> controllers = new HashMap<>();
controllers.put(1, OptionalLong.of(10000L));
controllers.put(2, OptionalLong.of(7000L));
Admin admin = setUpMocks(1, controllers);
... |
public static boolean matches(String wildcard, String ipAddress) {
if (false == ReUtil.isMatch(PatternPool.IPV4, ipAddress)) {
return false;
}
final String[] wildcardSegments = wildcard.split("\\.");
final String[] ipSegments = ipAddress.split("\\.");
if (wildcardSegments.length != ipSegments.length) {
... | @Test
public void matchesTest() {
final boolean matches1 = Ipv4Util.matches("127.*.*.1", "127.0.0.1");
assertTrue(matches1);
final boolean matches2 = Ipv4Util.matches("192.168.*.1", "127.0.0.1");
assertFalse(matches2);
} |
@Override public SlotAssignmentResult ensure(long key1, long key2) {
return super.ensure0(key1, key2);
} | @Test
public void testPut() {
final long key1 = randomKey();
final long key2 = randomKey();
SlotAssignmentResult slot = insert(key1, key2);
assertTrue(slot.isNew());
final long valueAddress = slot.address();
slot = hsa.ensure(key1, key2);
assertFalse(slot.isN... |
public static GenericRecord rewriteRecord(GenericRecord oldRecord, Schema newSchema) {
GenericRecord newRecord = new GenericData.Record(newSchema);
boolean isSpecificRecord = oldRecord instanceof SpecificRecordBase;
for (Schema.Field f : newSchema.getFields()) {
if (!(isSpecificRecord && isMetadataFie... | @Test
public void testNonNullableFieldWithDefault() {
GenericRecord rec = new GenericData.Record(new Schema.Parser().parse(EXAMPLE_SCHEMA));
rec.put("_row_key", "key1");
rec.put("non_pii_col", "val1");
rec.put("pii_col", "val2");
rec.put("timestamp", 3.5);
GenericRecord rec1 = HoodieAvroUtils.... |
@Override
@Nonnull
public <T extends DataConnection> T getAndRetainDataConnection(String name, Class<T> clazz) {
DataConnectionEntry dataConnection = dataConnections.computeIfPresent(name, (k, v) -> {
if (!clazz.isInstance(v.instance)) {
throw new HazelcastException("Data con... | @Test
public void should_return_data_connection_from_config() {
DataConnection dataConnection = dataConnectionService.getAndRetainDataConnection(TEST_CONFIG, DummyDataConnection.class);
assertThat(dataConnection).isInstanceOf(DummyDataConnection.class);
assertThat(dataConnection.getName()).... |
List<MappingField> resolveFields(
@Nonnull String[] externalName,
@Nullable String dataConnectionName,
@Nonnull Map<String, String> options,
@Nonnull List<MappingField> userFields,
boolean stream
) {
Predicate<MappingField> pkColumnName = Options.g... | @Test
public void testResolvesMappingFieldsViaSample_wrongUserType() {
try (MongoClient client = MongoClients.create(mongoContainer.getConnectionString())) {
String databaseName = "testDatabase";
String collectionName = "people_3";
MongoDatabase testDatabase = client.getD... |
public static int compare(byte[] left, byte[] right) {
return compare(left, 0, left.length, right, 0, right.length);
} | @Test
public void testCompare() {
byte[] foo = "foo".getBytes(StandardCharsets.UTF_8);
assertEquals(ByteArray.compare(foo, foo), 0);
assertEquals(ByteArray.compare(foo, Arrays.copyOf(foo, foo.length)), 0);
assertTrue(ByteArray.compare(foo, Arrays.copyOf(foo, foo.length - 1)) > 0);
assertTrue(ByteA... |
@Override
public void deleteRole(String role) {
String sql = "DELETE FROM roles WHERE role=?";
try {
EmbeddedStorageContextHolder.addSqlContext(sql, role);
databaseOperate.update(EmbeddedStorageContextHolder.getCurrentSqlContext());
} finally {
EmbeddedSto... | @Test
void testDeleteRole() {
embeddedRolePersistService.deleteRole("role");
embeddedRolePersistService.deleteRole("role", "userName");
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
assertEquals(0, currentSqlContext.siz... |
@Override
public KTable<K, Long> count() {
return doCount(NamedInternal.empty(), Materialized.with(keySerde, Serdes.Long()));
} | @Test
public void shouldCountAndMaterializeResults() {
groupedStream.count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as("count").withKeySerde(Serdes.String()));
try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
processData(driver);
... |
public static boolean httpRequestWasMade() {
return getFakeHttpLayer().hasRequestInfos();
} | @Test
public void httpRequestWasMade_returnsTrueIfRequestMatchingGivenRuleWasMade()
throws IOException, HttpException {
makeRequest("http://example.com");
assertTrue(FakeHttp.httpRequestWasMade("http://example.com"));
} |
@Override
@Nonnull
public <T extends DataConnection> T getAndRetainDataConnection(String name, Class<T> clazz) {
DataConnectionEntry dataConnection = dataConnections.computeIfPresent(name, (k, v) -> {
if (!clazz.isInstance(v.instance)) {
throw new HazelcastException("Data con... | @Test
public void should_fail_when_non_existing_data_connection() {
assertThatThrownBy(() -> dataConnectionService.getAndRetainDataConnection("non-existing-data-connection", DummyDataConnection.class))
.isInstanceOf(HazelcastException.class)
.hasMessage("Data connection 'non-... |
@Override
public Integer addScoreAndGetRevRank(V object, Number value) {
return get(addScoreAndGetRevRankAsync(object, value));
} | @Test
public void testAddScoreAndGetRevRank() {
RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple");
Integer res1 = set.addScoreAndGetRevRank("12", 12);
assertThat(res1).isEqualTo(0);
Integer res2 = set.addScoreAndGetRevRank("15", 10);
assertThat(res2).isEqu... |
public static void initSSL(Properties consumerProps) {
// Check if one-way SSL is enabled. In this scenario, the client validates the server certificate.
String trustStoreLocation = consumerProps.getProperty(SSL_TRUSTSTORE_LOCATION);
String trustStorePassword = consumerProps.getProperty(SSL_TRUSTSTORE_PASSW... | @Test
public void testInitSSLTrustStoreOnly()
throws CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException,
IOException, KeyStoreException {
Properties consumerProps = new Properties();
setTrustStoreProps(consumerProps);
// should not throw ... |
public static String valueOf(String regionId) {
if (ObjectHelper.isEmpty(regionId)) {
throw new IllegalArgumentException("Unexpected empty parameter: regionId.");
} else {
String endpoint = REGIONS.get(regionId.toLowerCase());
if (ObjectHelper.isNotEmpty(endpoint)) {
... | @Test
public void testRegions() {
assertEquals("obs.af-south-1.myhuaweicloud.com", OBSRegion.valueOf("af-south-1"));
assertEquals("obs.ap-southeast-2.myhuaweicloud.com", OBSRegion.valueOf("ap-southeast-2"));
assertEquals("obs.ap-southeast-3.myhuaweicloud.com", OBSRegion.valueOf("ap-southeast... |
public static <T> Partition<T> of(
int numPartitions,
PartitionWithSideInputsFn<? super T> partitionFn,
Requirements requirements) {
Contextful ctfFn =
Contextful.fn(
(T element, Contextful.Fn.Context c) ->
partitionFn.partitionFor(element, numPartitions, c),
... | @Test
public void testDisplayData() {
Partition<?> partition = Partition.of(123, new IdentityFn());
DisplayData displayData = DisplayData.from(partition);
assertThat(displayData, hasDisplayItem("numPartitions", 123));
assertThat(displayData, hasDisplayItem("partitionFn", IdentityFn.class));
} |
@Override
public ApiResult<TopicPartition, PartitionProducerState> handleResponse(
Node broker,
Set<TopicPartition> keys,
AbstractResponse abstractResponse
) {
DescribeProducersResponse response = (DescribeProducersResponse) abstractResponse;
Map<TopicPartition, Partition... | @Test
public void testCompletedResult() {
TopicPartition topicPartition = new TopicPartition("foo", 5);
DescribeProducersOptions options = new DescribeProducersOptions().brokerId(1);
DescribeProducersHandler handler = newHandler(options);
PartitionResponse partitionResponse = sample... |
public static HttpUrl buildHttpUrl(final String url) {
return buildHttpUrl(url, null);
} | @Test
public void buildHttpUrlTest() {
HttpUrl httpUrl = HttpUtils.buildHttpUrl(TEST_URL, formMap);
Assert.assertNotNull(httpUrl);
} |
public static <EventT> Write<EventT> write() {
return new AutoValue_JmsIO_Write.Builder<EventT>().build();
} | @Test
public void testPublisherWithRetryConfiguration() {
RetryConfiguration retryPolicy =
RetryConfiguration.create(5, Duration.standardSeconds(15), null);
JmsIO.Write<String> publisher =
JmsIO.<String>write()
.withConnectionFactory(connectionFactory)
.withRetryConfigu... |
public void setIncludedProtocols(String protocols) {
this.includedProtocols = protocols;
} | @Test
public void testSetIncludedProtocols() throws Exception {
configurable.setSupportedProtocols(new String[] { "A", "B", "C", "D" });
configuration.setIncludedProtocols("A,B ,C, D");
configuration.configure(configurable);
assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" },
configu... |
NodeIndices(ClusterSpec.Id cluster, NodeList allNodes) {
this(allNodes.cluster(cluster).mapToList(node -> node.allocation().get().membership().index()));
} | @Test
public void testNodeIndices() {
NodeIndices indices = new NodeIndices(List.of(1, 3, 4));
assertEquals(0, indices.probeNext());
assertEquals(2, indices.probeNext());
assertEquals(5, indices.probeNext());
assertEquals(6, indices.probeNext());
indices.resetProbe()... |
@Override
public Object getObject(final int columnIndex) throws SQLException {
return mergeResultSet.getValue(columnIndex, Object.class);
} | @Test
void assertGetObjectWithLong() throws SQLException {
long result = 0L;
when(mergeResultSet.getValue(1, long.class)).thenReturn(result);
assertThat(shardingSphereResultSet.getObject(1, long.class), is(result));
when(mergeResultSet.getValue(1, Long.class)).thenReturn(result);
... |
public void loadProperties(Properties properties) {
Set<Entry<Object, Object>> entries = properties.entrySet();
for (Entry entry : entries) {
String key = (String) entry.getKey();
Object value = entry.getValue();
String[] keySplit = key.split("[.]");
Map<String, Object> target = this;
... | @Test
void testLoadProperties() {
// given
K8sSpecTemplate template = new K8sSpecTemplate();
Properties p = new Properties();
p.put("k8s.intp.key1", "v1");
p.put("k8s.intp.key2", "v2");
p.put("k8s.key3", "v3");
p.put("key4", "v4");
// when
template.loadProperties(p);
// then
... |
public Instant getEndOfNextNthPeriod(Instant instant, int periods) {
return innerGetEndOfNextNthPeriod(this, this.periodicityType, instant, periods);
} | @Test
public void testVaryingNumberOfHourlyPeriods() {
RollingCalendar rc = new RollingCalendar("yyyy-MM-dd_HH");
long MILLIS_IN_HOUR = 3600 * 1000;
for (int p = 100; p > -100; p--) {
long now = 1223325293589L; // Mon Oct 06 22:34:53 CEST 2008
Instant result = rc.ge... |
@Override
public TaskId id() {
return task.id();
} | @Test
public void shouldDelegateId() {
final ReadOnlyTask readOnlyTask = new ReadOnlyTask(task);
readOnlyTask.id();
verify(task).id();
} |
public static void free(final DirectBuffer buffer)
{
if (null != buffer)
{
free(buffer.byteBuffer());
}
} | @Test
void freeShouldReleaseDirectBufferResources()
{
final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(4));
buffer.setMemory(0, 4, (byte)111);
BufferUtil.free(buffer);
} |
public String getDefMd5() { return defMd5; } | @Test
public void require_correct_defmd5() {
final String defMd5ForEmptyDefContent = "d41d8cd98f00b204e9800998ecf8427e";
RawConfig config = new RawConfig(key, null, payload, payloadChecksums, generation, false, defContent, Optional.empty());
assertThat(config.getDefMd5(), is(defMd5));
... |
@Override
public void clear() {
if (isEmpty()) {
return;
}
if (begin < end) {
Arrays.fill(elements, begin, end, null);
} else {
Arrays.fill(elements, 0, end, null);
Arrays.fill(elements, begin, elements.length, null);
}
... | @Test
public void testClear() {
CircularArrayList<String> list = new CircularArrayList<>();
list.clear();
assertEmpty(list);
for (int i = 0; i < 20; i++) {
list.add("str" + i);
}
list.clear();
assertEmpty(list);
for (int i = 10; i < 20; i... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testUnpartitionedIsNotNull() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
TruncateFunction.TruncateString function = new TruncateFunction.TruncateString();
UserDefinedScalarFunc udf = toUDF(function, expressions(in... |
static Properties getSystemProperties() {
String[] inputConfigSources = System.getProperty("proxyconfigsources",
DEFAULT_PROXY_CONFIG_SOURCES).split(",");
return new Properties(inputConfigSources);
} | @Test
void testReadingSystemProperties() {
ProxyServer.Properties properties = ProxyServer.getSystemProperties();
assertEquals(1, properties.configSources.length);
assertEquals(ProxyServer.DEFAULT_PROXY_CONFIG_SOURCES, properties.configSources[0]);
} |
@VisibleForTesting
int getSleepDuration() {
return sleepDuration;
} | @Test
public void testNoMetricUpdatesThenNoWaiting() {
ClientThrottlingAnalyzer analyzer = new ClientThrottlingAnalyzer(
"test",
ANALYSIS_PERIOD);
validate(0, analyzer.getSleepDuration());
sleep(ANALYSIS_PERIOD_PLUS_10_PERCENT);
validate(0, analyzer.getSleepDuration());
} |
public static <T> Encoder<T> encoderFor(Coder<T> coder) {
Encoder<T> enc = getOrCreateDefaultEncoder(coder.getEncodedTypeDescriptor().getRawType());
return enc != null ? enc : binaryEncoder(coder, true);
} | @Test
public void testBeamBinaryEncoder() {
List<List<String>> data = asList(asList("a1", "a2", "a3"), asList("b1", "b2"), asList("c1"));
Encoder<List<String>> encoder = encoderFor(ListCoder.of(StringUtf8Coder.of()));
serializeAndDeserialize(data.get(0), encoder);
Dataset<List<String>> dataset = cre... |
public static <C> AsyncBuilder<C> builder() {
return new AsyncBuilder<>();
} | @Test
void mapAndDecodeExecutesMapFunction() throws Throwable {
server.enqueue(new MockResponse().setBody("response!"));
TestInterfaceAsync api =
AsyncFeign.builder().mapAndDecode(upperCaseResponseMapper(), new StringDecoder())
.target(TestInterfaceAsync.class, "http://localhost:" + serve... |
public static <T> List<List<T>> splitBySize(List<T> list, int expectedSize)
throws NullPointerException, IllegalArgumentException {
Preconditions.checkNotNull(list, "list must not be null");
Preconditions.checkArgument(expectedSize > 0, "expectedSize must larger than 0");
if (1 == e... | @Test
public void testSplitBySizeNormal2() {
List<Integer> lists = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
int expectSize = 1;
List<List<Integer>> splitLists = ListUtil.splitBySize(lists, expectSize);
Assert.assertEquals(splitLists.size(), 1);
Assert.assertEquals(lists, sp... |
public static <T> CompletionStage<T> recover(CompletionStage<T> completionStage, Function<Throwable, T> exceptionHandler){
return completionStage.exceptionally(exceptionHandler);
} | @Test
public void shouldReturnResult2() throws Exception {
CompletableFuture<String> future = CompletableFuture.completedFuture("result");
String result = recover(future, TimeoutException.class, (e) -> "fallback").toCompletableFuture()
.get(1, TimeUnit.SECONDS);
assertThat(resu... |
@Override
public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() {
Iterable<RedisClusterNode> res = clusterGetNodes();
Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>();
for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.... | @Test
public void testClusterGetMasterSlaveMap() {
Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap();
assertThat(map).hasSize(3);
for (Collection<RedisClusterNode> slaves : map.values()) {
assertThat(slaves).hasSize(1);
}
... |
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
int[] colWidths = colWidths();
if (_headerColumnNames != null) {
append(buf, colWidths, _headerColumnNames);
int totalWidth = 0;
for (int width : colWidths) {
totalWidth += width;
}
buf.app... | @Test(priority = 1)
public void testToStringForEmptyTextTable() {
// Run the test
final String result = _textTableUnderTest.toString();
// Verify the results
assertEquals("", result);
} |
public ProtocolBuilder optimizer(String optimizer) {
this.optimizer = optimizer;
return getThis();
} | @Test
void optimizer() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.optimizer("optimizer");
Assertions.assertEquals("optimizer", builder.build().getOptimizer());
} |
@Override
public short getTypeCode() {
return MessageType.TYPE_BATCH_RESULT_MSG;
} | @Test
void getTypeCode() {
BatchResultMessage batchResultMessage = new BatchResultMessage();
Assertions.assertEquals(MessageType.TYPE_BATCH_RESULT_MSG, batchResultMessage.getTypeCode());
} |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldReturnValuesFullTableScan() {
// Given:
when(kafkaStreams.query(any())).thenReturn(getIteratorResult());
// When:
final KsMaterializedQueryResult<Row> result = table.get(PARTITION);
// Then:
Iterator<Row> rowIterator = result.getRowIterator();
assertThat(rowIterat... |
@PublicAPI(usage = ACCESS)
public Set<Dependency> getDirectDependenciesFromSelf() {
return javaClassDependencies.getDirectDependenciesFromClass();
} | @Test
public void direct_dependencies_from_self_by_references() {
JavaClass javaClass = importClasses(AReferencingB.class, BReferencedByA.class).get(AReferencingB.class);
assertReferencesFromAToB(javaClass.getDirectDependenciesFromSelf());
} |
public static LinearModel fit(Formula formula, DataFrame data) {
return fit(formula, data, new Properties());
} | @Test
public void testProstate() {
System.out.println("Prostate");
LinearModel model = OLS.fit(Prostate.formula, Prostate.train);
System.out.println(model);
double[] prediction = model.predict(Prostate.test);
double rmse = RMSE.of(Prostate.testy, prediction);
System... |
@Override
public void setRampDownPercent(long rampDownPercent) {
Validate.isTrue((rampDownPercent >= 0) && (rampDownPercent < 100), "rampDownPercent must be a value between 0 and 99");
this.rampDownPercent = rampDownPercent;
} | @Test(expected = IllegalArgumentException.class)
public void testSetRampDownPercent_exceeds99() {
sampler.setRampDownPercent(100);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.