focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseNonVarargWithNullValuesOfSameSchemas() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING, STRING),
function(OTHER, 0, STRING_VARARGS)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(Arrays.asList(SqlArgument.of(null, null), Sql... |
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new ConcurrentHashMap<>();
} | @Test
public void newConcurrentMap() {
Assert.assertNotNull(CollectionKit.newConcurrentMap(0));
Assert.assertNotNull(CollectionKit.newConcurrentMap());
} |
public static Message of(String msg, Object... arguments) {
return new Message(msg, arguments);
} | @Test
public void fail_when_message_is_null() {
assertThatThrownBy(() -> Message.of(null))
.isInstanceOf(IllegalArgumentException.class);
} |
@SuppressWarnings("unchecked")
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
ObjectUtil.checkNotNull(key, "key");
DefaultAttribute newAttribute = null;
for (;;) {
final DefaultAttribute[] attributes = this.attributes;
final int index = searchAttrib... | @Test
public void testSetRemove() {
AttributeKey<Integer> key = AttributeKey.valueOf("key");
Attribute<Integer> attr = map.attr(key);
attr.set(1);
assertSame(1, attr.getAndRemove());
Attribute<Integer> attr2 = map.attr(key);
attr2.set(2);
assertSame(2, attr2... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetGenericSchemaFromParameterizedTypeVariadic() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("genericMapType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getVarArgsSchemaFromType(genericType);
// Then:
... |
@Override
public void preflight(final Path workdir, final String filename) throws BackgroundException {
if(!validate(filename)) {
throw new InvalidFilenameException(MessageFormat.format(LocaleFactory.localizedString("Cannot create {0}", "Error"), filename));
}
// File/directory ... | @Test
public void testPreflightFileAccessGrantedCustomProps() throws Exception {
final Path file = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
new CteraTouchFeature(session).preflight(file, new AlphanumericR... |
@Override
public void writeDouble(final double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
} | @Test
public void testWriteDoubleForPositionVByteOrder() throws Exception {
double v = 1.1d;
out.writeDouble(1, v, LITTLE_ENDIAN);
long theLong = Double.doubleToLongBits(v);
long readLongB = Bits.readLongL(out.buffer, 1);
assertEquals(theLong, readLongB);
} |
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long deadline = System.nanoTime() + unit.toNanos(timeout);
for (EventLoop l: activeChildren) {
for (;;) {
long timeLeft = deadline - System.nanoTime();
... | @Test
public void testTerminationFutureSuccessReflectively() throws Exception {
Field terminationFutureField =
ThreadPerChannelEventLoopGroup.class.getDeclaredField("terminationFuture");
terminationFutureField.setAccessible(true);
final Exception[] exceptionHolder = new Excep... |
public static Duration parse(final String text) {
try {
final String[] parts = text.split("\\s");
if (parts.length != 2) {
throw new IllegalArgumentException("Expected 2 tokens, got: " + parts.length);
}
final long size = parseNumeric(parts[0]);
return buildDuration(size, part... | @Test
public void shouldThrowOnTooFewTokens() {
// Then:
// When:
final Exception e = assertThrows(
IllegalArgumentException.class,
() -> parse("10")
);
// Then:
assertThat(e.getMessage(), containsString("Expected 2 tokens, got: 1"));
} |
@Override
public boolean isProvisioningEnabled() {
return isEnabled() && configuration.getBoolean(GITLAB_AUTH_PROVISIONING_ENABLED).orElse(false);
} | @Test
public void isProvisioningEnabled_ifProvisioningEnabledButGithubAuthDisabled_returnsFalse() {
settings.setProperty(GITLAB_AUTH_PROVISIONING_ENABLED, true);
assertThat(config.isProvisioningEnabled()).isFalse();
} |
public static ExpressionStmt createArraysAsListExpression() {
ExpressionStmt toReturn = new ExpressionStmt();
MethodCallExpr arraysCallExpression = new MethodCallExpr();
SimpleName arraysName = new SimpleName(Arrays.class.getName());
arraysCallExpression.setScope(new NameExpr(arraysName)... | @Test
void createArraysAsListExpression() {
ExpressionStmt retrieved = CommonCodegenUtils.createArraysAsListExpression();
assertThat(retrieved).isNotNull();
String expected = "java.util.Arrays.asList();";
String retrievedString = retrieved.toString();
assertThat(retrievedStri... |
public long maxEntrySize() {
return maxEntrySize;
} | @Test
public void testMaxEntrySizeConfig() {
withSQLConf(
ImmutableMap.of(SparkSQLProperties.EXECUTOR_CACHE_MAX_ENTRY_SIZE, "128"),
() -> {
Conf conf = new Conf();
assertThat(conf.maxEntrySize()).isEqualTo(128L);
});
} |
@Override
public <VOut> KStream<K, VOut> processValues(
final FixedKeyProcessorSupplier<? super K, ? super V, VOut> processorSupplier,
final String... stateStoreNames
) {
return processValues(
processorSupplier,
Named.as(builder.newProcessorName(PROCESSVALUES_NAME... | @Test
public void shouldNotAllowNullNamedOnProcessValues() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.processValues(fixedKeyProcessorSupplier, (Named) null));
assertThat(exception.getMessage(), equalTo("named can't be n... |
@Override
public boolean match(final String rule) {
return rule.matches("^current(\\|.+)?");
} | @Test
public void testMatch() {
Assertions.assertTrue(generator.match("current"));
Assertions.assertFalse(generator.match("current|"));
Assertions.assertTrue(generator.match("current|YYYY-MM-dd"));
} |
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try ... | @Test
public void testExecute() {
TopicRouteSubCommand cmd = new TopicRouteSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin... |
public static <T> List<List<T>> diffList(Collection<T> oldList, Collection<T> newList,
BiFunction<T, T, Boolean> sameFunc) {
List<T> createList = new LinkedList<>(newList); // 默认都认为是新增的,后续会进行移除
List<T> updateList = new ArrayList<>();
List<T> deleteLis... | @Test
public void testDiffList() {
// 准备参数
Collection<Dog> oldList = Arrays.asList(
new Dog(1, "花花", "hh"),
new Dog(2, "旺财", "wc")
);
Collection<Dog> newList = Arrays.asList(
new Dog(null, "花花2", "hh"),
new Dog(null, "小白... |
@Override
public KeyValueIterator<Windowed<K>, V> fetch(final K key) {
Objects.requireNonNull(key, "key cannot be null");
return new MeteredWindowedKeyValueIterator<>(
wrapped().fetch(keyBytes(key)),
fetchSensor,
iteratorDurationSensor,
streamsMetrics,... | @Test
public void shouldThrowNullPointerOnFetchRangeIfFromIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> store.fetch(null, "to"));
} |
@Override
public void endInput(int inputId) throws Exception {
// sanity check.
checkState(inputId >= 1 && inputId <= 2);
if (inputId == 1) {
userFunction.endFirstInput(nonPartitionedContext);
} else {
userFunction.endSecondInput(nonPartitionedContext);
... | @Test
void testEndInput() throws Exception {
AtomicInteger firstInputCounter = new AtomicInteger();
AtomicInteger secondInputCounter = new AtomicInteger();
TwoInputNonBroadcastProcessOperator<Integer, Long, Long> processOperator =
new TwoInputNonBroadcastProcessOperator<>(
... |
@VisibleForTesting
public static void validateIngestionConfig(TableConfig tableConfig, @Nullable Schema schema) {
IngestionConfig ingestionConfig = tableConfig.getIngestionConfig();
if (ingestionConfig != null) {
String tableNameWithType = tableConfig.getTableName();
// Batch
if (ingestion... | @Test
public void validateIngestionConfig() {
Schema schema = new Schema.SchemaBuilder().setSchemaName(TABLE_NAME).build();
// null ingestion config
TableConfig tableConfig =
new TableConfigBuilder(TableType.OFFLINE).setTableName(TABLE_NAME).setIngestionConfig(null).build();
TableConfigUtils.v... |
@Override
public void writeTo(ByteBuf byteBuf) throws LispWriterException {
WRITER.writeTo(byteBuf, this);
} | @Test
public void testSerialization() throws LispReaderException, LispWriterException, LispParseError {
ByteBuf byteBuf = Unpooled.buffer();
RegisterWriter writer = new RegisterWriter();
writer.writeTo(byteBuf, register1);
RegisterReader reader = new RegisterReader();
LispM... |
@Override
public void onMatch(RelOptRuleCall call) {
final Sort sort = call.rel(0);
final SortExchange exchange = call.rel(1);
final RelMetadataQuery metadataQuery = call.getMetadataQuery();
if (RelMdUtil.checkInputForCollationAndLimit(
metadataQuery,
exchange.getInput(),
sort... | @Test
public void shouldNotMatchOffsetNoLimitNoSort() {
// Given:
SortExchange exchange =
PinotLogicalSortExchange.create(_input, RelDistributions.SINGLETON, RelCollations.EMPTY, false, true);
Sort sort = LogicalSort.create(exchange, RelCollations.EMPTY, literal(1), null);
Mockito.when(_call.r... |
public void reset() {
mPhysicalState = RELEASING;
mMomentaryPress = false;
mLogicalState = INACTIVE;
mActiveStateStartTime = 0L;
mConsumed = false;
} | @Test
public void testReset() throws Exception {
long millis = 1000;
setCurrentTimeMillis(++millis);
ModifierKeyState state = new ModifierKeyState(true);
Assert.assertFalse(state.isActive());
Assert.assertFalse(state.isLocked());
Assert.assertFalse(state.isPressed());
state.onPress();
... |
@Override
public boolean createReservation(ReservationId reservationId, String user,
Plan plan, ReservationDefinition contract) throws PlanningException {
LOG.info("placing the following ReservationRequest: " + contract);
try {
boolean res =
planner.createReservation(reservationId, use... | @Test
public void testSingleSliding() throws PlanningException {
prepareBasicPlan();
// create a single request for which we need subsequent (tight) packing.
ReservationDefinition rr = new ReservationDefinitionPBImpl();
rr.setArrival(100 * step);
rr.setDeadline(120 * step);
rr.setRecurrenceEx... |
static Collection<TopicPartition> getMatchingTopicPartitions(
Admin adminClient, String topicRegex, int startPartition, int endPartition)
throws Throwable {
final Pattern topicNamePattern = Pattern.compile(topicRegex);
// first get list of matching topics
List<String> matchedTop... | @Test
public void testGetMatchingTopicPartitionsCorrectlyMatchesTopics() throws Throwable {
final String topic1 = "test-topic";
final String topic2 = "another-test-topic";
final String topic3 = "one-more";
makeExistingTopicWithOneReplica(topic1, 10);
makeExistingTopicWithOneR... |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
} |
@Override
public synchronized void write(int b) throws IOException {
mUfsOutStream.write(b);
mBytesWritten++;
} | @Test
public void writeIncreasingBytes() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
try (FileOutStream outStream = mFileSystem.createFile(ufsPath)) {
for (int i = 0; i < CHUNK_SIZE; i++) {
outStream.write(i);
}
}
verifyIncreasingBytesWritten(ufsPath, ... |
@Override
public PageResult<MailTemplateDO> getMailTemplatePage(MailTemplatePageReqVO pageReqVO) {
return mailTemplateMapper.selectPage(pageReqVO);
} | @Test
public void testGetMailTemplatePage() {
// mock 数据
MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class, o -> { // 等会查询到
o.setName("源码");
o.setCode("test_01");
o.setAccountId(1L);
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
... |
@Override
public ReadWriteBuffer onCall(Command command, ReadWriteBuffer parameter) throws IOException {
Path p = null;
if (null == command) {
return null;
}
if (command.equals(GET_OUTPUT_PATH)) {
p = output.getOutputFileForWrite(-1);
} else if (command.equals(GET_OUTPUT_INDEX... | @Test
public void testGetCombiner() throws IOException {
this.handler = new NativeCollectorOnlyHandler(taskContext, nativeHandler, pusher, combiner);
Mockito.when(combiner.getId()).thenReturn(100L);
final ReadWriteBuffer result = handler.onCall(
NativeCollectorOnlyHandler.GET_COMBINE_HANDLER, null);... |
@Override
public void upgrade() {
if (hasBeenRunSuccessfully()) {
LOG.debug("Migration already completed.");
return;
}
final Set<String> dashboardIdToViewId = new HashSet<>();
final Consumer<String> recordMigratedDashboardIds = dashboardIdToViewId::add;
... | @Test
@MongoDBFixtures("dashboard_with_minimal_quickvalues_widget.json")
public void migrateDashboardWithMinimalQuickValuesWidget() throws Exception {
this.migration.upgrade();
final MigrationCompleted migrationCompleted = captureMigrationCompleted();
assertThat(migrationCompleted.migra... |
@Override
public void close() throws IOException {
if (closed) {
return;
}
try (PositionOutputStream temp = out) {
temp.flush();
if (crcAllocator != null) {
crcAllocator.close();
}
} finally {
closed = true;
}
} | @Test
public void testWriteReadStatisticsAllNulls() throws Exception {
// this test assumes statistics will be read
Assume.assumeTrue(!shouldIgnoreStatistics(Version.FULL_VERSION, BINARY));
File testFile = temp.newFile();
testFile.delete();
writeSchema = "message example {\n" + "required binary ... |
@Deprecated
public static int getScreenWidth(String qualifiers) {
for (String qualifier : qualifiers.split("-", 0)) {
Matcher matcher = SCREEN_WIDTH_PATTERN.matcher(qualifier);
if (matcher.find()) {
return Integer.parseInt(matcher.group(1));
}
}
return -1;
} | @Test
public void getScreenWidth() {
assertThat(Qualifiers.getScreenWidth("w320dp")).isEqualTo(320);
assertThat(Qualifiers.getScreenWidth("w320dp-v7")).isEqualTo(320);
assertThat(Qualifiers.getScreenWidth("en-rUS-w320dp")).isEqualTo(320);
assertThat(Qualifiers.getScreenWidth("en-rUS-w320dp-v7")).isEqu... |
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) {
AnalyzerContext context = new AnalyzerContext();
int treeSize = aggregatePredicateStatistics(predicate, false, context);
int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.h... | @Test
void require_that_minfeature_is_min_for_or() {
Predicate p =
or(
and(
feature("foo").inSet("bar"),
feature("baz").inSet("qux"),
feature("quux").inSet("corge")),
... |
static DatabaseInput toDatabaseInput(
Namespace namespace, Map<String, String> metadata, boolean skipNameValidation) {
DatabaseInput.Builder builder =
DatabaseInput.builder().name(toDatabaseName(namespace, skipNameValidation));
Map<String, String> parameters = Maps.newHashMap();
metadata.forEa... | @Test
public void testToDatabaseInputEmptyLocation() {
Map<String, String> properties =
ImmutableMap.of(IcebergToGlueConverter.GLUE_DESCRIPTION_KEY, "description", "key", "val");
DatabaseInput databaseInput =
IcebergToGlueConverter.toDatabaseInput(Namespace.of("ns"), properties, false);
as... |
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) {
if (xmppServer.isLocal(user)) {
try {
getUser(user.getNode());
return true;
}
catch (final UserNotFoundException e) {
return false;
... | @Test
public void isRegisteredUserFalseWillReturnTrueForLocalUsers() {
final boolean result = userManager.isRegisteredUser(new JID(USER_ID, Fixtures.XMPP_DOMAIN, null), false);
assertThat(result, is(true));
} |
private AlarmEntityId(final URI uri) {
super(uri);
} | @Test(expected = IllegalArgumentException.class)
public void verifyUnexpectedSchemaRejected() {
alarmEntityId("junk:foo");
} |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldNotMatchIfParamLengthDiffers() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING)
);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> udfIndex.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING), SqlArgument.of(... |
@Override
public boolean isReachable(DeviceId deviceId) {
String id = deviceId.uri().getSchemeSpecificPart();
JID jid = new JID(id);
XmppDeviceId xmppDeviceId = new XmppDeviceId(jid);
return controller.getDevice(xmppDeviceId) != null;
} | @Test
public void testIsReachable() {
assertTrue(provider.isReachable(DeviceId.deviceId("reachable@xmpp.org")));
assertFalse(provider.isReachable(DeviceId.deviceId("non-reachable@xmpp.org")));
} |
public static ListenableFuture<CustomerId> findEntityIdAsync(TbContext ctx, EntityId originator) {
switch (originator.getEntityType()) {
case CUSTOMER:
return Futures.immediateFuture((CustomerId) originator);
case USER:
return toCustomerIdAsync(ctx, ctx.ge... | @Test
public void givenCustomerEntityType_whenFindEntityIdAsync_thenOK() throws ExecutionException, InterruptedException {
// GIVEN
var customer = new Customer(new CustomerId(UUID.randomUUID()));
// WHEN
var actualCustomerId = EntitiesCustomerIdAsyncLoader.findEntityIdAsync(ctxMock,... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultMappingValue) {
DefaultMappingValue that = (DefaultMappingValue) obj;
return Objects.equals(action, that.action) &&
Objects.equals... | @Test
public void testEquals() {
MappingTreatment treatment1 = DefaultMappingTreatment.builder()
.withAddress(ma1)
.setUnicastPriority(10)
.setUnicastWeight(10)
... |
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
return isEnumType(type);
} | @Test
void testAccept() {
TypeElement typeElement = getType(Color.class);
assertTrue(builder.accept(processingEnv, typeElement.asType()));
} |
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // TODO(b/134064106): design an alternative to no-arg check()
public final Ordered containsExactly() {
return check().about(iterableEntries()).that(checkNotNull(actual).entries()).containsExactly();
} | @Test
public void containsExactlyVarargFailureExtra() {
ImmutableMultimap<Integer, String> expected =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ListMultimap<Integer, String> actual = LinkedListMultimap.create(expected);
actual.put(4, "nine");
actual.put(5, "eigh... |
Map<Path, Set<Integer>> changedLines() {
return tracker.changedLines();
} | @Test
public void count_single_added_line() throws IOException {
String example = "Index: sample1\n"
+ "===================================================================\n"
+ "--- a/sample1\n"
+ "+++ b/sample1\n"
+ "@@ -0,0 +1 @@\n"
+ "+added line\n";
printDiff(example);
a... |
public static String getDefaultHost(@Nullable String strInterface,
@Nullable String nameserver,
boolean tryfallbackResolution)
throws UnknownHostException {
if (strInterface == null || "default".equals(strInterface)) {
return cach... | @Test
public void testGetLocalHostIsFast() throws Exception {
String hostname1 = DNS.getDefaultHost(DEFAULT);
assertNotNull(hostname1);
String hostname2 = DNS.getDefaultHost(DEFAULT);
long t1 = Time.now();
String hostname3 = DNS.getDefaultHost(DEFAULT);
long t2 = Time.now();
assertEquals(h... |
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schams to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVis... | @Test
void visit12() {
String s12 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ct2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
assertEquals("... |
void startVulnerabilityDetecting(
ImmutableList<PluginMatchingResult<VulnDetector>> selectedVulnDetectors) {
checkState(currentExecutionStage.equals(ExecutionStage.SERVICE_FINGERPRINTING));
checkState(serviceFingerprintingTimer.isRunning());
this.serviceFingerprintingTimer.stop();
this.vulnerabil... | @Test
public void startVulnerabilityDetecting_whenStageNotFingerprinting_throwsException() {
ExecutionTracer executionTracer =
new ExecutionTracer(
portScanningTimer, serviceFingerprintingTimer, vulnerabilityDetectingTimer);
assertThrows(
IllegalStateException.class,
() ->... |
@Override
public CompletableFuture<String> getLeaderAddressFuture() {
return leaderAddressFuture;
} | @Test
void testLeaderAddressGetsForwarded() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
String testingAddress = "yolohost";
... |
public void launch(Monitored mp) {
if (!lifecycle.tryToMoveTo(Lifecycle.State.STARTING)) {
throw new IllegalStateException("Already started");
}
monitored = mp;
Logger logger = LoggerFactory.getLogger(getClass());
try {
launch(logger);
} catch (Exception e) {
logger.warn("Fail... | @Test
public void terminate_if_unexpected_shutdown() throws Exception {
Props props = createProps();
final ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime);
final StandardProcess process = new StandardProcess();
Thread runner = new Thread(() -> {
// starts an... |
public static RectL getBounds(final RectL pIn,
final long pCenterX, final long pCenterY, final double pDegrees,
final RectL pReuse) {
final RectL out = pReuse != null ? pReuse : new RectL();
if (pDegrees == 0) { // optimization
... | @Test
public void testGetBoundsSamplesRect() {
final Rect in = new Rect();
final Rect out = new Rect();
in.top = 0; // lousy member setting for Rect - see javadoc comments on class
in.left = 0;
in.bottom = 6;
in.right = 4;
RectL.getBounds(in, 0, 0, 180, out);... |
float parseFloat(String s) {
return parse(s).floatValue();
} | @Test
void can_parse_float() {
assertEquals(1042.2f, english.parseFloat("1,042.2"), 0);
assertEquals(1042.2f, german.parseFloat("1.042,2"), 0);
System.out.println(Arrays.toString(NumberFormat.getAvailableLocales()));
} |
public void updateState(List<TridentTuple> tuples) {
try {
String bulkRequest = buildRequest(tuples);
final Request request = new Request("post", "_bulk");
request.setEntity(new StringEntity(bulkRequest));
Response response = client.performRequest(request);
... | @Test
public void updateState() throws Exception {
List<TridentTuple> tuples = tuples(index, type, documentId, source);
state.updateState(tuples);
} |
static void activateHttpAndHttpsProxies(Settings settings, SettingsDecrypter decrypter)
throws MojoExecutionException {
List<Proxy> proxies = new ArrayList<>(2);
for (String protocol : ImmutableList.of("http", "https")) {
if (areProxyPropertiesSet(protocol)) {
continue;
}
setting... | @Test
public void testActivateHttpAndHttpsProxies_dontOverwriteUserHttps()
throws MojoExecutionException {
System.setProperty("https.proxyHost", "host");
MavenSettingsProxyProvider.activateHttpAndHttpsProxies(
mixedProxyEncryptedSettings, settingsDecrypter);
Assert.assertEquals("password1",... |
@Override
public Object getParameter(String key) {
return param.get(key);
} | @Test
void testGetParameter() {
ConfigRequest configRequest = new ConfigRequest();
String dataId = "id";
String group = "group";
String tenant = "n";
String content = "abc";
configRequest.setContent(content);
configRequest.setDataId(dataId);
c... |
protected Collection<URL> getUserClassPaths() {
return userClassPaths;
} | @Test
public void testGetUserClassPathReturnEmptyListIfJobDirIsNull() throws IOException {
final TestJobGraphRetriever testJobGraphRetriever = new TestJobGraphRetriever(null);
assertTrue(testJobGraphRetriever.getUserClassPaths().isEmpty());
} |
@Nullable
public HostsFileEntriesResolver hostsFileEntriesResolver() {
return hostsFileEntriesResolver;
} | @Test
void hostsFileEntriesResolverBadValues() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> builder.hostsFileEntriesResolver(null));
} |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void shouldThrowMaxRetriesExceptionAfterRetriesExhaustedWhenConfigured() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3)
.failAfte... |
@Override
public InetSocketAddress resolve(ServerWebExchange exchange) {
List<String> xForwardedValues = extractXForwardedValues(exchange);
if (!xForwardedValues.isEmpty()) {
int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex);
return new InetSocketAddress(xForwardedValues.get(index), 0);
}
... | @Test
public void maxIndexOneFallsBackToRemoteIp() {
ServerWebExchange exchange = buildExchange(remoteAddressOnlyBuilder());
InetSocketAddress address = trustOne.resolve(exchange);
assertThat(address.getHostName()).isEqualTo("0.0.0.0");
} |
@SuppressWarnings("unchecked")
public static JobContext cloneContext(JobContext original,
Configuration conf
) throws IOException,
InterruptedException {
try {
if (original insta... | @Test
public void testCloneContext() throws Exception {
ContextFactory.cloneContext(jobContext, conf);
} |
public Destination[] createDestinations(int destCount) throws JMSException {
final String destName = getClient().getDestName();
ArrayList<Destination> destinations = new ArrayList<>();
if (destName.contains(DESTINATION_SEPARATOR)) {
if (getClient().isDestComposite() && (destCount == ... | @Test
public void testCreateDestinations_multipleComposite() throws JMSException {
clientProperties.setDestComposite(true);
clientProperties.setDestName("queue://foo,queue://cheese");
Destination[] destinations = jmsClient.createDestinations(1);
assertEquals(1, destinations.length);
... |
static int bucketMaxUs(int bucket) {
return bucketMinUs(bucket + 1) - 1;
} | @Test
public void bucketMaxUs() {
assertEquals(1, LatencyDistribution.bucketMaxUs(0));
assertEquals(3, LatencyDistribution.bucketMaxUs(1));
assertEquals(7, LatencyDistribution.bucketMaxUs(2));
assertEquals(15, LatencyDistribution.bucketMaxUs(3));
assertEquals(31, LatencyDistr... |
@Override
public long nbigram() {
return freq2.size();
} | @Test
public void testGetNumBigrams() {
System.out.println("getNumBigrams");
assertEquals(18303, corpus.nbigram());
} |
static Set<String> convertToUpperCaseSet( String[] array ) {
if ( array == null ) {
return Collections.emptySet();
}
Set<String> strings = new HashSet<String>();
for ( String currentString : array ) {
strings.add( currentString.toUpperCase() );
}
return strings;
} | @Test
public void convertToUpperCaseSet_null_array() {
Set<String> actualResult = MetaInject.convertToUpperCaseSet( null );
assertNotNull( actualResult );
assertTrue( actualResult.isEmpty() );
} |
public File getDatabaseFile(String filename) {
File dbFile = null;
if (filename != null && filename.trim().length() > 0) {
dbFile = new File(filename);
}
if (dbFile == null || dbFile.isDirectory()) {
dbFile = new File(new AndroidContextUtil().getDatabasePath("logback.db"));
}
return ... | @Test
public void emptyFilenameResultsInDefault() throws IOException {
final File file = appender.getDatabaseFile("");
assertThat(file, is(notNullValue()));
assertThat(file.getName(), is("logback.db"));
} |
public synchronized Counter findCounter(String group, String name) {
if (name.equals("MAP_INPUT_BYTES")) {
LOG.warn("Counter name MAP_INPUT_BYTES is deprecated. " +
"Use FileInputFormatCounters as group name and " +
" BYTES_READ as counter name instead");
return findCounter... | @Test
public void testFilesystemCounter() {
GroupFactory groupFactory = new GroupFactoryForTest();
Group fsGroup = groupFactory.newFileSystemGroup();
org.apache.hadoop.mapreduce.Counter count1 =
fsGroup.findCounter("ANY_BYTES_READ");
Assert.assertNotNull(count1);
// Verify no exce... |
@Override
public String getName() {
return _name;
} | @Test
public void testStringSplitPartTransformFunction() {
int index = 1;
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("split_part(%s, 'ab', %d)", STRING_ALPHANUM_SV_COLUMN, index));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _d... |
@Override
public URL getResource(String name) {
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resource '{}'", name);
for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) {
URL url = null;
... | @Test
void parentLastGetResourceExistsOnlyInPlugin() throws IOException, URISyntaxException {
URL resource = parentLastPluginClassLoader.getResource("META-INF/plugin-file");
assertFirstLine("plugin", resource);
} |
@Override
public Class<ReportAnalysisFailureNotification> getNotificationClass() {
return ReportAnalysisFailureNotification.class;
} | @Test
public void getNotificationClass_is_ReportAnalysisFailureNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(ReportAnalysisFailureNotification.class);
} |
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
super.init(ctx);
this.mqttNodeConfiguration = TbNodeUtils.convert(configuration, TbMqttNodeConfiguration.class);
try {
this.mqttClient = initClient(ctx);
} catch (Excepti... | @Test
public void givenFailedByTimeoutConnectResult_whenInit_thenThrowsException() throws ExecutionException, InterruptedException, TimeoutException {
mqttNodeConfig.setHost("localhost");
mqttNodeConfig.setClientId("bfrbTESTmfkr23");
mqttNodeConfig.setCredentials(new CertPemCredentials());
... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test(dataProvider = "requestHandlersData")
public void testRequestHandlers(URI uri, String expectedResponse)
{
RestLiConfig config = new RestLiConfig();
config.addResourcePackageNames("com.linkedin.restli.server.twitter");
config.setDocumentationRequestHandler(new DefaultDocumentationRequestHandler() {... |
@Override
public boolean needToLoad(FilterInvoker invoker) {
AbstractInterfaceConfig<?, ?> config = invoker.getConfig();
String enabled = config.getParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED);
if (StringUtils.isNotBlank(enabled)) {
return Boolean.parseBoolean(enabled)... | @Test
public void testNeedToLoadConsumer() {
SentinelSofaRpcConsumerFilter consumerFilter = new SentinelSofaRpcConsumerFilter();
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setInterfaceId(Serializer.class.getName());
consumerConfig.setId("BBB");
Filte... |
public static String truncateUtf8(String str, int maxBytes) {
Charset charset = StandardCharsets.UTF_8;
//UTF-8编码单个字符最大长度4
return truncateByByteLength(str, charset, maxBytes, 4, true);
} | @Test
public void truncateUtf8Test3() {
final String str = "一二三四";
final String ret = StrUtil.truncateUtf8(str, 11);
assertEquals("一二...", ret);
} |
@Override
public boolean trySetCount(long count) {
return get(trySetCountAsync(count));
} | @Test
public void testDelete() throws Exception {
RCountDownLatch latch = redisson.getCountDownLatch("latch");
latch.trySetCount(1);
Assertions.assertTrue(latch.delete());
} |
private static Timestamp fromLong(Long elapsedSinceEpoch, TimestampPrecise precise) throws IllegalArgumentException {
final long seconds;
final int nanos;
switch (precise) {
case Millis:
seconds = Math.floorDiv(elapsedSinceEpoch, (long) THOUSAND);
nanos = (int) Math.floorMod(elapsedSinceEpo... | @Test
void timestampMicrosConversionSecondsLowerLimit() throws Exception {
assertThrows(IllegalArgumentException.class, () -> {
TimestampMicrosConversion conversion = new TimestampMicrosConversion();
long exceeded = (ProtoConversions.SECONDS_LOWERLIMIT - 1) * 1000000;
conversion.fromLong(exceede... |
@Override
public ByteBuf retainedSlice() {
return slice().retain();
} | @Test
public void testRetainedSliceAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertRetainedSliceFailAfterRelease(buf, buf2);
} |
@Override
public JobResourceRequirements requestJobResourceRequirements() {
final JobResourceRequirements.Builder builder = JobResourceRequirements.newBuilder();
for (JobInformation.VertexInformation vertex : jobInformation.getVertices()) {
builder.setParallelismForJobVertex(
... | @Test
void testRequestDefaultResourceRequirementsInReactiveMode() throws Exception {
final JobGraph jobGraph = createJobGraph();
final Configuration configuration = new Configuration();
configuration.set(JobManagerOptions.SCHEDULER_MODE, SchedulerExecutionMode.REACTIVE);
final Adapti... |
public static DistCpOptions parse(String[] args)
throws IllegalArgumentException {
CommandLineParser parser = new CustomParser();
CommandLine command;
try {
command = parser.parse(cliOptions, args, true);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to pars... | @Test
public void testParsebandwidth() {
DistCpOptions options = OptionsParser.parse(new String[] {
"hdfs://localhost:8020/source/first",
"hdfs://localhost:8020/target/"});
assertThat(options.getMapBandwidth()).isCloseTo(0f, within(DELTA));
options = OptionsParser.parse(new String[] {
... |
public void dropBackend(Backend backend) {
idToBackendRef.remove(backend.getId());
Map<Long, AtomicLong> copiedReportVersions = Maps.newHashMap(idToReportVersionRef);
copiedReportVersions.remove(backend.getId());
idToReportVersionRef = ImmutableMap.copyOf(copiedReportVersions);
} | @Test
public void testDropBackend() throws Exception {
new MockUp<RunMode>() {
@Mock
public RunMode getCurrentRunMode() {
return RunMode.SHARED_DATA;
}
};
Backend be = new Backend(10001, "newHost", 1000);
service.addBackend(be);
... |
@Override
public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication,
long blockSize, Progressable progress) throws IOException {
String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK);
Mode mode =... | @Test
public void hadoopShouldLoadFileSystemWithMultipleZkUri() throws Exception {
org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "zk@host1:2181,host2:2181,host3:2181/tmp/path.txt");
org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.get(ur... |
void removeWatchers() {
List<NamespaceWatcher> localEntries = Lists.newArrayList(entries);
while (localEntries.size() > 0) {
NamespaceWatcher watcher = localEntries.remove(0);
if (entries.remove(watcher)) {
try {
log.debug("Removing watcher for... | @Test
public void testMissingNode() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
try {
client.start();
WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCurator... |
public Optional<ReadwriteSplittingDataSourceGroupRule> findDataSourceGroupRule(final String dataSourceName) {
return Optional.ofNullable(dataSourceRuleGroups.get(dataSourceName));
} | @Test
void assertFindDataSourceGroupRule() {
Optional<ReadwriteSplittingDataSourceGroupRule> actual = createReadwriteSplittingRule().findDataSourceGroupRule("readwrite");
assertTrue(actual.isPresent());
assertDataSourceGroupRule(actual.get());
} |
@Override
public Iterable<Token> tokenize(String input, Language language, StemMode stemMode, boolean removeAccents) {
if (input.isEmpty()) return List.of();
List<Token> tokens = textToTokens(input, analyzerFactory.getAnalyzer(language, stemMode, removeAccents));
log.log(Level.FINEST, () ->... | @Test
public void testLithuanianTokenizer() {
String text = "Žalgirio mūšio data yra 1410 metai";
Iterable<Token> tokens = luceneLinguistics().getTokenizer()
.tokenize(text, Language.LITHUANIAN, StemMode.ALL, true);
assertEquals(List.of("žalgir", "mūš", "dat", "1410", "met"),... |
Map<TaskId, Task> allTasks() {
// not bothering with an unmodifiable map, since the tasks themselves are mutable, but
// if any outside code modifies the map or the tasks, it would be a severe transgression.
if (stateUpdater != null) {
final Map<TaskId, Task> ret = stateUpdater.getTa... | @Test
public void shouldReturnRunningTasksStateUpdaterTasksAndTasksToInitInAllTasks() {
final StreamTask activeTaskToInit = statefulTask(taskId01, taskId01ChangelogPartitions)
.inState(State.CREATED)
.withInputPartitions(taskId03Partitions).build();
final StreamTask runningAc... |
@Override
public Iterable<K> get() {
return StateFetchingIterators.readAllAndDecodeStartingFrom(
cache, beamFnStateClient, keysRequest, keyCoder);
} | @Test
public void testGetCached() throws Exception {
FakeBeamFnStateClient fakeBeamFnStateClient =
new FakeBeamFnStateClient(
ImmutableMap.of(
keysStateKey(), KV.of(ByteArrayCoder.of(), asList(A, B)),
key(A), KV.of(StringUtf8Coder.of(), asList("A1", "A2", "A3"))... |
public static List<Path> pluginUrls(Path topPath) throws IOException {
boolean containsClassFiles = false;
Set<Path> archives = new TreeSet<>();
LinkedList<DirectoryEntry> dfs = new LinkedList<>();
Set<Path> visited = new HashSet<>();
if (isArchive(topPath)) {
return... | @Test
public void testEmptyStructurePluginUrls() throws Exception {
createBasicDirectoryLayout();
assertEquals(Collections.emptyList(), PluginUtils.pluginUrls(pluginPath));
} |
@Override
public ImmutableList<String> computeEntrypoint(List<String> jvmFlags) throws IOException {
try (JarFile jarFile = new JarFile(jarPath.toFile())) {
String mainClass =
jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
if (mainClass == null) {
thr... | @Test
public void testComputeEntrypoint_noMainClass() throws URISyntaxException {
Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_EMPTY).toURI());
StandardPackagedProcessor standardPackagedModeProcessor =
new StandardPackagedProcessor(standardJar, JAR_JAVA_VERSION);
IllegalArgumen... |
static <S> List<Class<S>> getAllExtensionClass(Class<S> service) {
return InnerEnhancedServiceLoader.getServiceLoader(service).getAllExtensionClass(findClassLoader(), true);
} | @Test
public void getAllExtensionClass() {
List<Class<Hello>> allExtensionClass = EnhancedServiceLoader.getAllExtensionClass(Hello.class);
assertThat(allExtensionClass.get(3).getSimpleName()).isEqualTo((LatinHello.class.getSimpleName()));
assertThat(allExtensionClass.get(2).getSimpleName()).... |
@Override
public void close() {
close(Duration.ofMillis(0));
} | @Test
public void shouldThrowOnBeginTransactionIfProducerIsClosed() {
buildMockProducer(true);
producer.close();
assertThrows(IllegalStateException.class, producer::beginTransaction);
} |
public static void addSecurityProvider(Properties properties) {
properties.keySet().stream()
.filter(key -> key.toString().matches("security\\.provider(\\.\\d+)?"))
.sorted(Comparator.comparing(String::valueOf)).forEach(key -> addSecurityProvider(properties.get(key).toString()));... | @Test
void addSecurityProviderTestWithConfigForUnconfigurableProvider() {
removeAllDummyProviders();
int providersCountBefore = Security.getProviders().length;
SecurityProviderLoader.addSecurityProvider(DummyProvider.class.getName()+":0:Configure");
Provider[] providersAfter = Secu... |
protected static void parse(OldExcelExtractor extractor, XHTMLContentHandler xhtml)
throws TikaException, IOException, SAXException {
// Get the whole text, as a single string
String text = extractor.getText();
// Split and output
String line;
BufferedReader reader = ... | @Test
@Disabled
public void testMetadata() throws Exception {
TikaInputStream stream = getTestFile(file);
Metadata metadata = new Metadata();
ContentHandler handler = new BodyContentHandler();
OldExcelParser parser = new OldExcelParser();
parser.parse(stream, handler, m... |
public void removeJobMetricsGroup(JobID jobId) {
if (jobId != null) {
TaskManagerJobMetricGroup groupToClose;
synchronized (this) { // synchronization isn't strictly necessary as of FLINK-24864
groupToClose = jobs.remove(jobId);
}
if (groupToClose ... | @Test
void testRemoveInvalidJobID() {
metricGroup.removeJobMetricsGroup(JOB_ID);
} |
private RabinFingerprint() {
} | @Test
public void testRabinFingerprint() {
SchemaWriter writer = new SchemaWriter("SomeType");
writer.writeInt32("id", 0);
writer.writeString("name", null);
writer.writeInt8("age", (byte) 0);
writer.writeArrayOfTimestamp("times", null);
Schema schema = writer.build();... |
public static void tripSuggestions(
List<CharSequence> suggestions, final int maxSuggestions, List<CharSequence> stringsPool) {
while (suggestions.size() > maxSuggestions) {
removeSuggestion(suggestions, maxSuggestions, stringsPool);
}
} | @Test
public void testTrimSuggestionsWithMultipleRecycleBackToPool() {
ArrayList<CharSequence> list =
new ArrayList<>(
Arrays.<CharSequence>asList(
"typed",
"something",
"duped",
new StringBuilder("duped"),
new Str... |
@Override
public void suspend() {
if (!started) {
return;
}
LOG.info("Suspending the slot manager.");
slotManagerMetricGroup.close();
// stop the timeout checks for the TaskManagers
if (clusterReconciliationCheck != null) {
clusterReconcilia... | @Test
void testCloseAfterSuspendDoesNotThrowException() throws Exception {
new Context() {
{
runTest(() -> getSlotManager().suspend());
}
};
} |
public int distanceOf(PartitionTableView partitionTableView) {
int distance = 0;
for (int i = 0; i < partitions.length; i++) {
distance += distanceOf(partitions[i], partitionTableView.partitions[i]);
}
return distance;
} | @Test
public void testDistance_whenSomeReplicasNull() throws Exception {
// distanceOf([A, B, C, D...], [A, B, null...]) == count(null) * MAX_REPLICA_COUNT
PartitionTableView table1 = createRandomPartitionTable();
InternalPartition[] partitions = extractPartitions(table1);
Partition... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatDescribeTables() {
// Given:
final DescribeTables describeTables = new DescribeTables(Optional.empty(), false);
// When:
final String formatted = SqlFormatter.formatSql(describeTables);
// Then:
assertThat(formatted, is("DESCRIBE TABLES"));
} |
@Override
public InterpreterResult interpret(String cypherQuery, InterpreterContext interpreterContext) {
LOGGER.info("Opening session");
if (StringUtils.isBlank(cypherQuery)) {
return new InterpreterResult(Code.SUCCESS);
}
final List<String> queries = isMultiStatementEnabled ?
Array... | @Test
void testMultiLineInterpreter() {
Properties p = new Properties();
p.setProperty(Neo4jConnectionManager.NEO4J_SERVER_URL, neo4jContainer.getBoltUrl());
p.setProperty(Neo4jConnectionManager.NEO4J_AUTH_TYPE, Neo4jAuthType.NONE.toString());
p.setProperty(Neo4jConnectionManager.NEO4J_MAX_CONCURRENCY... |
@Nullable
public static URI getUriWithScheme(@Nullable final URI uri, final String scheme) {
if (uri == null) {
return null;
}
try {
return new URI(
scheme,
uri.getUserInfo(),
uri.getHost(),
... | @Test
public void testGetUriWithScheme() throws Exception {
assertEquals("gopher", Tools.getUriWithScheme(new URI("http://example.com"), "gopher").getScheme());
assertNull(Tools.getUriWithScheme(new URI("http://example.com"), null).getScheme());
assertNull(Tools.getUriWithScheme(null, "http"... |
public boolean validate(final Protocol protocol, final LoginOptions options) {
return protocol.validate(this, options);
} | @Test
public void testLoginWithoutPass() {
Credentials credentials = new Credentials("guest", null);
assertFalse(credentials.validate(new TestProtocol(Scheme.ftp), new LoginOptions()));
} |
@Override
public CRMaterial deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN);
} | @Test
public void shouldDeserializeGitMaterialType() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "git");
materialTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext);
verify(jsonDeserializationContext).deserialize(jsonObject, CRGitMate... |
@Override
public Character getCharAndRemove(K name) {
return null;
} | @Test
public void testGetCharAndRemoveDefault() {
assertEquals('x', HEADERS.getCharAndRemove("name1", 'x'));
} |
@Override
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = mapper.readTree(createParser(input));
if (node == null) {
th... | @Test
void handlesSingleElementArrayOverride() throws Exception {
System.setProperty("dw.type", "overridden");
final Example example = factory.build(configurationSourceProvider, validFile);
assertThat(example.getType())
.singleElement()
.isEqualTo("overridden");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.