focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void setName( String name ) {
this.name = name;
} | @Test
public void setName() {
JobScheduleParam jobScheduleParam = mock( JobScheduleParam.class );
doCallRealMethod().when( jobScheduleParam ).setName( any() );
String name = "hitachi";
jobScheduleParam.setName( name );
Assert.assertEquals( name, ReflectionTestUtils.getField( jobScheduleParam, "nam... |
@Override
public void collect(MetricsEmitter metricsEmitter) {
for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) {
MetricKey metricKey = entry.getKey();
KafkaMetric metric = entry.getValue();
try {
collectMetric(metricsEmitter, metricKey... | @Test
public void testSecondCollectCumulative() {
Sensor sensor = metrics.sensor("test");
sensor.add(metricName, new CumulativeSum());
sensor.record();
sensor.record();
time.sleep(60 * 1000L);
collector.collect(testEmitter);
// Update it again by 5 and adva... |
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
} | @Test
void handleFlowableConflictExceptionWithoutSendFullErrorException() throws Exception {
testController.exceptionSupplier = () -> new FlowableConflictException("task already exists");
handlerAdvice.setSendFullErrorException(false);
String body = mockMvc.perform(get("/"))
... |
public static int getDefaultResolutionIndex(final Context context,
final List<VideoStream> videoStreams) {
final String defaultResolution = computeDefaultResolution(context,
R.string.default_resolution_key, R.string.default_resolution_value);
... | @Test
public void getDefaultResolutionTest() {
final List<VideoStream> testList = new ArrayList<>(List.of(
generateVideoStream("mpeg_4-720", MediaFormat.MPEG_4, "720p", false),
generateVideoStream("v3gpp-240", MediaFormat.v3GPP, "240p", false),
generateVideoSt... |
@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) {
... | @Test
public void testCompare() {
assertNotEquals(0, compare(0, 1));
assertNotEquals(0, compare("foo", "bar"));
assertEquals(0, compare(0, 0));
assertEquals(0, compare(1.0, 1.0));
assertEquals(0, compare("foo", "foo"));
assertThat(compare(0, 1)).isNegative();
... |
public static int checkBackupCount(int newBackupCount, int currentAsyncBackupCount) {
if (newBackupCount < 0) {
throw new IllegalArgumentException("backup-count can't be smaller than 0");
}
if (currentAsyncBackupCount < 0) {
throw new IllegalArgumentException("async-back... | @Test
public void checkBackupCount() {
checkBackupCount(-1, 0, false);
checkBackupCount(-1, -1, false);
checkBackupCount(0, -1, false);
checkBackupCount(0, 0, true);
checkBackupCount(0, 1, true);
checkBackupCount(1, 1, true);
checkBackupCount(2, 1, true);
... |
public Object getCell(final int columnIndex) {
Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.size() + 1);
return data.get(columnIndex - 1);
} | @Test
void assertGetCellWithProperties() {
LocalDataQueryResultRow actual = new LocalDataQueryResultRow(new Properties(), PropertiesBuilder.build(new Property("foo", "bar")));
assertThat(actual.getCell(1), is(""));
assertThat(actual.getCell(2), is("{\"foo\":\"bar\"}"));
} |
@Override
public OAuth2AccessTokenDO grantAuthorizationCodeForAccessToken(String clientId, String code,
String redirectUri, String state) {
OAuth2CodeDO codeDO = oauth2CodeService.consumeAuthorizationCode(code);
Assert.notNull(codeD... | @Test
public void testGrantAuthorizationCodeForAccessToken() {
// 准备参数
String clientId = randomString();
String code = randomString();
List<String> scopes = Lists.newArrayList("read", "write");
String redirectUri = randomString();
String state = randomString();
... |
public static boolean verify(String token, byte[] key) {
return JWT.of(token).setKey(key).verify();
} | @Test
public void verifyTest(){
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
"eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2MjQwMDQ4MjIsInVzZXJJZCI6MSwiYXV0aG9yaXRpZXMiOlsiUk9MRV_op5LoibLkuozlj7ciLCJzeXNfbWVudV8xIiwiUk9MRV_op5LoibLkuIDlj7ciLCJzeXNfbWVudV8yIl0sImp0aSI6ImQ0YzVlYjgwLTA5ZTc... |
@Override
public ResultSet getVersionColumns(final String catalog, final String schema, final String table) {
return null;
} | @Test
void assertGetVersionColumns() {
assertNull(metaData.getVersionColumns("", "", ""));
} |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void variable() throws ScanException {
Tokenizer tokenizer = new Tokenizer("${abc}");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "abc"));
assertEquals(witne... |
public boolean usesBuckets( @NonNull VFSConnectionDetails details ) throws KettleException {
return details.hasBuckets() && getResolvedRootPath( details ) == null;
} | @Test
public void testUsesBucketsReturnsFalseIfNoBuckets() throws KettleException {
when( vfsConnectionDetails.hasBuckets() ).thenReturn( false );
// when( vfsConnectionDetails.getRootPath() ).thenReturn();
assertFalse( vfsConnectionManagerHelper.usesBuckets( vfsConnectionDetails ) );
} |
public Timestamp parseToTimestamp(final String text, final ZoneId zoneId) {
return Timestamp.from(parseZoned(text, zoneId).toInstant());
} | @Test
public void shouldParseToTimestamp() {
// Given
final String format = "yyyy-MM-dd HH";
final String timestamp = "1605-11-05 10";
// When
final Timestamp ts = new StringToTimestampParser(format).parseToTimestamp(timestamp, ZoneId.systemDefault());
// Then
assertThat(ts.getTime(), is... |
public String toServerErrorMessage() {
return fields.entrySet().stream().map(entry -> entry.getKey() + entry.getValue()).collect(Collectors.joining("\0"));
} | @Test
void assertToServerErrorMessage() {
PostgreSQLErrorResponsePacket responsePacket = createErrorResponsePacket();
String expectedMessage = "SFATAL\0VFATAL\0C3D000\0Mdatabase \"test\" does not exist\0Ddetail\0Hhint\0P1\0p2\0qinternal query\0"
+ "Wwhere\0stest\0ttable\0ccolumn\0dda... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchDisconnectedShouldClearPreferredReadReplica() {
buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(), new BytesDeserializer(),
Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED, Duration.ofMinutes(5).toMillis());
subscripti... |
public Path getParent() {
final String path = uri.getPath();
final int lastSlash = path.lastIndexOf('/');
final int start = hasWindowsDrive(path, true) ? 3 : 0;
if ((path.length() == start)
|| // empty path
(lastSlash == start && path.length() == start + 1... | @Test
void testGetParent() {
Path p = new Path("/my/fancy/path");
assertThat(p.getParent().toUri().getPath()).isEqualTo("/my/fancy");
p = new Path("/my/other/fancy/path/");
assertThat(p.getParent().toUri().getPath()).isEqualTo("/my/other/fancy");
p = new Path("hdfs:///my/p... |
@ConstantFunction.List(list = {
@ConstantFunction(name = "convert_tz", argTypes = {DATE, VARCHAR, VARCHAR}, returnType = DATETIME),
@ConstantFunction(name = "convert_tz", argTypes = {DATETIME, VARCHAR, VARCHAR}, returnType = DATETIME)
})
public static ConstantOperator convert_tz(Constant... | @Test
public void convert_tz() {
ConstantOperator olddt = ConstantOperator.createDatetime(LocalDateTime.of(2019, 8, 1, 13, 21, 3));
assertEquals("2019-07-31T22:21:03",
ScalarOperatorFunctions.convert_tz(olddt,
ConstantOperator.createVarchar("Asia/Shanghai"),
... |
@Override
public Connection getConnection() throws SQLException {
Connection connection = dataSource.getConnection();
return getConnectionProxy(connection);
} | @Test
public void testGetConnection() throws SQLException {
// Mock
Driver driver = Mockito.mock(Driver.class);
JDBC4MySQLConnection connection = Mockito.mock(JDBC4MySQLConnection.class);
Mockito.when(connection.getAutoCommit()).thenReturn(true);
DatabaseMetaData metaData = M... |
@Override
public void handlerPlugin(final PluginData pluginData) {
if (null != pluginData && pluginData.getEnabled()) {
SofaRegisterConfig sofaRegisterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), SofaRegisterConfig.class);
if (Objects.isNull(sofaRegisterConfig)) ... | @Test
public void testPluginEnable() {
PluginData pluginData = new PluginData("", "", registryConfig, "1", true, null);
sofaPluginDataHandler.handlerPlugin(pluginData);
assertEquals("127.0.0.1:2181", Singleton.INST.get(SofaRegisterConfig.class).getRegister());
} |
@Override
public V fetch(final K key,
final long time) {
return getValueOrNull(inner.fetch(key, time));
} | @Test
public void shouldReturnPlainKeyValuePairsOnSingleKeyFetchLongParameters() {
when(mockedWindowTimestampIterator.next())
.thenReturn(KeyValue.pair(21L, ValueAndTimestamp.make("value1", 22L)))
.thenReturn(KeyValue.pair(42L, ValueAndTimestamp.make("value2", 23L)));
when(mo... |
@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException {
final byte[] digest = this.digest("SHA-256", this.normalize(in, status), status);
return new Checksum(HashAlgorithm.sha256, digest);
} | @Test
public void testNormalize() throws Exception {
assertEquals("c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20",
new SHA256ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()),
new TransferStatus()).hash);
assertEquals("c... |
public static long getMapSize(byte zoomLevel, int tileSize) {
if (zoomLevel < 0) {
throw new IllegalArgumentException("zoom level must not be negative: " + zoomLevel);
}
return (long) tileSize << zoomLevel;
} | @Test
public void getMapSizeTest() {
for (int tileSize : TILE_SIZES) {
for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) {
long factor = Math.round(MercatorProjection.zoomLevelToScaleFactor(zoomLevel));
Assert.assertEquals(tileSize * ... |
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof RollbackRule)) {
return false;
}
RollbackRule rhs = (RollbackRule) other;
return this.exceptionName.equals(rhs.exceptionName);
} | @Test
public void equalsTest(){
RollbackRule otherRollbackRuleByName = new RollbackRule(Exception.class.getName());
RollbackRule otherRollbackRuleByName2 = new NoRollbackRule(Exception.class.getName());
Assertions.assertNotEquals("", otherRollbackRuleByName.getExceptionName());
Asse... |
public SearchQuery parse(String encodedQueryString) {
if (Strings.isNullOrEmpty(encodedQueryString) || "*".equals(encodedQueryString)) {
return new SearchQuery(encodedQueryString);
}
final var queryString = URLDecoder.decode(encodedQueryString, StandardCharsets.UTF_8);
fina... | @Test
void fieldPrefixIsAddedToAllFieldsIfSpecified() {
final SearchQueryParser parser = new SearchQueryParser("name", ImmutableSet.of("name", "breed"), "pets.");
final SearchQuery searchQuery = parser.parse("Bobby breed:terrier");
final Multimap<String, SearchQueryParser.FieldValue> queryM... |
public String expand(final String remote) {
return this.expand(remote, PREFIX);
} | @Test
public void testExpand() {
final String expanded = new TildePathExpander(new Path("/home/jenkins", EnumSet.of(Path.Type.directory)))
.expand("~/f", "~/");
assertEquals("/home/jenkins/f", expanded);
} |
@Override
public void stop() throws Exception {
if (!running) {
return;
}
running = false;
LOG.info("Stopping ZooKeeperJobGraphStoreWatcher ");
pathCache.close();
} | @Test
void testJobGraphAddedAndRemovedShouldNotifyGraphStoreListener() throws Exception {
try (final CuratorFrameworkWithUnhandledErrorListener curatorFrameworkWrapper =
ZooKeeperUtils.startCuratorFramework(
configuration, NoOpFatalErrorHandler.INSTANCE)) {
... |
public static KMeans fit(double[][] data, int k) {
return fit(data, k, 100, 1E-4);
} | @Test
public void testBBD64() {
System.out.println("BBD 64");
MathEx.setSeed(19650218); // to get repeatable results.
KMeans model = KMeans.fit(x, 64);
System.out.println(model);
double r = RandIndex.of(y, model.y);
double r2 = AdjustedRandIndex.of(y, model.y);
... |
@Override
public PageData<Customer> findByTenantId(UUID tenantId, PageLink pageLink) {
return findCustomersByTenantId(tenantId, pageLink);
} | @Test
public void testFindByTenantId() {
UUID tenantId1 = Uuids.timeBased();
UUID tenantId2 = Uuids.timeBased();
for (int i = 0; i < 20; i++) {
createCustomer(tenantId1, i);
createCustomer(tenantId2, i * 2);
}
PageLink pageLink = new PageLink(15, 0, ... |
@Override
public void removeProject(Project project) {
synchronized (this) {
if (projects.getCurrentProject() == project) {
closeCurrentProject();
}
projects.removeProject((ProjectImpl) project);
}
} | @Test
public void testRemoveProject() {
ProjectControllerImpl pc = new ProjectControllerImpl();
pc.addProjectListener(projectListener);
Project project = pc.newProject();
pc.removeProject(project);
Assert.assertFalse(pc.hasCurrentProject());
Assert.assertTrue(pc.getAl... |
public Optional<VoterSet> addVoter(VoterNode voter) {
if (voters.containsKey(voter.voterKey().id())) {
return Optional.empty();
}
HashMap<Integer, VoterNode> newVoters = new HashMap<>(voters);
newVoters.put(voter.voterKey().id(), voter);
return Optional.of(new Voter... | @Test
void testAddVoter() {
Map<Integer, VoterSet.VoterNode> aVoterMap = voterMap(IntStream.of(1, 2, 3), true);
VoterSet voterSet = VoterSet.fromMap(new HashMap<>(aVoterMap));
assertEquals(Optional.empty(), voterSet.addVoter(voterNode(1, true)));
VoterSet.VoterNode voter4 = voterNo... |
@Benchmark
@Threads(16) // Use several threads since we expect contention during logging
public void testSkippedLogging(ZeroExpectedCallsLoggingClientAndService client) {
LOG.trace("no log");
} | @Test
public void testSkippedLogging() throws Exception {
ZeroExpectedCallsLoggingClientAndService service =
new ZeroExpectedCallsLoggingClientAndService();
new BeamFnLoggingClientBenchmark().testSkippedLogging(service);
service.tearDown();
} |
@Override
public void putJobGraph(JobGraph jobGraph) throws Exception {
checkNotNull(jobGraph, "Job graph");
final JobID jobID = jobGraph.getJobID();
final String name = jobGraphStoreUtil.jobIDToName(jobID);
LOG.debug("Adding job graph {} to {}.", jobID, jobGraphStateHandleStore);
... | @Test
public void testPutJobGraphWhenNotExist() throws Exception {
final CompletableFuture<JobGraph> addFuture = new CompletableFuture<>();
final TestingStateHandleStore<JobGraph> stateHandleStore =
builder.setExistsFunction(ignore -> IntegerResourceVersion.notExisting())
... |
public static boolean splitKeyRangeContains(
Object[] key, Object[] splitKeyStart, Object[] splitKeyEnd) {
// for all range
if (splitKeyStart == null && splitKeyEnd == null) {
return true;
}
// first split
if (splitKeyStart == null) {
int[] upp... | @Test
public void testSplitKeyRangeContains() {
// table with only one split
assertKeyRangeContains(new Object[] {100L}, null, null);
// the last split
assertKeyRangeContains(new Object[] {101L}, new Object[] {100L}, null);
// the first split
assertKeyRangeContains(n... |
public Blade register(@NonNull Object bean) {
this.ioc.addBean(bean);
return this;
} | @Test
public void testRegister() {
Blade blade = Blade.create();
BladeClassDefineType object = new BladeClassDefineType();
blade.register(object);
assertEquals(object, blade.ioc().getBean(BladeClassDefineType.class));
} |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitStringStringTrueWithLeadingSplitChars() {
// Test leading split characters
assertThat("Ignore leading split chars", JOrphanUtils.split(",,a,bc", ",", true),
CoreMatchers.equalTo(new String[]{"a", "bc"}));
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleQualifiedSelectStarOnRightJoinSource() {
// Given:
final SingleStatementContext stmt =
givenQuery("SELECT TEST2.* FROM TEST1 JOIN TEST2 WITHIN 1 SECOND ON TEST1.ID = TEST2.ID;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
... |
@HighFrequencyInvocation
public boolean accept(final Grantee grantee) {
return grantee.username.equalsIgnoreCase(username) && isPermittedHost(grantee);
} | @Test
void assertAccept() {
Grantee grantee = new Grantee("name", "%");
assertTrue(grantee.accept(new Grantee("name", "")));
assertTrue(grantee.accept(new Grantee("name", "127.0.0.1")));
} |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test(description = "no NPE resolving map")
public void testTicket2793() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2793Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /distances:\n" +
... |
public static void validate(TableConfig tableConfig, @Nullable Schema schema) {
validate(tableConfig, schema, null);
} | @Test
public void testValidateFieldConfig() {
Schema schema = new Schema.SchemaBuilder().setSchemaName(TABLE_NAME)
.addDateTime(TIME_COLUMN, FieldSpec.DataType.LONG, "1:HOURS:EPOCH", "1:HOURS")
.addSingleValueDimension("myCol1", FieldSpec.DataType.STRING)
.addMultiValueDimension("myCol2", ... |
public String accessSecret(String secretVersion) {
checkArgument(!secretVersion.isEmpty(), "secretVersion can not be empty");
checkIsUsable();
try {
SecretVersionName secretVersionName;
if (SecretVersionName.isParsableFrom(secretVersion)) {
secretVersionName = SecretVersionName.parse(s... | @Test
public void testAccessSecretWithInvalidNameShouldFail() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> testManager.accessSecret(""));
assertThat(exception).hasMessageThat().contains("secretVersion can not be empty");
} |
public SalesforceUpsertMeta() {
super(); // allocate BaseStepMeta
} | @Test
public void testSalesforceUpsertMeta() throws KettleException {
List<String> attributes = new ArrayList<String>();
attributes.addAll( SalesforceMetaTest.getDefaultAttributes() );
attributes.addAll( Arrays.asList( "upsertField", "batchSize", "salesforceIDFieldName", "updateLookup",
"updateStrea... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void fabric0_12() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/fabric-version-0.12.txt")),
CrashReportAnalyzer.Rule.FABRIC_VERSION_0_12);
} |
public static <InputT extends PInput, OutputT extends POutput>
PTransform<InputT, OutputT> compose(SerializableFunction<InputT, OutputT> fn) {
return new PTransform<InputT, OutputT>() {
@Override
public OutputT expand(InputT input) {
return fn.apply(input);
}
};
} | @Test
public void testNamedCompose() {
PTransform<PCollection<Integer>, PCollection<Integer>> composed =
PTransform.compose("MyName", (PCollection<Integer> numbers) -> numbers);
assertEquals("MyName", composed.name);
} |
@Override
public void execute(Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void execute_whenAnalyzerChangedAndLanguageNotSupported_shouldSkipRaisingEvent() {
QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date());
mockLanguageInRepository(LANGUAGE_KEY_1);
when(measureRepository.getBaseMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optio... |
public static Object getValueOrCachedValue(Record record, SerializationService serializationService) {
Object cachedValue = record.getCachedValueUnsafe();
if (cachedValue == NOT_CACHED) {
//record does not support caching at all
return record.getValue();
}
for (; ... | @Test
public void getValueOrCachedValue_whenRecordIsNotCachable_thenDoNotCache() {
String objectPayload = "foo";
Data dataPayload = serializationService.toData(objectPayload);
Record record = new DataRecordWithStats(dataPayload);
Object value = Records.getValueOrCachedValue(record, n... |
@Override
@SuppressFBWarnings("PATH_TRAVERSAL_IN") // suppressing because we are using the getValidFilePath
public String getMimeType(String file) {
if (file == null || !file.contains(".")) {
return null;
}
String mimeType = null;
// may not work on Lambda until mai... | @Test
void getMimeType_nonExistentFileInTaskPath_expectNull() {
AwsServletContext ctx = new AwsServletContext(null);
assertNull(ctx.getMimeType("/var/task/nothing"));
} |
@Override
public PageData<WidgetsBundle> findAllTenantWidgetsBundlesByTenantId(WidgetsBundleFilter widgetsBundleFilter, PageLink pageLink) {
return findTenantWidgetsBundlesByTenantIds(Arrays.asList(widgetsBundleFilter.getTenantId().getId(), NULL_UUID), widgetsBundleFilter, pageLink);
} | @Test
public void testFindAllWidgetsBundlesByTenantIdFullSearch() {
UUID tenantId1 = Uuids.timeBased();
UUID tenantId2 = Uuids.timeBased();
for (int i = 0; i < 10; i++) {
createWidgetBundles(5, tenantId1, "WB1_" + i + "_");
createWidgetBundles(3, tenantId2, "WB2_" + i... |
public Set<String> topicCleanupPolicy(String topic) {
Config topicConfig = describeTopicConfig(topic);
if (topicConfig == null) {
// The topic must not exist
log.debug("Unable to find topic '{}' when getting cleanup policy", topic);
return Collections.emptySet();
... | @Test
public void verifyingGettingTopicCleanupPolicies() {
String topicName = "myTopic";
Map<String, String> topicConfigs = Collections.singletonMap("cleanup.policy", "compact");
Cluster cluster = createCluster(1);
try (MockAdminClient mockAdminClient = new MockAdminClient(cluster.no... |
public static <T> T getLast(List<T> list) {
if (isEmpty(list)) {
return null;
}
int size;
while (true) {
size = list.size();
if (size == 0) {
return null;
}
try {
return list.get(size - 1);
... | @Test
public void test_getLast() {
// case 1: null
Assertions.assertNull(CollectionUtils.getLast(null));
// case 2: empty
List<String> emptyList = Collections.EMPTY_LIST;
Assertions.assertNull(CollectionUtils.getLast(emptyList));
// case 3: not empty
List<St... |
@Override
public Optional<Track<T>> clean(Track<T> track) {
NavigableSet<Point<T>> points = newTreeSet(track.points());
Set<Point<T>> badPoints = findPointsWithoutEnoughTimeSpacing(track);
points.removeAll(badPoints);
return (points.isEmpty())
? Optional.empty()
... | @Test
public void testCleaningExample2() {
Track<NopHit> testTrack = createTrackFromResource(
HighFrequencyPointRemover.class,
"highFrequencyPoints_example2.txt"
);
Duration MIN_ALLOWABLE_SPACING = Duration.ofMillis(500);
DataCleaner<Track<NopHit>> smoother... |
static String generateDatabaseName(String baseString) {
return generateResourceId(
baseString,
ILLEGAL_DATABASE_NAME_CHARS,
REPLACE_DATABASE_NAME_CHAR,
MAX_DATABASE_NAME_LENGTH,
TIME_FORMAT);
} | @Test
public void testGenerateDatabaseNameShouldReplaceSpace() {
String testBaseString = "Test DB Name";
String actual = generateDatabaseName(testBaseString);
assertThat(actual).matches("test-db-name-\\d{8}-\\d{6}-\\d{6}");
} |
int freeIps(Node host) {
if (host.type() == NodeType.host) {
return allNodes.eventuallyUnusedIpAddressCount(host);
}
return host.ipConfig().pool().findUnusedIpAddresses(allNodes).size();
} | @Test
public void freeIPs() {
assertEquals(2, capacity.freeIps(host1));
assertEquals(1, capacity.freeIps(host2));
assertEquals(1, capacity.freeIps(host3));
assertEquals(0, capacity.freeIps(host4));
} |
@Override public V get(Object o) {
if (o == null) return null; // null keys are not allowed
int i = arrayIndexOfKey(o);
return i != -1 ? value(i + 1) : null;
} | @Test void mapKeys() {
array[0] = " 1";
array[1] = "one";
array[2] = "2 ";
array[3] = "two";
array[4] = " 3";
array[5] = "three";
Map<String, String> map = builder.mapKeys(o -> ((String) o).trim()).build(array);
assertSize(map, 3);
assertBaseCase(map);
assertThat(map).containsO... |
protected TransformerInput buildTransformerInput(List<Long> tokens, int maxTokens, boolean isQuery) {
if (!isQuery) {
tokens = tokens.stream().filter(token -> !skipTokens.contains(token)).toList();
}
List<Long> inputIds = new ArrayList<>(maxTokens);
List<Long> attentionMask =... | @Test
public void testInputTensorsSentencePiece() {
// Sentencepiece tokenizer("this is a query !") -> [903, 83, 10, 41, 1294, 711]
// ! is mapped to 711 and is a punctuation character
List<Long> tokens = List.of(903L, 83L, 10L, 41L, 1294L, 711L);
ColBertEmbedder.TransformerInput inp... |
public Mono<Void> createStreamAppAcl(KafkaCluster cluster, CreateStreamAppAclDTO request) {
return adminClientService.get(cluster)
.flatMap(ac -> createAclsWithLogging(ac, createStreamAppBindings(request)))
.then();
} | @Test
void createsStreamAppDependantAcls() {
ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class);
when(adminClientMock.createAcls(createdCaptor.capture()))
.thenReturn(Mono.empty());
var principal = UUID.randomUUID().toString();
var host = UUID.ran... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldAlterTable() {
// Given:
alterSource = new AlterSourceCommand(EXISTING_TABLE, DataSourceType.KTABLE.getKsqlType(), NEW_COLUMNS);
// When:
final DdlCommandResult result = cmdExec.execute(SQL_TEXT, alterSource, false, NO_QUERY_SOURCES);
// Then:
assertThat(result.isSucc... |
@Override
public UrlPattern doGetPattern() {
return UrlPattern.builder()
.includes(MOVED_WEB_SERVICES)
.build();
} | @Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern().matches("/api/components/update_key")).isTrue();
assertThat(underTest.doGetPattern().matches("/api/components/bulk_update_key")).isTrue();
assertThat(underTest.doGetPattern().matches("/api/projects/update_key")).isFalse();
} |
public static TaskAndAction createRemoveTask(final TaskId taskId,
final CompletableFuture<StateUpdater.RemovedTaskResult> future) {
Objects.requireNonNull(taskId, "Task ID of task to remove is null!");
Objects.requireNonNull(future, "Future for task to re... | @Test
public void shouldThrowIfRemoveTaskActionIsCreatedWithNullFuture() {
final Exception exception = assertThrows(
NullPointerException.class,
() -> createRemoveTask(new TaskId(0, 0), null)
);
assertTrue(exception.getMessage().contains("Future for task to remove is ... |
@SuppressWarnings({"unchecked", "UnstableApiUsage"})
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement) {
if (!(statement.getStatement() instanceof DropStatement)) {
return statement;
}
final DropStatement dropStatement = (DropState... | @Test
public void shouldDeleteAvroSchemaInSR() throws IOException, RestClientException {
// Given:
when(topic.getKeyFormat()).thenReturn(KeyFormat.of(FormatInfo.of(FormatFactory.AVRO.name()), SerdeFeatures.of(), Optional.empty()));
when(topic.getValueFormat()).thenReturn(ValueFormat.of(FormatInfo.of(Forma... |
public boolean shouldUpdateRoot() {
return updateRoot;
} | @Test
public void testUpdateRoot() {
final DistCpOptions options = new DistCpOptions.Builder(
Collections.singletonList(
new Path("hdfs://localhost:8020/source")),
new Path("hdfs://localhost:8020/target/"))
.withUpdateRoot(true)
.build();
Assert.assertTrue(options.s... |
long getNodeResultLimit(int ownedPartitions) {
return isQueryResultLimitEnabled ? (long) ceil(resultLimitPerPartition * ownedPartitions) : Long.MAX_VALUE;
} | @Test
public void testNodeResultLimitThreePartitions() {
initMocksWithConfiguration(200000, 3);
assertEquals(2547, limiter.getNodeResultLimit(3));
} |
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) );
}
... | @Test
public void testGetLegacyColumnNameDriverLessOrEqualToThreeFieldContactLastName() throws Exception {
DatabaseMetaData databaseMetaData = mock( DatabaseMetaData.class );
doReturn( 3 ).when( databaseMetaData ).getDriverMajorVersion();
assertEquals( "CONTACTLASTNAME", new MySQLDatabaseMeta().getLegacy... |
public T run() throws Exception {
try {
return execute();
} catch(Exception e) {
if (e.getClass().equals(retryExceptionType)){
tries++;
if (MAX_RETRIES == tries) {
throw e;
} else {
return run();
}
} else {
throw e;
}
}
} | @Test
public void testRetrySuccess() {
Retry<Void> retriable = new Retry<Void>(NullPointerException.class) {
private int count = 0;
@Override
public Void execute() {
if (count < 1) {
count++;
throw new NullPointerException();
} else {
return null;
... |
public Page<Organization> getAllOrganizations(int pageIndex, int pageSize) {
return organizationRepository.findAll(PageRequest.of(pageIndex, pageSize));
} | @Test
public void getAllOrganizations() {
when(repositoryMock.findAll(any(Pageable.class))).thenReturn(getPageOrganizations());
Page<Organization> result = organizationServiceMock.getAllOrganizations(1, 10);
verify(repositoryMock, times(1)).findAll(any(Pageable.class));
assertNotNu... |
boolean isInsideClosedOpen(Number toEvaluate) {
if (leftMargin == null) {
return toEvaluate.doubleValue() < rightMargin.doubleValue();
} else if (rightMargin == null) {
return toEvaluate.doubleValue() >= leftMargin.doubleValue();
} else {
return toEvaluate.dou... | @Test
void isInsideClosedOpen() {
KiePMMLInterval kiePMMLInterval = new KiePMMLInterval(null, 20, CLOSURE.CLOSED_OPEN);
assertThat(kiePMMLInterval.isInsideClosedOpen(10)).isTrue();
assertThat(kiePMMLInterval.isInsideClosedOpen(20)).isFalse();
assertThat(kiePMMLInterval.isInsideClosed... |
@Override
public String getMessage()
{
String message = super.getMessage();
if (message == null && getCause() != null) {
message = getCause().getMessage();
}
if (message == null) {
message = errorCode.getName();
}
return message;
} | @Test
public void testMessage()
{
PrestoException exception = new PrestoException(new TestErrorCode(), "test");
assertEquals(exception.getMessage(), "test");
exception = new PrestoException(new TestErrorCode(), new RuntimeException("test2"));
assertEquals(exception.getMessage(),... |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherVal... | @Test
void assertCompareToStringWithCaseInsensitive() {
assertThat(CompareUtils.compareTo("A", "a", OrderDirection.DESC, NullsOrderType.FIRST, !caseSensitive), is(0));
} |
@Override
public ServiceInfo queryInstancesOfService(String serviceName, String groupName, String clusters,
boolean healthyOnly) throws NacosException {
ServiceQueryRequest request = new ServiceQueryRequest(namespaceId, serviceName, groupName);
request.setCluster(clusters);
reque... | @Test
void testQueryInstancesOfService() throws Exception {
QueryServiceResponse res = new QueryServiceResponse();
ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS);
res.setServiceInfo(info);
when(this.rpcClient.request(any())).thenReturn(res);
... |
@Override
public boolean isInputConsumable(
SchedulingExecutionVertex executionVertex,
Set<ExecutionVertexID> verticesToDeploy,
Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) {
for (ConsumedPartitionGroup consumedPartitionGroup :
executionVert... | @Test
void testPartialFinishedBlockingInput() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
final List<TestingSchedulingExecutionVertex> producers =
topology.addExecutionVertices().withParallelism(2).finish();
final List<TestingSchedulingExec... |
public boolean isDisabled() {
return _disabled;
} | @Test
public void withEmptyConf()
throws JsonProcessingException {
String confStr = "{}";
IndexConfig config = JsonUtils.stringToObject(confStr, IndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
} |
@Override
public void stop() {
LOG.debug("Notify {} handlers...", ServerStopHandler.class.getSimpleName());
for (ServerStopHandler handler : stopHandlers) {
handler.onServerStop(server);
}
} | @Test
public void notifyOnStop() {
ServerLifecycleNotifier notifier = new ServerLifecycleNotifier(server, new ServerStartHandler[] {start1, start2}, new ServerStopHandler[] {stop1, stop2});
notifier.stop();
verify(start1, never()).onServerStart(server);
verify(start2, never()).onServerStart(server);
... |
@Nullable public static BaggageField getByName(@Nullable TraceContext context, String name) {
if (context == null) return null;
return ExtraBaggageContext.getFieldByName(context, validateName(name));
} | @Test void getByName_context_null() {
// permits unguarded use of CurrentTraceContext.get()
assertThat(BaggageField.getByName((TraceContext) null, "foo"))
.isNull();
} |
public HeaderFields getUntreatedHeaders() {
return untreatedHeaders;
} | @Test
void testGetUntreatedHeaders() {
URI uri = URI.create("http://example.yahoo.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
httpReq.headers().add("key1", "value1");
httpReq.headers().add("key2", List.of("value1", "value2"... |
public void lockClusterState(ClusterStateChange stateChange, Address initiator, UUID txnId, long leaseTime,
int memberListVersion, long partitionStateStamp) {
Preconditions.checkNotNull(stateChange);
clusterServiceLock.lock();
try {
if (!node.getNodeE... | @Test
public void test_lockClusterState_success() throws Exception {
Address initiator = newAddress();
clusterStateManager.lockClusterState(ClusterStateChange.from(FROZEN), initiator, TXN, 1000, MEMBERLIST_VERSION,
PARTITION_STAMP);
assertLockedBy(initiator);
} |
@Override
public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Er... | @Test
public void testHeartbeatSuccessfulResponseWhenLeavingGroupCompletesLeave() {
ConsumerMembershipManager membershipManager = createMemberInStableState();
mockLeaveGroup();
CompletableFuture<Void> leaveResult = membershipManager.leaveGroup();
verify(subscriptionState).unsubscrib... |
@SuppressWarnings("unchecked")
public T getValue() {
final T value = (T) FROM_STRING.get(getConverterClass()).apply(JiveGlobals.getProperty(key), this);
if (value == null || (Collection.class.isAssignableFrom(value.getClass()) && ((Collection) value).isEmpty())) {
return defaultValue;
... | @Test
public void willCreateAnInstantPropertyWithADefaultValue() {
final String key = "test.instant.property.with.default";
final Instant defaultValue = Instant.now().truncatedTo(ChronoUnit.MILLIS);
final SystemProperty<Instant> property = SystemProperty.Builder.ofType(Instant.class)
... |
@Override
public Optional<WindowType> windowType() {
return inner.windowType();
} | @Test
public void shouldReturnInnerWindowType() {
// Given:
when(inner.windowType()).thenReturn(Optional.of(WindowType.SESSION));
givenNoopTransforms();
// When:
final Optional<WindowType> windowType = materialization.windowType();
// Then:
assertThat(windowType, is(Optional.of(WindowTyp... |
@Nonnull
public MappingResults applyToPrimaryResource(@Nonnull Mappings mappings) {
mappings = enrich(mappings);
WorkspaceResource resource = workspace.getPrimaryResource();
MappingResults results = new MappingResults(mappings, listeners.createBundledMappingApplicationListener())
.withAggregateManager(aggre... | @Test
void applyOverlapping() {
String overlapInterfaceAName = OverlapInterfaceA.class.getName().replace('.', '/');
String overlapInterfaceBName = OverlapInterfaceB.class.getName().replace('.', '/');
String overlapClassABName = OverlapClassAB.class.getName().replace('.', '/');
String overlapCallerName = Overla... |
@Override public SlotAssignmentResult ensure(long key1, long key2) {
assert key1 != unassignedSentinel : "ensure() called with key1 == nullKey1 (" + unassignedSentinel + ')';
return super.ensure0(key1, key2);
} | @Test
public void testCursor_valueAddress() {
final SlotAssignmentResult slot = hsa.ensure(randomKey(), randomKey());
HashSlotCursor16byteKey cursor = hsa.cursor();
cursor.advance();
assertEquals(slot.address(), cursor.valueAddress());
} |
public byte[] getAuthenticationPluginData() {
return Bytes.concat(authenticationPluginDataPart1, authenticationPluginDataPart2);
} | @Test
void assertGetAuthPluginDataWithoutArguments() {
MySQLAuthenticationPluginData actual = new MySQLAuthenticationPluginData();
assertThat(actual.getAuthenticationPluginDataPart1().length, is(8));
assertThat(actual.getAuthenticationPluginDataPart2().length, is(12));
assertThat(act... |
@Override
public String processLink(String link) {
var externalLink = externalUrlSupplier.getRaw();
if (StringUtils.isBlank(link)) {
return link;
}
if (externalLink == null || !linkInSite(externalLink, link)) {
return link;
}
return append(ext... | @Test
void processWhenLinkIsEmpty() {
assertThat(externalLinkProcessor.processLink(null)).isNull();
assertThat(externalLinkProcessor.processLink("")).isEmpty();
} |
public static double of(double[] truth, double[] prediction) {
if (truth.length != prediction.length) {
throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, prediction.length));
}
double RSS = 0.0;
double TSS = 0.0;
... | @Test
public void test() {
System.out.println("R2");
double[] truth = {
83.0, 88.5, 88.2, 89.5, 96.2, 98.1, 99.0, 100.0, 101.2,
104.6, 108.4, 110.8, 112.6, 114.2, 115.7, 116.9
};
double[] prediction = {
83.60082, 86.94973, 88.096... |
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
if (registryAttr inst... | @Test(expected = ServletException.class)
public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception {
final ServletContext servletContext = mock(ServletContext.class);
final ServletConfig servletConfig = mock(ServletConfig.class);
when(serv... |
public List<NotificationChannel> getChannels() {
return Arrays.asList(channels);
} | @Test
public void shouldReturnChannels() {
assertThat(underTest.getChannels()).containsOnly(emailChannel, gtalkChannel);
} |
private String getUpstreamIpFromHttpDomain() {
String domain = (String) exchange.getAttributes().get(Constants.HTTP_DOMAIN);
try {
if (StringUtils.isNotBlank(domain)) {
URL url = new URL(domain);
return url.getHost();
}
} catch (Exception e... | @Test
public void testGetUpstreamIpFromHttpDomain() throws Exception {
exchange.getAttributes().put(Constants.HTTP_DOMAIN, "http://localhost:9195/http/order/path/123/name");
loggingServerHttpResponse.setExchange(exchange);
Method method1 = loggingServerHttpResponse.getClass().getDeclaredMeth... |
@Udf
public String lpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnNullForNullPaddingBytes() {
final ByteBuffer result = udf.lpad(BYTES_123, 4, null);
assertThat(result, is(nullValue()));
} |
public static Pagination pageStartingAt(Integer offset, Integer total, Integer pageSize) {
return new Pagination(offset, total, pageSize);
} | @Test
public void shouldCreatePaginationWithLessEquals300Records() {
try {
Pagination.pageStartingAt(0, 1000, 300);
} catch (Exception e) {
fail();
}
} |
@Deprecated
@Override
public void trackTimer(final String eventName, final TimeUnit timeUnit) {
} | @Test
public void trackTimer() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
... |
public static RunnerApi.Pipeline toProto(Pipeline pipeline) {
return toProto(pipeline, SdkComponents.create(pipeline.getOptions()));
} | @Test
public void testProtoDirectly() {
final RunnerApi.Pipeline pipelineProto = PipelineTranslation.toProto(pipeline, false);
pipeline.traverseTopologically(
new PipelineProtoVerificationVisitor(pipelineProto, pipeline.getCoderRegistry(), false));
} |
@Override
public void registerBeanDefinitions(final AnnotationMetadata metadata, final BeanDefinitionRegistry registry) {
registerShenyuClients(metadata, registry);
} | @Test
public void registerBeanDefinitionsTest() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
final ShenyuSdkClient client = spy(ShenyuSdkClient.class);
((DefaultListableBeanFactory) context.getBeanFactory()).setAllowBeanDefinitionOverriding(false);... |
public static ThreadFactory namedThreads(String pattern) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern)
.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
.build();
} | @Test
public void exceptionHandler() throws InterruptedException {
ThreadFactory f = Tools.namedThreads("foo");
Thread t = f.newThread(() -> {
throw new IllegalStateException("BOOM!");
});
assertNotNull("thread should have exception handler", t.getUncaughtExceptionHandler... |
public static long computeStartOfNextHour(long now) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(now));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.add(Calendar.HOUR, 1);
return cal.getTime().get... | @Test
public void testHour() {
// Mon Nov 20 18:05:17,522 GMT 2006
long now = 1164045917522L;
now = correctBasedOnTimeZone(now);
// Mon Nov 20 19:00:00 GMT 2006
long expected = 1164049200000L;
expected = correctBasedOnTimeZone(expected);
long computed = TimeU... |
@Override
public void eventAdded( KettleLoggingEvent event ) {
Object messageObject = event.getMessage();
checkNotNull( messageObject, "Expected log message to be defined." );
if ( messageObject instanceof LogMessage ) {
LogMessage message = (LogMessage) messageObject;
LoggingObjectInterface l... | @Test
public void testAddLogEventNoRegisteredLogObject() {
listener.eventAdded( logEvent );
verify( diLogger ).info( messageSub + " " + msgText );
when( message.getLevel() ).thenReturn( ERROR );
listener.eventAdded( logEvent );
verify( diLogger ).error( messageSub + " " + msgText );
verifyNoI... |
public static Object getNestedFieldVal(GenericRecord record, String fieldName, boolean returnNullIfNotFound, boolean consistentLogicalTimestampEnabled) {
String[] parts = fieldName.split("\\.");
GenericRecord valueNode = record;
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
O... | @Test
public void testGetNestedFieldValWithDecimalField() {
GenericRecord rec = new GenericData.Record(new Schema.Parser().parse(SCHEMA_WITH_DECIMAL_FIELD));
rec.put("key_col", "key");
BigDecimal bigDecimal = new BigDecimal("1234.5678");
ByteBuffer byteBuffer = ByteBuffer.wrap(bigDecimal.unscaledValue... |
@Override
public SubmitApplicationResponse submitApplication(
SubmitApplicationRequest request) throws YarnException, IOException {
if (request == null || request.getApplicationSubmissionContext() == null
|| request.getApplicationSubmissionContext().getApplicationId() == null) {
routerMetrics... | @Test
public void testSubmitApplication()
throws YarnException, IOException {
LOG.info("Test FederationClientInterceptor: Submit Application.");
ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1);
SubmitApplicationRequest request = mockSubmitApplicationRequest(appId);
... |
public static String followGoogleRedirectIfNeeded(final String url) {
// If the url is a redirect from a Google search, extract the actual URL
try {
final URL decoded = stringToURL(url);
if (decoded.getHost().contains("google") && decoded.getPath().equals("/url")) {
... | @Test
void testFollowGoogleRedirect() {
assertEquals("https://www.youtube.com/watch?v=Hu80uDzh8RY",
Utils.followGoogleRedirectIfNeeded("https://www.google.it/url?sa=t&rct=j&q=&esrc=s&cd=&cad=rja&uact=8&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHu80uDzh8RY&source=video"));
asser... |
public static int getIdleTimeout(URL url) {
int heartBeat = getHeartbeat(url);
// idleTimeout should be at least more than twice heartBeat because possible retries of client.
int idleTimeout = url.getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3);
if (idleTimeout < heartBeat *... | @Test
void testGetIdleTimeout() {
URL url1 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000");
URL url2 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=50000");
URL url3 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=10000");
A... |
@Override
public void setConf(Configuration conf) {
if (conf != null) {
conf = addSecurityConfiguration(conf);
}
super.setConf(conf);
} | @Test
public void testFailoverWithInvalidFenceArg() throws Exception {
Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus();
HdfsConfiguration conf = getHAConf();
conf.set(DFSConfigKeys.DFS_HA_FENCE_METHODS_KEY, getFencerTrueCommand());
tool.setConf(conf);
assertEquals(-1, ... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
return toProtobuf(ManagementFactory.getMemoryMXBean());
} | @Test
public void toSystemInfoSection() {
JvmStateSection underTest = new JvmStateSection(PROCESS_NAME);
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThat(section.getName()).isEqualTo(PROCESS_NAME);
assertThat(section.getAttributesCount()).isPositive();
assertThat(section.ge... |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void testMetadataVersionMatchesKafkaVersionWithLongVersion() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withVersion(KafkaVersionTestUtils.LATEST_KAFKA_VERSION)
.withMetadataVersion(KafkaVe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.