focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Iterable<K> loadAllKeys() {
// If loadAllKeys property is disabled, don't load anything
if (!genericMapStoreProperties.loadAllKeys) {
return Collections.emptyList();
}
awaitSuccessfulInit();
String sql = queries.loadAllKeys();
SqlResult ... | @Test
public void givenRowAndIdColumn_whenLoadAllKeys_thenReturnKeys() {
ObjectSpec spec = objectProvider.createObject(mapName, true);
objectProvider.insertItems(spec, 1);
Properties properties = new Properties();
properties.setProperty(DATA_CONNECTION_REF_PROPERTY, TEST_DATABASE_RE... |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvWithSingleComma() {
CharSequence value = ",";
CharSequence expected = "\",\"";
escapeCsv(value, expected);
} |
@Override
public Boolean authenticate(final Host bookmark, final LoginCallback callback, final CancelCallback cancel)
throws BackgroundException {
final Credentials credentials = bookmark.getCredentials();
if(StringUtils.isBlank(credentials.getPassword())) {
final Credentials... | @Test(expected = LoginFailureException.class)
public void testAuthenticateFailure() throws Exception {
// Reconnect
session.disconnect();
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback());
session.getHost... |
@Override
public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment,
InstancePartitions instancePartitions, InstancePartitionsType instancePartitionsType) {
validateSegmentAssignmentStrategy(instancePartitions);
return SegmentAssignmentUtils.assignSegmentWi... | @Test
public void testTableBalanced() {
Map<String, Map<String, String>> currentAssignment = new TreeMap<>();
for (String segmentName : SEGMENTS) {
List<String> instancesAssigned =
_segmentAssignment.assignSegment(segmentName, currentAssignment, _instancePartitionsMap);
currentAssignment... |
public static KafkaPool fromCrd(
Reconciliation reconciliation,
Kafka kafka,
KafkaNodePool pool,
NodeIdAssignment idAssignment,
Storage oldStorage,
OwnerReference ownerReference,
SharedEnvironmentProvider sharedEnvironmentProvider
)... | @Test
public void testKafkaPoolConfigureOptionsThroughPoolSpec() {
KafkaNodePool pool = new KafkaNodePoolBuilder(POOL)
.editSpec()
.withResources(new ResourceRequirementsBuilder().withRequests(Map.of("cpu", new Quantity("4"), "memory", new Quantity("16Gi"))).build())
... |
PartitionRegistration getPartition(Uuid topicId, int partitionId) {
TopicControlInfo topic = topics.get(topicId);
if (topic == null) {
return null;
}
return topic.parts.get(partitionId);
} | @Test
public void testEligibleLeaderReplicas_CleanElection() {
ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder()
.setIsElrEnabled(true)
.build();
ReplicationControlManager replicationControl = ctx.replicationControl;
ctx.registerBrokers(0... |
@Nonnull
@Override
public Sketch<IntegerSummary> getResult() {
return unionAll();
} | @Test
public void testAccumulatorWithSingleSketch() {
IntegerSketch input = new IntegerSketch(_lgK, IntegerSummary.Mode.Sum);
IntStream.range(0, 1000).forEach(i -> input.update(i, 1));
CompactSketch<IntegerSummary> sketch = input.compact();
TupleIntSketchAccumulator accumulator = new TupleIntSketchAc... |
@Config("functions")
@ConfigDescription("A comma-separated list of ignored functions")
public IgnoredFunctionsMismatchResolverConfig setFunctions(String functions)
{
if (functions != null) {
this.functions = Splitter.on(",").trimResults().splitToList(functions).stream()
... | @Test
public void testDefault()
{
assertRecordedDefaults(recordDefaults(IgnoredFunctionsMismatchResolverConfig.class)
.setFunctions(null));
} |
public static Optional<KiePMMLModel> getFromCommonDataAndTransformationDictionaryAndModelWithSourcesCompiled(final CompilationDTO compilationDTO) {
logger.trace("getFromCommonDataAndTransformationDictionaryAndModelWithSourcesCompiled {}", compilationDTO);
final Function<ModelImplementationProvider<Model... | @Test
void getFromCommonDataAndTransformationDictionaryAndModelWithSourcesCompiledWithProvider() throws Exception {
pmml = getPMMLWithMiningRandomTestModel();
MiningModel parentModel = (MiningModel) pmml.getModels().get(0);
Model model = parentModel.getSegmentation().getSegments().get(0).get... |
public static Object extractValue(Object object, String attributeName, boolean failOnMissingAttribute) throws Exception {
return createGetter(object, attributeName, failOnMissingAttribute).getValue(object);
} | @Test
public void extractValue_whenIntermediateFieldIsInterfaceAndDoesNotContainField_thenThrowIllegalArgumentException()
throws Exception {
OuterObject object = new OuterObject();
try {
ReflectionHelper.extractValue(object, "emptyInterface.doesNotExist", true);
f... |
public static String stripSpaces(String str) {
StringBuilder ret = new StringBuilder();
boolean inQuotes = false;
boolean inSpaceSequence = false;
for (char c : str.toCharArray()) {
if (Character.isWhitespace(c)) {
if (inQuotes) {
ret.appen... | @Test
public void testStripSpaces() {
assertEquals("a b", ConfigUtils.stripSpaces("a b"));
assertEquals("\"a b\"", ConfigUtils.stripSpaces("\"a b\""));
assertEquals("a b \"a b\"", ConfigUtils.stripSpaces("a b \"a b\""));
assertEquals("a b", ConfigUtils.stripSpaces("a b"... |
@Override
public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) {
return getDescriptionInHtml(rule)
.map(this::generateSections)
.orElse(emptySet());
} | @Test
public void parse_moved_noncompliant_code() {
when(rule.htmlDescription()).thenReturn(DESCRIPTION + RECOMMENTEDCODINGPRACTICE + NONCOMPLIANTCODE + SEE);
Set<RuleDescriptionSectionDto> results = generator.generateSections(rule);
Map<String, String> sectionKeyToContent = results.stream().collect(toM... |
@Override
public void moveTo(long position) throws IllegalArgumentException {
if (position < 0 || length() < position) {
throw new IllegalArgumentException("Position out of the bounds of the file!");
}
fp = position;
} | @Test
public void available() throws IOException {
int amount = 12;
ss.moveTo(text.length - amount);
assertEquals(amount, ss.availableExact());
} |
@CanIgnoreReturnValue
public Replacements add(Replacement replacement) {
return add(replacement, CoalescePolicy.REJECT);
} | @Test
public void zeroLengthRangeOverlaps() {
Replacements replacements = new Replacements();
replacements.add(Replacement.create(1, 1, "Something"));
Replacement around = Replacement.create(0, 2, "Around");
assertThrows(IllegalArgumentException.class, () -> replacements.add(around));
} |
@Override
public AppToken createAppToken(long appId, String privateKey) {
Algorithm algorithm = readApplicationPrivateKey(appId, privateKey);
LocalDateTime now = LocalDateTime.now(clock);
// Expiration period is configurable and could be greater if needed.
// See https://developer.github.com/apps/buil... | @Test
public void getApplicationJWTToken_throws_ISE_if_conf_is_not_complete() {
GithubAppConfiguration githubAppConfiguration = createAppConfiguration(false);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()))
.isInstanceOf(IllegalS... |
public ChannelFuture handshake(Channel channel, FullHttpRequest req) {
return handshake(channel, req, null, channel.newPromise());
} | @Test
public void testHandshakeForHttpRequestWithoutAggregator() {
EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestDecoder(), new HttpResponseEncoder());
WebSocketServerHandshaker serverHandshaker = newHandshaker("ws://example.com/chat",
... |
static public int convert(ILoggingEvent event) {
Level level = event.getLevel();
switch (level.levelInt) {
case Level.ERROR_INT:
return SyslogConstants.ERROR_SEVERITY;
case Level.WARN_INT:
return SyslogConstants.WARNING_SEVERITY;
case Level.INFO_INT:
return SyslogConstants.INFO_S... | @Test
public void smoke() {
assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity
.convert(createEventOfLevel(Level.TRACE)));
assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity
.convert(createEventOfLevel(Level.DEBUG)));
assertEquals(SyslogConstants.INFO_SEV... |
@Override
public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config)
throws InvalidRequestEventException {
// Expect the HTTP method and context to be populated. If they are not, we are handling an
// uns... | @Test
void readRequest_invalidEventEmptyMethod_expectException() {
try {
AwsProxyRequest req = new AwsProxyRequestBuilder("/path", null).build();
reader.readRequest(req, null, null, ContainerConfig.defaultConfig());
fail("Expected InvalidRequestEventException");
}... |
public void register() {
if (StringUtils.isEmpty(RegisterContext.INSTANCE.getClientInfo().getServiceId())) {
LOGGER.warning("No service to register for nacos client...");
return;
}
String serviceId = RegisterContext.INSTANCE.getClientInfo().getServiceId();
String ... | @Test
public void testRegister() throws NacosException {
mockNamingService();
nacosClient.register();
Assert.assertNotNull(ReflectUtils.getFieldValue(nacosClient, "instance"));
} |
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) {
if ( lists == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "lists", "cannot be null"));
}
final Set<Object> resultSet = new LinkedHashSet<>();
for ( final Obj... | @Test
void invokeEmptyArray() {
FunctionTestUtil.assertResultList(unionFunction.invoke(new Object[]{}), Collections.emptyList());
} |
public static boolean validateCSConfiguration(
final Configuration oldConfParam, final Configuration newConf,
final RMContext rmContext) throws IOException {
// ensure that the oldConf is deep copied
Configuration oldConf = new Configuration(oldConfParam);
QueueMetrics.setConfigurationVa... | @Test
public void testValidateCSConfigInvalidCapacity() {
Configuration oldConfig = CapacitySchedulerConfigGeneratorForTest
.createBasicCSConfiguration();
Configuration newConfig = new Configuration(oldConfig);
newConfig
.set("yarn.scheduler.capacity.root.test1.capacity", "500");
... |
@Override
@CacheEvict(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#id")
public void deleteMailAccount(Long id) {
// 校验是否存在账号
validateMailAccountExists(id);
// 校验是否存在关联模版
if (mailTemplateService.getMailTemplateCountByAccountId(id) > 0) {
throw exception(MAIL_ACCOUNT... | @Test
public void testDeleteMailAccount_success() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailAccount.getId();
// mock 方法(无关联模版)
when(mailTempl... |
@Override
public double score(int[] truth, int[] prediction) {
return of(truth, prediction, strategy);
} | @Test
public void testMacro() {
System.out.println("Macro-Precision");
int[] truth = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... |
public static KTableHolder<GenericKey> build(
final KGroupedStreamHolder groupedStream,
final StreamAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedStream,
aggregate,
buildContext,
... | @Test
public void shouldBuildSchemaCorrectlyForWindowedAggregate() {
// Given:
givenHoppingWindowedAggregate();
// When:
final KTableHolder<?> result = windowedAggregate.build(planBuilder, planInfo);
// Then:
assertThat(result.getSchema(), is(OUTPUT_SCHEMA));
} |
String getUrl() {
return "http://" + this.httpServer.getInetAddress().getHostAddress() + ":" + this.httpServer.getLocalPort();
} | @Test
public void action_is_matched_on_URL_with_parameters() throws IOException {
Response response = call(underTest.getUrl() + "/pompom?toto=2");
assertIsPomPomResponse(response);
} |
static int calcTimeoutMsRemainingAsInt(long now, long deadlineMs) {
long deltaMs = deadlineMs - now;
if (deltaMs > Integer.MAX_VALUE)
deltaMs = Integer.MAX_VALUE;
else if (deltaMs < Integer.MIN_VALUE)
deltaMs = Integer.MIN_VALUE;
return (int) deltaMs;
} | @Test
public void testCalcTimeoutMsRemainingAsInt() {
assertEquals(0, KafkaAdminClient.calcTimeoutMsRemainingAsInt(1000, 1000));
assertEquals(100, KafkaAdminClient.calcTimeoutMsRemainingAsInt(1000, 1100));
assertEquals(Integer.MAX_VALUE, KafkaAdminClient.calcTimeoutMsRemainingAsInt(0, Long.M... |
@Override
public Range<T> firstRange() {
return rangeSet.firstRange();
} | @Test
public void testFirstRange() {
set = new RangeSetWrapper<>(consumer, reverseConvert, managedCursor);
assertNull(set.firstRange());
set.addOpenClosed(0, 97, 0, 99);
assertEquals(set.firstRange(), Range.openClosed(new LongPair(0, 97), new LongPair(0, 99)));
assertEquals(s... |
@Override
public int deleteUndoLogByLogCreated(Date logCreated, int limitRows, Connection conn) throws SQLException {
return super.deleteUndoLogByLogCreated(logCreated, limitRows, conn);
} | @Test
public void testDeleteUndoLogByLogCreated() throws SQLException {
Assertions.assertEquals(0, undoLogManager.deleteUndoLogByLogCreated(new Date(), 3000, dataSource.getConnection()));
Assertions.assertDoesNotThrow(() -> undoLogManager.deleteUndoLogByLogCreated(new Date(), 3000, connectionProxy))... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testBank32nhLS() {
test(Loss.ls(), "bank32nh", Bank32nh.formula, Bank32nh.data, 0.0845);
} |
public double getLatitudeFromY01(final double pY01, boolean wrapEnabled) {
final double latitude = getLatitudeFromY01(wrapEnabled ? Clip(pY01, 0, 1) : pY01);
return wrapEnabled ? Clip(latitude, getMinLatitude(), getMaxLatitude()) : latitude;
} | @Test
public void testGetLatitudeFromY01() {
checkLatitude(tileSystem.getMaxLatitude(), tileSystem.getLatitudeFromY01(0, true));
checkLatitude(0, tileSystem.getLatitudeFromY01(0.5, true));
checkLatitude(tileSystem.getMinLatitude(), tileSystem.getLatitudeFromY01(1, true));
} |
public B group(String group) {
this.group = group;
return getThis();
} | @Test
void group() {
ServiceBuilder builder = new ServiceBuilder();
builder.group("group");
Assertions.assertEquals("group", builder.build().getGroup());
} |
public static <P> Builder<P> newBuilder() {
return new Builder<P>();
} | @Test void noRulesOk() {
ParameterizedSampler.<Boolean>newBuilder().build();
} |
@Override
public void upgrade() {
Optional<IndexSetTemplate> defaultIndexSetTemplate = indexSetDefaultTemplateService.getDefaultIndexSetTemplate();
if (defaultIndexSetTemplate.isEmpty()) {
IndexSetsDefaultConfiguration legacyDefaultConfig = clusterConfigService.get(IndexSetsDefaultConfig... | @Test
void testDefaultConfigWithDataTieringAndUseLegacyRotation() throws JsonProcessingException {
when(clusterConfigService.get(IndexSetsDefaultConfiguration.class)).thenReturn(readLegacyConfig(CONFIG_USE_LEGACY_FALSE));
IndexSetTemplateConfig defaultConfiguration = readConfig(CONFIG_USE_LEGACY_FAL... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void between() {
String inputExpression = "x between 10+y and 3**z";
BaseNode between = parse( inputExpression );
assertThat( between).isInstanceOf(BetweenNode.class);
assertThat( between.getResultType()).isEqualTo(BuiltInType.BOOLEAN);
assertThat( between.getText()).i... |
public HttpResponseDecoderSpec parseHttpAfterConnectRequest(boolean parseHttpAfterConnectRequest) {
this.parseHttpAfterConnectRequest = parseHttpAfterConnectRequest;
return this;
} | @Test
void parseHttpAfterConnectRequest() {
checkDefaultParseHttpAfterConnectRequest(conf);
conf.parseHttpAfterConnectRequest(true);
assertThat(conf.parseHttpAfterConnectRequest).as("parse http after connect request").isTrue();
checkDefaultMaxInitialLineLength(conf);
checkDefaultMaxHeaderSize(conf);
che... |
protected String decideSource(MappedMessage cef, RawMessage raw) {
// Try getting the host name from the CEF extension "deviceAddress"/"dvc"
final Map<String, Object> fields = cef.mappedExtensions();
if (fields != null && !fields.isEmpty()) {
final String deviceAddress = (String) fie... | @Test
public void decideSourceWithoutDeviceAddressReturnsRawMessageRemoteAddress() throws Exception {
final MappedMessage cefMessage = mock(MappedMessage.class);
when(cefMessage.mappedExtensions()).thenReturn(Collections.emptyMap());
final RawMessage rawMessage = new RawMessage(new byte[0],... |
public FEELFnResult<String> invoke(@ParameterName("from") Object val) {
if ( val == null ) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) );
}
} | @Test
void invokeZonedDateTime() {
final ZonedDateTime zonedDateTime = ZonedDateTime.now();
FunctionTestUtil.assertResult(stringFunction.invoke(zonedDateTime),
DateAndTimeFunction.REGION_DATETIME_FORMATTER.format(zonedDateTime));
} |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfByteArrayNegativePrefixLengthIPv4() {
IpPrefix ipPrefix;
byte[] value;
value = new byte[] {1, 2, 3, 4};
ipPrefix = IpPrefix.valueOf(IpAddress.Version.INET, value, -1);
} |
static int determineOperatorReservoirSize(int operatorParallelism, int numPartitions) {
int coordinatorReservoirSize = determineCoordinatorReservoirSize(numPartitions);
int totalOperatorSamples = coordinatorReservoirSize * OPERATOR_OVER_SAMPLE_RATIO;
return (int) Math.ceil((double) totalOperatorSamples / op... | @Test
public void testOperatorReservoirSize() {
assertThat(SketchUtil.determineOperatorReservoirSize(5, 3))
.isEqualTo((10_002 * SketchUtil.OPERATOR_OVER_SAMPLE_RATIO) / 5);
assertThat(SketchUtil.determineOperatorReservoirSize(123, 123))
.isEqualTo((123_00 * SketchUtil.OPERATOR_OVER_SAMPLE_RAT... |
@Udf
public <T> String toJsonString(@UdfParameter final T input) {
return toJson(input);
} | @Test
public void shouldSerializeBytes() {
// When:
final String result = udf.toJsonString(ByteBuffer.allocate(4).putInt(1097151));
// Then:
assertEquals("\"ABC9vw==\"", result);
} |
public int getSequenceCount() {
return this.sequenceCount;
} | @Test
public void testGetSequenceCount() throws Exception {
assertEquals(4, buildChunk().getSequenceCount());
} |
public static String toHexStringWithPrefix(BigInteger value) {
return HEX_PREFIX + value.toString(16);
} | @Test
public void testToHexStringWithPrefix() {
assertEquals(Numeric.toHexStringWithPrefix(BigInteger.TEN), ("0xa"));
assertEquals(Numeric.toHexStringWithPrefix(BigInteger.valueOf(1024)), ("0x400"));
assertEquals(Numeric.toHexStringWithPrefix(BigInteger.valueOf(65)), ("0x41"));
asser... |
public List<R> scanForResourcesUri(URI classpathResourceUri) {
requireNonNull(classpathResourceUri, "classpathResourceUri must not be null");
if (CLASSPATH_SCHEME.equals(classpathResourceUri.getScheme())) {
return scanForClasspathResource(resourceName(classpathResourceUri), NULL_FILTER);
... | @Test
void scanForResourcesClasspathPackageUri() {
URI uri = URI.create("classpath:io/cucumber/core/resource");
List<URI> resources = resourceScanner.scanForResourcesUri(uri);
assertThat(resources, containsInAnyOrder(
URI.create("classpath:io/cucumber/core/resource/test/resource.... |
@Override
public long getMaxMigrationNumber() {
return steps.get(steps.size() - 1).getMigrationNumber();
} | @Test
public void getMaxMigrationNumber_returns_migration_of_last_step_in_constructor_list_argument() {
assertThat(underTest.getMaxMigrationNumber()).isEqualTo(8L);
assertThat(unorderedSteps.getMaxMigrationNumber()).isOne();
} |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void assigns_feature_paths() {
RuntimeOptions options = parser
.parse("somewhere_else")
.build();
assertThat(options.getFeaturePaths(), contains(new File("somewhere_else").toURI()));
} |
@Override
public boolean match(final String rule) {
return rule.matches("^zh\\|\\d+-\\d+$");
} | @Test
public void match() {
assertTrue(generator.match("zh|10-15"));
assertFalse(generator.match("zh"));
assertFalse(generator.match("zh|"));
assertFalse(generator.match("zh|10.1-15"));
} |
@Override
public List<Document> get() {
try (var input = markdownResource.getInputStream()) {
Node node = parser.parseReader(new InputStreamReader(input));
DocumentVisitor documentVisitor = new DocumentVisitor(config);
node.accept(documentVisitor);
return documentVisitor.getDocuments();
}
catch (IO... | @Test
void testBlockquote() {
MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/blockquote.md");
List<Document> documents = reader.get();
assertThat(documents).hasSize(2)
.extracting(Document::getMetadata, Document::getContent)
.containsOnly(tuple(Map.of(),
"Lorem ipsum dolor si... |
public static byte[] decryptDES(byte[] data, byte[] key) {
return desTemplate(data, key, DES_Algorithm, DES_Transformation, false);
} | @Test
public void testDecryptDES() throws Exception {
TestCase.assertTrue(
Arrays.equals(
bytesDataDES,
EncryptKit.decryptDES(bytesResDES, bytesKeyDES)
)
);
TestCase.assertTrue(
Arrays.equals(
... |
public String abbreviate(String fqClassName) {
StringBuilder buf = new StringBuilder(targetLength);
if (fqClassName == null) {
throw new IllegalArgumentException("Class name may not be null");
}
int inLen = fqClassName.length();
if (inLen < targetLength) {
return fqClassName;
}
... | @Test
public void testXDot() {
{
TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(21);
String name = "com.logback.wombat.alligator.Foobar";
assertEquals("c.l.w.a.Foobar", abbreviator.abbreviate(name));
}
{
TargetLengthBasedClassName... |
public static List<String> getUnixGroups(String user) throws IOException {
String effectiveGroupsResult;
String allGroupsResult;
List<String> groups = new ArrayList<>();
try {
effectiveGroupsResult = ShellUtils.execCommand(
ShellUtils.getEffectiveGroupsForUserCommand(user));
allGro... | @Test
public void userGroup() throws Throwable {
String userName = "alluxio-user1";
String userEffectiveGroup1 = "alluxio-user1-effective-group1";
String userEffectiveGroup2 = "alluxio-user1-effective-group2";
String userAllGroup1 = "alluxio-user1-all-group1";
String userAllGroup2 = "alluxio-user1... |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ExportStorageNodesStatement sqlStatement, final ContextManager contextManager) {
checkSQLStatement(contextManager.getMetaDataContexts().getMetaData(), sqlStatement);
String exportedData = generateExportData(contextManager.getMetaData... | @Test
void assertExecuteWithEmptyMetaData() {
ContextManager contextManager = mockEmptyContextManager();
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
when(ProxyContext.getInstance().getAllDatabaseNames()).thenReturn(Collections.singleton("empty_metadata"))... |
public String decrypt(String encryptedText) {
Matcher matcher = ENCRYPTED_PATTERN.matcher(encryptedText);
if (matcher.matches()) {
Cipher cipher = ciphers.get(matcher.group(1).toLowerCase(Locale.ENGLISH));
if (cipher != null) {
return cipher.decrypt(matcher.group(2));
}
}
retur... | @Test
public void decrypt_unknown_algorithm() {
Encryption encryption = new Encryption(null);
assertThat(encryption.decrypt("{xxx}Zm9v")).isEqualTo("{xxx}Zm9v");
} |
public static int[] computePhysicalIndicesOrTimeAttributeMarkers(
TableSource<?> tableSource,
List<TableColumn> logicalColumns,
boolean streamMarkers,
Function<String, String> nameRemapping) {
Optional<String> proctimeAttribute = getProctimeAttribute(tableSource);... | @Test
void testWrongLogicalTypeForProctimeAttribute() {
TestTableSource tableSource =
new TestTableSource(
DataTypes.BIGINT(), Collections.singletonList("rowtime"), "proctime");
assertThatThrownBy(
() ->
... |
@Override
public TableEntryByTypeTransformer tableEntryByTypeTransformer() {
return transformer;
} | @Test
void transforms_with_correct_method_with_cell_transformer() throws Throwable {
Method method = JavaDefaultDataTableEntryTransformerDefinitionTest.class.getMethod(
"correct_method_with_cell_transformer", Map.class, Type.class, TableCellByTypeTransformer.class);
JavaDefaultDataTableE... |
public boolean allSearchFiltersVisible() {
return hiddenSearchFiltersIDs.isEmpty();
} | @Test
void testAllSearchFiltersVisibleReturnsFalseOnNonEmptyHiddenFilters() {
toTest = new SearchFilterVisibilityCheckStatus(Collections.singletonList("There is a hidden one!"));
assertFalse(toTest.allSearchFiltersVisible());
assertFalse(toTest.allSearchFiltersVisible(null));
assertF... |
@Override
public Map<String, Map<String, String>> getAdditionalInformation() {
return Collections.singletonMap("values", values);
} | @Test
public void testGetValues() throws Exception {
Map<String,String> values = new HashMap<>();
values.put("foo", "bar");
values.put("baz", "lol");
final ListField list = new ListField("list", "The List", Collections.emptyList(), values, "Hello, this is a list", ConfigurationField... |
@Override
public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff)
throws IOException, InterruptedException {
IOException lastException = null;
do {
try {
// Match inputPath which may contains glob
Collection<Metadata> files =
Iterables.getOnlyElement... | @Test
public void testReadWithRetriesFailsWhenRedundantFileLoaded() throws Exception {
tmpFolder.newFile("result-000-of-001");
tmpFolder.newFile("tmp-result-000-of-001");
NumberedShardedFile shardedFile = new NumberedShardedFile(filePattern);
thrown.expect(IOException.class);
thrown.expectMessag... |
@Override
public void release(final String id) {
synchronized(lock) {
if(log.isDebugEnabled()) {
log.debug(String.format("Release sleep assertion %s", id));
}
this.releaseAssertion(id);
}
} | @Test
public void testRelease() {
final SleepPreventer s = new IOKitSleepPreventer();
final String lock = s.lock();
Assert.assertNotNull(lock);
s.release(lock);
} |
public boolean hasOnlineDir(Uuid dir) {
return DirectoryId.isOnline(dir, directories);
} | @Test
void testHasOnlineDir() {
BrokerRegistration registration = new BrokerRegistration.Builder().
setId(0).
setEpoch(0).
setIncarnationId(Uuid.fromString("m6CiJvfITZeKVC6UuhlZew")).
setListeners(Collections.singletonList(new Endpoint("INTERNA... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testCursorStrategyCutIfBeginIndexIsDisabled() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.cursorStrategy(CUT)
.sourceField("msg")
.callback(new Callable<Result[]>() {
@Override
... |
public FEELFnResult<String> invoke(@ParameterName("from") Object val) {
if ( val == null ) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) );
}
} | @Test
void invokeListEmpty() {
FunctionTestUtil.assertResult(stringFunction.invoke(Collections.emptyList()), "[ ]");
} |
public <T extends VFSConnectionDetails> boolean test( @NonNull ConnectionManager manager,
@NonNull T details,
@Nullable VFSConnectionTestOptions options )
throws KettleException {
if ( options == nul... | @Test
public void testTestReturnsTrueWhenRootPathInvalidAndOptionsToIgnoreRootPath() throws KettleException {
when( vfsConnectionDetails.getRootPath() ).thenReturn( "../invalid" );
assertTrue( vfsConnectionManagerHelper.test( connectionManager, vfsConnectionDetails, getTestOptionsRootPathIgnored() ) );
} |
public Future<KafkaVersionChange> reconcile() {
return getPods()
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testUpgradeWithoutVersion(VertxTestContext context) {
VersionChangeCreator vcc = mockVersionChangeCreator(
mockKafka(null, VERSIONS.version(KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION).metadataVersion(), null),
mockRos(mockUniformPods(VERSIONS.version(Kafka... |
@SuppressWarnings("FutureReturnValueIgnored")
public void start() {
running.set(true);
configFetcher.start();
memoryMonitor.start();
streamingWorkerHarness.start();
sampler.start();
workerStatusReporter.start();
activeWorkRefresher.start();
} | @Test
public void testUnboundedSourcesDrain() throws Exception {
List<Integer> finalizeTracker = Lists.newArrayList();
TestCountingSource.setFinalizeTracker(finalizeTracker);
StreamingDataflowWorker worker =
makeWorker(
defaultWorkerParams()
.setInstructions(makeUnboun... |
public double calculateDensity(Graph graph, boolean isGraphDirected) {
double result;
double edgesCount = graph.getEdgeCount();
double nodesCount = graph.getNodeCount();
double multiplier = 1;
if (!isGraphDirected) {
multiplier = 2;
}
result = (multi... | @Test
public void testDirectedCompleteGraphDensity() {
GraphModel graphModel = GraphGenerator.generateCompleteDirectedGraph(5);
DirectedGraph graph = graphModel.getDirectedGraph();
GraphDensity d = new GraphDensity();
double density = d.calculateDensity(graph, true);
assertEq... |
public Usage metrics(boolean details) {
ZonedDateTime to = ZonedDateTime.now();
ZonedDateTime from = to
.toLocalDate()
.atStartOfDay(ZoneId.systemDefault())
.minusDays(1);
return metrics(details, from, to);
} | @Test
public void metrics() throws URISyntaxException {
ImmutableMap<String, Object> properties = ImmutableMap.of("kestra.server-type", ServerType.WEBSERVER.name());
try (ApplicationContext applicationContext = Helpers.applicationContext(properties).start()) {
CollectorService collector... |
public static AccessTokenRetriever create(Map<String, ?> configs, Map<String, Object> jaasConfig) {
return create(configs, null, jaasConfig);
} | @Test
public void testConfigureRefreshingFileAccessTokenRetriever() throws Exception {
String expected = "{}";
File tmpDir = createTempDir("access-token");
File accessTokenFile = createTempFile(tmpDir, "access-token-", ".json", expected);
Map<String, ?> configs = Collections.single... |
public Cluster buildCluster() {
Set<String> internalTopics = new HashSet<>();
List<PartitionInfo> partitions = new ArrayList<>();
Map<String, Uuid> topicIds = new HashMap<>();
for (TopicMetadata metadata : topicMetadata()) {
if (metadata.error == Errors.NONE) {
... | @Test
void buildClusterTest() {
Uuid zeroUuid = new Uuid(0L, 0L);
Uuid randomUuid = Uuid.randomUuid();
MetadataResponseData.MetadataResponseTopic topicMetadata1 = new MetadataResponseData.MetadataResponseTopic()
.setName("topic1")
.setErrorCode(Errors.NONE.cod... |
public static void smooth(PointList geometry, double maxWindowSize) {
if (geometry.size() <= 2) {
// geometry consists only of tower nodes, there are no pillar nodes to be smoothed in between
return;
}
// calculate the distance between all points once here to avoid repea... | @Test
public void testSparsePoints() {
PointList pl = new PointList(3, true);
pl.add(47.329730504970684, 10.156667197157475, 0);
pl.add(47.3298073615309, 10.15798541322701, 100);
pl.add(47.3316055451794, 10.158042110691866, 200);
EdgeElevationSmoothingMovingAverage.smooth(pl... |
@SuppressWarnings({"rawtypes", "unchecked"})
public SchemaMetaData revise(final SchemaMetaData originalMetaData) {
SchemaMetaData result = originalMetaData;
for (Entry<ShardingSphereRule, MetaDataReviseEntry> entry : OrderedSPILoader.getServices(MetaDataReviseEntry.class, rules).entrySet()) {
... | @Test
void assertReviseWithMetaDataReviseEntry() {
SchemaMetaData schemaMetaData = new SchemaMetaData("expected", Collections.singletonList(createTableMetaData()));
SchemaMetaData actual = new SchemaMetaDataReviseEngine(
Collections.singleton(new FixtureGlobalRule()), new Configurati... |
public static Optional<Page> createPartitionManifest(PartitionUpdate partitionUpdate)
{
// Manifest Page layout:
// fileName fileSize
// X X
// X X
// X X
// ....
PageBuilder manifestBuilder = new PageBuilder(I... | @Test
public void testCreatePartitionManifest()
{
PartitionUpdate partitionUpdate = new PartitionUpdate("testPartition", NEW, "/testDir", "/testDir", ImmutableList.of(new FileWriteInfo("testFileName", "testFileName", Optional.of(FILE_SIZE))), 100, 1024, 1024, false);
Optional<Page> manifestPage ... |
@Override
public KTableValueGetterSupplier<K, VOut> view() {
if (queryableName != null) {
return new KTableMaterializedValueGetterSupplier<>(queryableName);
}
return new KTableValueGetterSupplier<K, VOut>() {
final KTableValueGetterSupplier<K, V> parentValueGetterSup... | @Test
public void shouldGetQueryableStoreNameIfMaterialized() {
final KTableTransformValues<String, String, String> transformValues =
new KTableTransformValues<>(parent, new ExclamationValueTransformerSupplier(), QUERYABLE_NAME);
final String[] storeNames = transformValues.view().storeN... |
@Override
public void open() throws CatalogException {
if (this.client == null) {
try {
this.client = Hive.get(hiveConf).getMSC();
} catch (Exception e) {
throw new HoodieCatalogException("Failed to create hive metastore client", e);
}
LOG.info("Connected to Hive metastore"... | @Test
void testCreateTableWithoutPreCombineKey() throws TableAlreadyExistException, DatabaseNotExistException, IOException, TableNotExistException {
String db = "default";
hoodieCatalog = HoodieCatalogTestUtils.createHiveCatalog();
hoodieCatalog.open();
Map<String, String> options = new HashMap<>();
... |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test
public void endpointsByNamespaceWithPublicIpExposingMultiplePorts()throws JsonProcessingException {
// given
stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsListResponse());
stub(String.format("/api/v1/namespaces/%s/endpoints", NAMESPACE), endpointsListResponse());
... |
public String replaceSecretInfo(String line) {
if (line == null) {
return null;
}
for (CommandArgument argument : arguments) {
line = argument.replaceSecretInfo(line);
}
for (SecretString secret : secrets) {
line = secret.replaceSecretInfo(line... | @Test
void shouldReplaceSecretInfoShouldNotFailForNull() {
ArrayList<CommandArgument> commands = new ArrayList<>();
commands.add(new PasswordArgument("foo"));
ArrayList<SecretString> secretStrings = new ArrayList<>();
secretStrings.add(new PasswordArgument("foo"));
ConsoleRes... |
public static boolean isListEqual(List<String> firstList, List<String> secondList) {
if (firstList == null && secondList == null) {
return true;
}
if (firstList == null || secondList == null) {
return false;
}
if (firstList == secondList) {
... | @Test
void testIsListEqualForNotEquals() {
List<String> list1 = Arrays.asList("1", "2", "3");
List<String> list2 = Arrays.asList("1", "2", "3", "4");
List<String> list3 = Arrays.asList("1", "2", "3", "5");
assertFalse(CollectionUtils.isListEqual(list1, list2));
assertFalse(Co... |
public static boolean isHostInNetworkCard(String host) {
try {
InetAddress addr = InetAddress.getByName(host);
return NetworkInterface.getByInetAddress(addr) != null;
} catch (Exception e) {
return false;
}
} | @Test
public void isHostInNetworkCard() throws Exception {
} |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeOverwritingMetadataColumnsDuplicate() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.columnByMetadata("two", DataTypes.INT())
.build();
List<SqlNode> derivedColumns ... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
boolean satisfied = false;
// No trading history or no position opened, no gain
if (tradingRecord != null) {
Position currentPosition = tradingRecord.getCurrentPosition();
if (currentPositi... | @Test
public void testStopGainTriggeredOnLongPosition() {
TradingRecord tradingRecord = new BaseTradingRecord();
tradingRecord.enter(0, series.getBar(0).getClosePrice(), series.numOf(1));
AverageTrueRangeStopGainRule rule = new AverageTrueRangeStopGainRule(series, 3, 2.0);
assertFa... |
public static <T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
if (isEmpty(coll1) && isEmpty(coll2)) {
return new ArrayList<>();
}
if (isEmpty(coll1)) {
return new ArrayList<>(coll2);
} else if (isEmpty(coll2)) {
return new ArrayList<>(coll1);
}
final ArrayList<T> list = new Arr... | @SuppressWarnings("ConstantValue")
@Test
public void unionNullTest() {
final List<String> list1 = new ArrayList<>();
final List<String> list2 = null;
final List<String> list3 = null;
final Collection<String> union = CollUtil.union(list1, list2, list3);
assertNotNull(union);
} |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
MetaData.Builder metaData = new MetaData.Builder(sanit... | @Test
public void reportsCounters() throws Exception {
Counter counter = mock(Counter.class);
when(counter.getCount()).thenReturn(42L);
reporter.report(
map(),
map("api.rest.requests.count", counter),
map(),
map(),
... |
public ProducerTableInfo getAllProducerInfo(final String addr, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetAllProducerInfoRequestHeader requestHeader = new GetAllProducerInfoReques... | @Test
public void assertGetAllProducerInfo() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
Map<String, List<ProducerInfo>> data = new HashMap<>();
data.put("key", Collections.emptyList());
ProducerTableInfo responseBody = new ProducerTableInfo(... |
public static String cutString(String value) {
byte[] bytes = value.getBytes(Helper.UTF_CS);
// See #2609 and test why we use a value < 255
return bytes.length > 250 ? new String(bytes, 0, 250, Helper.UTF_CS) : value;
} | @Test
public void testCutString() {
String s = cutString("Бухарестская улица (http://ru.wikipedia.org/wiki/" +
"%D0%91%D1%83%D1%85%D0%B0%D1%80%D0%B5%D1%81%D1%82%D1%81%D0%BA%D0%B0%D1%8F_%D1%83%D0%BB%D0%B8%D1%86%D0%B0_(%D0%A1%D0%B0%D0%BD%D0%BA%D1%82-%D0%9F%D0%B5%D1%82%D0%B5%D1%80%D0%B1%D1%83%D... |
@Override
public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) {
if (stateManager.taskType() != TaskType.ACTIVE) {
throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ... | @Test
public void globalSessionStoreShouldBeReadOnly() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.getGlobalStore(anyString())).thenReturn(null);
final SessionStore<String, Long> sessionStore = mock(SessionStore.class);
whe... |
public Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
Marshaller marshaller = getContext(clazz).createMarshaller();
setMarshallerProperties(marshaller);
if (marshallerEventHandler != null) {
marshaller.setEventHandler(marshallerEventHandler);
}
marshaller.setSchema(marshall... | @Test
void buildsMarshallerWithSchemaLocationProperty() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder()
.withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd")
.build();
Marshaller marshaller = factory.createMarshaller(Object.... |
public static <T> SamplerFunction<T> deferDecision() {
return (SamplerFunction<T>) Constants.DEFER_DECISION;
} | @Test void deferDecision_returnsNull() {
assertThat(deferDecision().trySample(null)).isNull();
assertThat(deferDecision().trySample("1")).isNull();
} |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testContainsValueTTL() throws InterruptedException {
RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simple01");
Assertions.assertFalse(map.containsValue(new SimpleValue("34")));
map.put(new SimpleKey("33"), new SimpleValue("44"), Duration.ofSecond... |
public void transitionTo(ClassicGroupState groupState) {
assertValidTransition(groupState);
previousState = state;
state = groupState;
currentStateTimestamp = Optional.of(time.milliseconds());
metrics.onClassicGroupStateTransition(previousState, state);
} | @Test
public void testPreparingRebalanceToDeadTransition() {
group.transitionTo(PREPARING_REBALANCE);
group.transitionTo(DEAD);
assertState(group, DEAD);
} |
public static ClusterAllocationDiskSettings create(boolean enabled, String low, String high, String floodStage) {
if (!enabled) {
return ClusterAllocationDiskSettings.create(enabled, null);
}
return ClusterAllocationDiskSettings.create(enabled, createWatermarkSettings(low, high, floo... | @Test
public void createPercentageWatermarkSettingsWithoutFloodStage() throws Exception {
ClusterAllocationDiskSettings settings = ClusterAllocationDiskSettingsFactory.create(true, "65%", "75%", "");
assertThat(settings).isInstanceOf(ClusterAllocationDiskSettings.class);
assertThat(settings... |
@Override
public ManagedChannel shutdownNow() {
ArrayList<ManagedChannel> channels = new ArrayList<>();
synchronized (this) {
shutdownStarted = true;
channels.addAll(usedChannels);
channels.addAll(channelCache);
}
for (ManagedChannel channel : channels) {
channel.shutdownNow();... | @Test
public void testShutdownNow() throws Exception {
ManagedChannel mockChannel = mock(ManagedChannel.class);
when(channelSupplier.get()).thenReturn(mockChannel);
ClientCall<Object, Object> mockCall1 = mock(ClientCall.class);
ClientCall<Object, Object> mockCall2 = mock(ClientCall.class);
when(mo... |
@Restricted(NoExternalUse.class)
public static String extractPluginNameFromIconSrc(String iconSrc) {
if (iconSrc == null) {
return "";
}
if (!iconSrc.contains("plugin-")) {
return "";
}
String[] arr = iconSrc.split(" ");
for (String element :... | @Test
public void extractPluginNameFromIconSrcWhichContainsPluginWordInThePluginName() {
String result = Functions.extractPluginNameFromIconSrc("symbol-padlock plugin-design-library-plugin");
assertThat(result, is(equalTo("design-library-plugin")));
} |
public boolean isEmpty() {
return CommonUtils.isEmpty(providerInfos);
} | @Test
public void isEmpty() throws Exception {
ProviderGroup pg = new ProviderGroup("xxx", null);
Assert.assertTrue(pg.isEmpty());
pg = new ProviderGroup("xxx", new ArrayList<ProviderInfo>());
Assert.assertTrue(pg.isEmpty());
pg = new ProviderGroup("xxx", Arrays.asList(Prov... |
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
final UriTemplate uriTemplate = new UriTemplate(config.prefix);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
boolean alreadyPrefixed = exchange.getAttributeOrDefault(GATEWAY_... | @Test
public void toStringFormat() {
Config config = new Config();
config.setPrefix("myprefix");
GatewayFilter filter = new PrefixPathGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("myprefix");
} |
@Override
public CompletableFuture<ListGroupsResponseData> listGroups(
RequestContext context,
ListGroupsRequestData request
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(new ListGroupsResponseData()
.setErrorCode(Errors.COORDINATOR_NOT_A... | @Test
public void testListGroups() throws ExecutionException, InterruptedException, TimeoutException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
create... |
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
EnhancedPluginContext enhancedPluginContext = new EnhancedPluginContext();
EnhancedRequestContext enhancedRequestContext = EnhancedRequestContext.builder()
.httpHeaders(r... | @Test
public void testRun() throws IOException, URISyntaxException {
ClientHttpResponse actualResult;
final byte[] inputBody = null;
URI uri = new URI("http://0.0.0.0/");
doReturn(uri).when(mockHttpRequest).getURI();
doReturn(HttpMethod.GET).when(mockHttpRequest).getMethod();
doReturn(mockHttpHeaders).wh... |
@Override
public T peekLast()
{
if (_tail == null)
{
return null;
}
return _tail._value;
} | @Test
public void testEmptyPeekLast()
{
LinkedDeque<Object> q = new LinkedDeque<>();
Assert.assertNull(q.peekLast(), "peekLast on empty queue should return null");
} |
@Override
public Optional<DispatchEvent> build(final DataChangedEvent event) {
String instanceId = ComputeNode.getInstanceIdByComputeNode(event.getKey());
if (!Strings.isNullOrEmpty(instanceId)) {
Optional<DispatchEvent> result = createInstanceDispatchEvent(event, instanceId);
... | @Test
void assertCreateEventWhenEnabled() {
Optional<DispatchEvent> actual = new ComputeNodeStateDispatchEventBuilder()
.build(new DataChangedEvent("/nodes/compute_nodes/status/foo_instance_id", "", Type.UPDATED));
assertTrue(actual.isPresent());
assertTrue(((ComputeNodeInsta... |
public int compare(boolean b1, boolean b2) {
throw new UnsupportedOperationException(
"compare(boolean, boolean) was called on a non-boolean comparator: " + toString());
} | @Test
public void testDoubleComparator() {
Double[] valuesInAscendingOrder = {
null,
Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE,
-123456.7890123456789,
-Double.MIN_VALUE,
0.0,
Double.MIN_VALUE,
123456.7890123456789,
Double.MAX_VALUE,
Double.POSITIVE_INF... |
public InputSplit[] getSplits(JobConf job, int numSplits)
throws IOException {
StopWatch sw = new StopWatch().start();
FileStatus[] stats = listStatus(job);
// Save the number of input files for metrics/loadgen
job.setLong(NUM_INPUT_FILES, stats.length);
long totalSize = 0; ... | @Test
public void testIgnoreDirs() throws Exception {
Configuration conf = getConfiguration();
conf.setBoolean(FileInputFormat.INPUT_DIR_NONRECURSIVE_IGNORE_SUBDIRS, true);
conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads);
conf.set(org.apache.hadoop.mapreduce.lib.input.FileInputFormat.... |
@Override
public BlobDescriptor call() throws IOException, RegistryException {
EventHandlers eventHandlers = buildContext.getEventHandlers();
DescriptorDigest blobDigest = blobDescriptor.getDigest();
try (ProgressEventDispatcher progressEventDispatcher =
progressEventDispatcherFactory.create(
... | @Test
public void testCall_doBlobCheckAndBlobDoesNotExist() throws IOException, RegistryException {
Mockito.when(registryClient.checkBlob(Mockito.any())).thenReturn(Optional.empty());
call(false);
Mockito.verify(registryClient).checkBlob(Mockito.any());
Mockito.verify(registryClient)
.pushBl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.