focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static int durationStringLongToMs(String input) {
String[] parts = input.split(":");
if (parts.length != 3) {
return 0;
}
return Integer.parseInt(parts[0]) * 3600 * 1000
+ Integer.parseInt(parts[1]) * 60 * 1000
+ Integer.parseInt(parts[2... | @Test
public void testDurationStringLongToMs() {
String input = "01:20:30";
long expected = 4830000;
assertEquals(expected, Converter.durationStringLongToMs(input));
} |
public AwsAsgUtil getAwsAsgUtil() {
return awsAsgUtil;
} | @Test
public void testOverridesWithAsgEnabledThenDisabled() {
// Regular registration first
InstanceInfo myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);... |
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
int posx = Arrays.bina... | @Test
public void smallQuantilesAreTheFirstValue() {
assertThat(snapshot.getValue(0.0))
.isEqualTo(1.0, offset(0.1));
} |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetMonitoringInterceptorConfigPropertiesByClientType() {
// Given:
final Map<String, String> props = ImmutableMap.of(
"ksql.streams.consumer.confluent.monitoring.interceptor.topic", "foo",
"producer.confluent.monitoring.interceptor.topic", "bar"
);
final KsqlCo... |
protected FEEL newFeelEvaluator(AtomicReference<FEELEvent> errorHolder) {
// cleanup existing error
errorHolder.set(null);
FEEL feel = FEELBuilder.builder().withProfiles(singletonList(new ExtendedDMNProfile())).build();
feel.addListener(event -> {
FEELEvent feelEvent = errorH... | @Test
public void listener_singleSyntaxError() {
FEELEvent syntaxErrorEvent = new SyntaxErrorEvent(Severity.ERROR, "test", null, 0, 0, null);
AtomicReference<FEELEvent> error = new AtomicReference<>();
FEEL feel = expressionEvaluator.newFeelEvaluator(error);
applyEvents(List.of(synt... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_table__transposed() {
DataTable table = parse("",
" | | 1 | 2 | 3 |",
" | A | ♘ | | ♝ |",
" | B | | | |",
" | C | | ♝ | |");
assertEquals(table.transpose(), converter.convert(table, DataTable.class, true));
... |
public static boolean isValidOrigin(String sourceHost, ZeppelinConfiguration zConf)
throws UnknownHostException, URISyntaxException {
String sourceUriHost = "";
if (sourceHost != null && !sourceHost.isEmpty()) {
sourceUriHost = new URI(sourceHost).getHost();
sourceUriHost = (sourceUriHost ==... | @Test
void isLocalhost() throws URISyntaxException, UnknownHostException {
assertTrue(CorsUtils.isValidOrigin("http://localhost", ZeppelinConfiguration.load()));
} |
public WikipediaEditsSource() {
this(DEFAULT_HOST, DEFAULT_PORT, DEFAULT_CHANNEL);
} | @TestTemplate
@RetryOnFailure(times = 1)
void testWikipediaEditsSource() throws Exception {
if (canConnect(1, TimeUnit.SECONDS)) {
final Time testTimeout = Time.seconds(60);
final WikipediaEditsSource wikipediaEditsSource = new WikipediaEditsSource();
ExecutorService... |
@Nullable
public synchronized Beacon track(@NonNull Beacon beacon) {
Beacon trackedBeacon = null;
if (beacon.isMultiFrameBeacon() || beacon.getServiceUuid() != -1) {
trackedBeacon = trackGattBeacon(beacon);
}
else {
trackedBeacon = beacon;
}
re... | @Test
public void multiFrameBeaconProgramaticParserAssociationDifferentServiceUUIDFieldsGetUpdated() {
Beacon beacon = getMultiFrameBeacon();
Beacon beaconUpdate = getMultiFrameBeaconUpdateDifferentServiceUUID();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker(false);
tra... |
public DecoderResult decode(AztecDetectorResult detectorResult) throws FormatException {
ddata = detectorResult;
BitMatrix matrix = detectorResult.getBits();
boolean[] rawbits = extractBits(matrix);
CorrectedBitsResult correctedBits = correctBits(rawbits);
byte[] rawBytes = convertBoolArrayToByteArr... | @Test(expected = FormatException.class)
public void testDecodeTooManyErrors() throws FormatException {
BitMatrix matrix = BitMatrix.parse(""
+ "X X . X . . . X X . . . X . . X X X . X . X X X X X . \n"
+ "X X . . X X . . . . . X X . . . X X . . . X . X . . X \n"
+ "X . . . X X . . X X X . ... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertEmptyObjectMessageToAmqpMessageWithAmqpValueBody() throws Exception {
ActiveMQObjectMessage outbound = createObjectMessage();
outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_VALUE_BINARY);
outbound.onSend();
outbound.storeContent();
JM... |
@Override
protected Set<StepField> getUsedFields( ExcelInputMeta meta ) {
Set<StepField> usedFields = new HashSet<>();
if ( meta.isAcceptingFilenames() && StringUtils.isNotEmpty( meta.getAcceptingStepName() ) ) {
StepField stepField = new StepField( meta.getAcceptingStepName(), meta.getAcceptingField() ... | @Test
public void testGetUsedFields_isAcceptingFilenamesButNoStepName() throws Exception {
lenient().when( meta.isAcceptingFilenames() ).thenReturn( true );
lenient().when( meta.getAcceptingField() ).thenReturn( "filename" );
lenient().when( meta.getAcceptingStepName() ).thenReturn( null );
Set<StepFi... |
public <E extends T> boolean processEvent(E event) {
boolean consumed = false;
if (!onEventConsumers.isEmpty()) {
for (EventConsumer<T> onEventConsumer : onEventConsumers) {
onEventConsumer.consumeEvent(event);
}
consumed = true;
}
if ... | @Test
public void testNoConsumers() {
EventProcessor<Number> eventProcessor = new EventProcessor<>();
boolean consumed = eventProcessor.processEvent(1);
assertThat(consumed).isFalse();
} |
@Override
public boolean put(K key, V value) {
return get(putAsync(key, value));
} | @Test
public void testEntrySet() {
RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("test1");
map.put(new SimpleKey("0"), new SimpleValue("1"));
map.put(new SimpleKey("0"), new SimpleValue("1"));
map.put(new SimpleKey("3"), new SimpleValue("4"));
assertTh... |
public String decryptFilename(final BaseEncoding encoding, final String ciphertextName, final byte[] associatedData) throws AuthenticationFailedException {
final CacheKey key = new CacheKey(encoding, ciphertextName, associatedData);
if(decryptCache.contains(key)) {
return decryptCache.get(ke... | @Test
public void TestDecryptFilename() {
final FileNameCryptor mock = mock(FileNameCryptor.class);
final CryptorCache cryptor = new CryptorCache(mock);
when(mock.decryptFilename(any(), any(), any())).thenReturn(RandomStringUtils.randomAscii(10));
final String decrypted1 = cryptor.de... |
@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
final Set<Evidence> remove;
if (dependency.getVersion() != null) {
remove = dependency.getEvidence(EvidenceType.VERSION).stream()
.filter(e -> !e.isFromHint() ... | @Test
public void testAnalyzeDependency() throws Exception {
Dependency dependency = new Dependency();
dependency.addEvidence(EvidenceType.VERSION, "util", "version", "33.3", Confidence.HIGHEST);
dependency.addEvidence(EvidenceType.VERSION, "other", "version", "alpha", Confidence.HIGHEST);
... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations", enabled=false)
public void testHandleWrongContentType(MultiplexerRunMode multiplexerRunMode) throws Exception
{
MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(null, multiplexerRunMode);
RestRequest request = muxRequestBuilder()
.setMet... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 1, 1, HELP);
final String filePath = args.get(0);
final String content = loadScript(filePath);
requestExecutor.makeKsqlRequest(content);
} | @Test
public void shouldExecuteScript() {
// When:
cmd.execute(ImmutableList.of(scriptFile.toString()), terminal);
// Then:
verify(requestExecutor).makeKsqlRequest(FILE_CONTENT);
} |
public Method get(Object object) {
return get(object, null);
} | @Test
void testCache() throws Exception {
URL url = MethodCacheTest.class.getClassLoader().getResource("dummy").toURI().resolve(".").toURL();
class MyLoader extends URLClassLoader {
MyLoader() { super(new URL[] { url }, MethodCacheTest.class.getClassLoader()); }
public Clas... |
public boolean filter(char[] content, int offset, int length) {
if (content == null) {
return false;
}
boolean filtered = false;
for (int i = offset; i < offset + length; i++) {
if (isFiltered(content[i])) {
filtered = true;
conten... | @Test
public void testFilter1ArgNonFiltered() {
when(nonXmlCharFiltererMock.filter(anyString())).thenCallRealMethod();
when(nonXmlCharFiltererMock.filter(any(char[].class), anyInt(), anyInt())).thenReturn(false);
String string = "abc";
String result = nonXmlCharFiltererMock.filter(s... |
@Override
public void register() {
client.register();
} | @Test
public void register() {
scRegister.register();
Mockito.verify(scClient, Mockito.times(1)).register();
} |
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
} | @Test
void shouldReturnTrueForDistinctKeys() {
Function<Object, Object> keyExtractor = Object::getClass;
Predicate<Object> distinctByKey = LambdaUtils.distinctByKey(keyExtractor);
boolean result = distinctByKey.test(new Object());
assertTrue(result);
} |
public boolean isAdmin(Admin admin) {
return !isSecurityEnabled() || noAdminsConfigured() || adminsConfig.isAdmin(admin, rolesConfig.memberRoles(admin));
} | @Test
public void shouldKnowIfRoleIsAdmin() throws Exception {
SecurityConfig security = security(passwordFileAuthConfig(), admins(role("role1")));
assertThat(security.isAdmin(new AdminUser(new CaseInsensitiveString("chris"))), is(true));
assertThat(security.isAdmin(new AdminUser(new CaseIns... |
public static String getQuotedFqtn(String fqtn) {
String[] fqtnTokens = fqtn.split("\\.");
// adding single quotes around fqtn for cases when db and/or tableName has special character(s),
// like '-'
return String.format("`%s`.`%s`", fqtnTokens[0], fqtnTokens[1]);
} | @Test
void testGetQuotedFqtn() {
Assertions.assertEquals("`db`.`table-name`", SparkJobUtil.getQuotedFqtn("db.table-name"));
Assertions.assertEquals(
"`db-dashed`.`table-name`", SparkJobUtil.getQuotedFqtn("db-dashed.table-name"));
} |
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 shouldFindOneArgConflict() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING),
function(OTHER, -1, INT)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING)));
// Then:
assertThat(fun.na... |
public static void main(final String[] args) {
var view = new View();
view.createView();
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static int toInt(final String str, final int defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
} | @Test
public void testToInReturnParsedValue() {
Assertions.assertEquals(10, NumberUtils.toInt("10", 9));
} |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
cachedNanoClock.update(nowNs);
dutyCycleTracker.measureAndUpdate(nowNs);
final int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT);
final long shortSendsBefore = shortSen... | @Test
void shouldBeAbleToSendOnChannelTwice()
{
final StatusMessageFlyweight msg = mock(StatusMessageFlyweight.class);
when(msg.consumptionTermId()).thenReturn(INITIAL_TERM_ID);
when(msg.consumptionTermOffset()).thenReturn(0);
when(msg.receiverWindowLength()).thenReturn(2 * ALIGN... |
@Override
public final int position() {
return pos;
} | @Test(expected = IllegalArgumentException.class)
public void testPositionNewPos_HighNewPos() {
in.position(INIT_DATA.length + 10);
} |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherVal... | @Test
void assertCompareToWhenFirstValueIsNullForOrderByAscAndNullsLast() {
assertThat(CompareUtils.compareTo(null, 1, OrderDirection.ASC, NullsOrderType.LAST, caseSensitive), is(1));
} |
@Override
public void executeWithLock(Runnable task) {
Optional<LockConfiguration> lockConfigOptional = lockConfigurationExtractor.getLockConfiguration(task);
if (lockConfigOptional.isEmpty()) {
logger.debug("No lock configuration for {}. Executing without lock.", task);
task... | @Test
void executeIfLockAvailable() {
when(lockConfigurationExtractor.getLockConfiguration(task)).thenReturn(Optional.of(LOCK_CONFIGURATION));
when(lockProvider.lock(LOCK_CONFIGURATION)).thenReturn(Optional.of(lock));
defaultLockManager.executeWithLock(task);
verify(task).run();
... |
@Override
void execute() throws HiveMetaException {
// Need to confirm unless it's a dry run or specified -yes
if (!schemaTool.isDryRun() && !this.yes) {
boolean confirmed = promptToConfirm();
if (!confirmed) {
System.out.println("Operation cancelled, exiting.");
return;
}
... | @Test
public void testExecuteWithYes() throws Exception {
setUpTwoDatabases();
uut.yes = true;
uut.execute();
Mockito.verify(stmtMock, times(3)).execute(anyString());
} |
public ApplicationResourceUsageReport getResourceUsageReport() {
writeLock.lock();
try {
AggregateAppResourceUsage runningResourceUsage =
getRunningAggregateAppResourceUsage();
Resource usedResourceClone = Resources.clone(
attemptResourceUsage.getAllUsed());
Resource reserv... | @Test
public void testAppPercentagesOnswitch() throws Exception {
FifoScheduler scheduler = mock(FifoScheduler.class);
when(scheduler.getClusterResource()).thenReturn(Resource.newInstance(0, 0));
when(scheduler.getResourceCalculator())
.thenReturn(new DefaultResourceCalculator());
Application... |
@Nullable static String route(ContainerRequest request) {
ExtendedUriInfo uriInfo = request.getUriInfo();
List<UriTemplate> templates = uriInfo.getMatchedTemplates();
int templateCount = templates.size();
if (templateCount == 0) return "";
StringBuilder builder = null; // don't allocate unless you n... | @Test void route_invalid() {
setBaseUri("/");
when(uriInfo.getMatchedTemplates()).thenReturn(Arrays.asList(
new PathTemplate("/"),
new PathTemplate("/")
));
assertThat(SpanCustomizingApplicationEventListener.route(request))
.isEmpty();
} |
public JetConfig getJetConfig() {
return jetConfig;
} | @Test
public void when_instanceIsCreatedWithOverriddenDefaultConfiguration_then_defaultConfigurationIsNotChanged() {
Config config = new Config();
DataPersistenceConfig dataPersistenceConfig = new DataPersistenceConfig();
dataPersistenceConfig.setEnabled(true);
config.addMapConfig(ge... |
@Override
public void setMonochrome(boolean monochrome) {
formats = monochrome ? monochrome() : ansi();
} | @Test
void should_print_encoded_characters() {
Feature feature = TestFeatureParser.parse("path/test.feature", "" +
"Feature: Test feature\n" +
" Scenario: Test Characters\n" +
" Given first step\n" +
" | URLEncoded | %71s%22i%22%3A%7B... |
private void verifyTaskGenerationAndOwnership(ConnectorTaskId id, int initialTaskGen) {
log.debug("Reading to end of config topic to ensure it is still safe to bring up source task {} with exactly-once support", id);
if (!refreshConfigSnapshot(Long.MAX_VALUE)) {
throw new ConnectException("F... | @Test
public void testVerifyTaskGeneration() {
Map<String, Integer> taskConfigGenerations = new HashMap<>();
herder.configState = new ClusterConfigState(
1,
null,
Collections.singletonMap(CONN1, 3),
Collections.singletonMap(CONN1, CONN1... |
public static List<String> getFilterNames( Document webXml )
{
return getNames( "filter", webXml );
} | @Test
public void testGetFilterNames() throws Exception
{
// Setup fixture.
final Document webXml = WebXmlUtils.asDocument( new File( Objects.requireNonNull(WebXmlUtilsTest.class.getResource("/org/jivesoftware/util/test-web.xml")).toURI() ) );
// Execute system under test.
final... |
@Override
public byte[] serialize(final String topicName, final T record) {
return serializer.get().serialize(topicName, record);
} | @Test
public void shouldUseAThreadLocalSerializer() throws InterruptedException {
final List<Serializer<GenericRow>> serializers = new LinkedList<>();
final ThreadLocalSerializer<GenericRow> serializer = new ThreadLocalSerializer<>(
() -> {
final Serializer<GenericRow> local = mock(Serializ... |
public void addListener(ExtensionLoaderListener<T> listener) {
synchronized (this) {
if (!listeners.contains(listener)) {
this.listeners.add(listener);
for (ExtensionClass<T> value : all.values()) {
try {
listener.onLoad(val... | @Test
public void testAddListener(){
ExtensionLoader<Filter> extensionLoader = ExtensionLoaderFactory.getExtensionLoader(Filter.class);
extensionLoader.loadExtension(DynamicFilter.class);
ConcurrentMap<String, ExtensionClass<Filter>> all = extensionLoader.all;
String alias = "dynamic... |
@Override
protected Mono<Boolean> doMatcher(final ServerWebExchange exchange, final WebFilterChain chain) {
String path = exchange.getRequest().getURI().getRawPath();
return Mono.just(paths.contains(path));
} | @Test
public void testDoNotMatcher() {
ServerWebExchange webExchange =
MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost:8080/"));
Mono<Boolean> filter = fallbackFilter.doMatcher(webExchange, webFilterChain);
StepVerifier.create(... |
@Override
protected void analyzeDependency(final Dependency dependency, final Engine engine) throws AnalysisException {
// batch request component-reports for all dependencies
synchronized (FETCH_MUTIX) {
if (reports == null) {
try {
requestDelay();
... | @Test
public void should_analyzeDependency_fail_when_socket_error_from_sonatype() throws Exception {
// Given
OssIndexAnalyzer analyzer = new OssIndexAnalyzerThrowingSocketTimeout();
getSettings().setBoolean(Settings.KEYS.ANALYZER_OSSINDEX_WARN_ONLY_ON_REMOTE_ERRORS, false);
analyze... |
@Override
public CompletableFuture<Map<String, BrokerLookupData>> filterAsync(Map<String, BrokerLookupData> brokers,
ServiceUnitId serviceUnit,
LoadManagerContext context) ... | @Test
public void test() throws IllegalAccessException, BrokerFilterException, ExecutionException, InterruptedException {
LoadManagerContext context = getContext();
LoadDataStore<BrokerLoadData> store = context.brokerLoadDataStore();
BrokerLoadData maxTopicLoadData = new BrokerLoadData();
... |
@Override
public boolean dropTable(TableIdentifier identifier, boolean purge) {
if (!tableExists(identifier)) {
return false;
}
EcsURI tableObjectURI = tableURI(identifier);
if (purge) {
// if re-use the same instance, current() will throw exception.
TableOperations ops = newTableOp... | @Test
public void testRegisterExistingTable() {
TableIdentifier identifier = TableIdentifier.of("a", "t1");
ecsCatalog.createTable(identifier, SCHEMA);
Table registeringTable = ecsCatalog.loadTable(identifier);
TableOperations ops = ((HasTableOperations) registeringTable).operations();
String meta... |
static Set<String> parseStaleDataNodeList(String liveNodeJsonString,
final int blockThreshold, final Logger log) throws IOException {
final Set<String> dataNodesToReport = new HashSet<>();
JsonFactory fac = JacksonUtil.createBasicJsonFactory();
JsonParser parser = fac.createParser(IOUtils
.to... | @Test
public void testParseStaleDatanodeListSingleDatanode() throws Exception {
// Confirm all types of values can be properly parsed
String json = "{"
+ "\"1.2.3.4:5\": {"
+ " \"numBlocks\": 5,"
+ " \"fooString\":\"stringValue\","
+ " \"fooInteger\": 1,"
+ " \"fooF... |
public static Status unblock(
final UnsafeBuffer logMetaDataBuffer,
final UnsafeBuffer termBuffer,
final int blockedOffset,
final int tailOffset,
final int termId)
{
Status status = NO_ACTION;
int frameLength = frameLengthVolatile(termBuffer, blockedOffset);
... | @Test
void shouldScanForwardForNextCompleteMessage()
{
final int messageLength = HEADER_LENGTH * 4;
final int termOffset = 0;
final int tailOffset = messageLength * 2;
when(mockTermBuffer.getIntVolatile(messageLength)).thenReturn(messageLength);
assertEquals(
... |
public static String getMigrationsDir(
final String configFilePath,
final MigrationConfig config
) {
final String migrationsDir = config.getString(MigrationConfig.KSQL_MIGRATIONS_DIR_OVERRIDE);
if (migrationsDir != null && !migrationsDir.isEmpty()) {
return migrationsDir;
} else {
... | @Test
public void shouldOverrideMigrationsDirFromConfig() {
// Given:
when(config.getString(MigrationConfig.KSQL_MIGRATIONS_DIR_OVERRIDE)).thenReturn(CUSTOM_DIR);
// When / Then:
assertThat(MigrationsDirectoryUtil.getMigrationsDir(migrationsConfigPath, config), is(CUSTOM_DIR));
} |
@Override
public String getAELSafeURIString() {
throw new UnsupportedOperationException( String.format(
"This connection file object does not support this operation: '%s'",
this.getOriginalURIString() ) );
} | @Test( expected = UnsupportedOperationException.class )
public void testGetAELSafeURIString() {
fileObject.getAELSafeURIString();
} |
public static Path copyFile(Resource src, Path target, CopyOption... options) throws IORuntimeException {
Assert.notNull(src, "Source is null !");
if(src instanceof FileResource){
return copyFile(((FileResource) src).getFile().toPath(), target, options);
}
try(InputStream stream = src.getStream()){
return... | @Test
@Disabled
public void copyFileTest(){
PathUtil.copyFile(
Paths.get("d:/test/1595232240113.jpg"),
Paths.get("d:/test/1595232240113_copy.jpg"),
StandardCopyOption.COPY_ATTRIBUTES,
StandardCopyOption.REPLACE_EXISTING
);
} |
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) {
if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) {
throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'.");
}
return loadManagerWrapper.get();... | @Test(enabled = false)
public static void testOptimizeUnloadDisable(TopicDomain topicDomain,
String defaultTestNamespace,
PulsarAdmin admin,
String brokerServiceUrl,
... |
@Override
public Object getDefaultValue() {
return defaultValue;
} | @Test
public void testGetDefaultValue() throws Exception {
final ListField list = new ListField("list", "The List", ImmutableList.of("Foo", "Bar", "Baz"), "Hello, this is a list", ConfigurationField.Optional.NOT_OPTIONAL);
final Object defaultValue = list.getDefaultValue();
assertThat(defaul... |
public List<String> build() {
if (columnDefs.isEmpty()) {
throw new IllegalStateException("No column has been defined");
}
switch (dialect.getId()) {
case PostgreSql.ID:
return createPostgresQuery();
case Oracle.ID:
return createOracleQuery();
default:
return ... | @Test
public void update_not_nullable_column_on_mssql() {
assertThat(createNotNullableBuilder(new MsSql()).build())
.containsOnly("ALTER TABLE issues ALTER COLUMN name NVARCHAR (10) NOT NULL");
} |
@Override
public final void init(@Nonnull Outbox outbox, @Nonnull Context context) throws Exception {
this.outbox = outbox;
this.logger = context.logger();
init(context);
} | @Test(expected = UnknownHostException.class)
public void when_customInitThrows_then_initRethrows() throws Exception {
new MockP().setInitError(UnknownHostException::new)
.init(mock(Outbox.class), new TestProcessorContext());
} |
public String getReplicaInfos() {
StringBuilder sb = new StringBuilder();
try (CloseableLock ignored = CloseableLock.lock(this.rwLock.readLock())) {
for (Replica replica : replicas) {
sb.append(String.format("%d:%d/%d/%d/%d:%s:%s,", replica.getBackendId(), replica.getVersion(... | @Test
public void testGetReplicaInfos() {
LocalTablet tablet = new LocalTablet();
Replica replica1 = new Replica(1L, 10001L, 8,
-1, 10, 10, ReplicaState.NORMAL, 9, 8);
Replica replica2 = new Replica(1L, 10002L, 9,
-1, 10, 10, ReplicaState.NORMAL, -1, 9);
... |
protected abstract FullHttpRequest newHandshakeRequest(); | @Test
public void testDuplicateWebsocketHandshakeHeaders() {
URI uri = URI.create("ws://localhost:9999/foo");
HttpHeaders inputHeaders = new DefaultHttpHeaders();
String bogusSubProtocol = "bogusSubProtocol";
String bogusHeaderValue = "bogusHeaderValue";
// add values for t... |
@Bean("Languages")
public Languages provide(Optional<List<Language>> languages) {
if (languages.isPresent()) {
return new Languages(languages.get().toArray(new Language[0]));
} else {
return new Languages();
}
} | @Test
public void should_provide_instance_when_languages() {
Language A = mock(Language.class);
when(A.getKey()).thenReturn("a");
Language B = mock(Language.class);
when(B.getKey()).thenReturn("b");
LanguagesProvider provider = new LanguagesProvider();
List<Language> languageList = Arrays.asL... |
public static AWSCloudCredential buildGlueCloudCredential(HiveConf hiveConf) {
for (CloudConfigurationProvider factory : cloudConfigurationFactoryChain) {
if (factory instanceof AWSCloudConfigurationProvider) {
AWSCloudConfigurationProvider provider = ((AWSCloudConfigurationProvider)... | @Test
public void testGlueCredential() {
HiveConf conf = new HiveConf();
conf.set(CloudConfigurationConstants.AWS_GLUE_USE_AWS_SDK_DEFAULT_BEHAVIOR, "true");
AWSCloudCredential cred = CloudConfigurationFactory.buildGlueCloudCredential(conf);
Assert.assertNotNull(cred);
Assert... |
public Collection<ComputeNodeInstance> loadAllComputeNodeInstances() {
Collection<ComputeNodeInstance> result = new LinkedList<>();
for (InstanceType each : InstanceType.values()) {
result.addAll(loadComputeNodeInstances(each));
}
return result;
} | @Test
void assertLoadAllComputeNodeInstances() {
when(repository.getChildrenKeys("/nodes/compute_nodes/online/jdbc")).thenReturn(Collections.singletonList("foo_instance_3307"));
when(repository.getChildrenKeys("/nodes/compute_nodes/online/proxy")).thenReturn(Collections.singletonList("foo_instance_3... |
@VisibleForTesting
public SmsChannelDO validateSmsChannel(Long channelId) {
SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId);
if (channelDO == null) {
throw exception(SMS_CHANNEL_NOT_EXISTS);
}
if (CommonStatusEnum.isDisable(channelDO.getStatus())) {
... | @Test
public void testValidateSmsChannel_disable() {
// 准备参数
Long channelId = randomLongId();
// mock 方法
SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> {
o.setId(channelId);
o.setStatus(CommonStatusEnum.DISABLE.getStatus()); // 保证 status 禁用,触发失败
... |
private Function<KsqlConfig, Kudf> getUdfFactory(
final Method method,
final UdfDescription udfDescriptionAnnotation,
final String functionName,
final FunctionInvoker invoker,
final String sensorName
) {
return ksqlConfig -> {
final Object actualUdf = FunctionLoaderUtils.instan... | @Test
public void shouldLoadDecimalUdfs() {
// Given:
final SqlDecimal schema = SqlTypes.decimal(2, 1);
// When:
final KsqlScalarFunction fun = FUNC_REG.getUdfFactory(FunctionName.of("floor"))
.getFunction(ImmutableList.of(SqlArgument.of(schema)));
// Then:
assertThat(fun.name().text... |
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeySpecException,
InvalidAlgorithmParameterException,... | @Test
public void testPkcs1UnencryptedRsa() throws Exception {
PrivateKey key = SslContext.toPrivateKey(
new File(getClass().getResource("rsa_pkcs1_unencrypted.key").getFile()), null);
assertNotNull(key);
} |
public void combine(AnalyzerSetting analyzerSetting) {
this.analyzer.putAll(analyzerSetting.getAnalyzer());
this.tokenizer.putAll(analyzerSetting.tokenizer);
this.filter.putAll(analyzerSetting.filter);
this.charFilter.putAll(analyzerSetting.charFilter);
} | @Test
public void combine() {
StorageModuleElasticsearchConfig elasticsearchConfig = new StorageModuleElasticsearchConfig();
AnalyzerSetting oapAnalyzerSetting = gson.fromJson(elasticsearchConfig.getOapAnalyzer(), AnalyzerSetting.class);
Assertions.assertEquals(oapAnalyzerSetting, getDefault... |
@PostMapping("edit")
public String updateProduct(@ModelAttribute(name = "product", binding = false) Product product,
UpdateProductPayload payload,
Model model,
HttpServletResponse response) {
try {
th... | @Test
void updateProduct_RequestIsInvalid_ReturnsProductEditPage() {
// given
var product = new Product(1, "Товар №1", "Описание товара №1");
var payload = new UpdateProductPayload(" ", null);
var model = new ConcurrentModel();
var response = new MockHttpServletResponse();
... |
public static QueryBuilder namedQuery(final String namedQuery) {
return new QueryBuilder() {
protected Query makeQueryObject(EntityManager entityManager) {
return entityManager.createNamedQuery(namedQuery);
}
@Override
public String toString() {
... | @Test
public void testNamedQueryBuilder() {
QueryBuilder q = QueryBuilder.namedQuery("step1");
assertNotNull(q);
assertEquals("Named: step1", q.toString());
} |
@Override
public void bind(
Map<String, Object> configurationProperties,
boolean ignoreUnknownFields,
boolean ignoreInvalidFields,
Object configurationBean) {
Iterable<PropertySource<?>> propertySources =
asList(new MapPropertySource("internal... | @Test
void testBinder() {
ApplicationConfig applicationConfig = new ApplicationConfig();
Map<String, Object> properties = getSubProperties(environment.getPropertySources(), "dubbo.application");
dubboConfigBinder.bind(properties, true, true, applicationConfig);
Assert.assertEquals("... |
public final Span joinSpan(TraceContext context) {
if (context == null) throw new NullPointerException("context == null");
if (!supportsJoin) return newChild(context);
// set shared flag if not already done
int flags = InternalPropagation.instance.flags(context);
if (!context.shared()) {
flag... | @Test void joinSpan_notYetSampledIsNotShared_child() {
TraceContext context =
TraceContext.newBuilder().traceId(1).parentId(2).spanId(3).shared(true).build();
Span span = tracer.joinSpan(context);
assertThat(span.context().shared()).isFalse();
} |
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
throws IOException, PKCSException, OperatorCreationException {
if (password == null || password.length == 0) {
return new PKCS8EncodedKeySpec(key);
}
final PKCS8EncryptedPrivateKeyInfo pri... | @Test
public void testGenerateKeySpecFromPBE1EncryptedPrivateKey() throws Exception {
final URL url = Resources.getResource("org/graylog2/shared/security/tls/key-enc-pbe1.p8");
final byte[] privateKey = PemReader.readPrivateKey(Paths.get(url.toURI()));
final PKCS8EncodedKeySpec keySpec = Pe... |
public Optional<Integer> findProjectionIndex(final String projectionName) {
int result = 1;
for (Projection each : projections) {
if (projectionName.equalsIgnoreCase(SQLUtils.getExactlyValue(each.getExpression()))) {
return Optional.of(result);
}
resul... | @Test
void assertFindProjectionIndex() {
Projection projection = getColumnProjection();
ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.singleton(projection));
Optional<Integer> actual = projectionsContext.findProjectionIndex(projection.getExpression())... |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldCoerceStringNumericWithENotationToDecimals() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of(
new IntegerLiteral(10),
new StringLiteral("1e3")
);
// When:
final Result result = CoercionUtil.coerceUserList(expressions, typeManager)... |
@Override
public byte[] serialize() {
byte[] payloadData = null;
if (this.payload != null) {
this.payload.setParent(this);
payloadData = this.payload.serialize();
}
this.payloadLength = 0;
if (payloadData != null) {
this.payloadLength = (s... | @Test
public void testSerialize() {
IPv6 ipv6 = new IPv6();
ipv6.setPayload(udp);
ipv6.setVersion((byte) 6);
ipv6.setTrafficClass((byte) 0x93);
ipv6.setFlowLabel(0x13579);
ipv6.setNextHeader(PROTOCOL_UDP);
ipv6.setHopLimit((byte) 32);
ipv6.setSourceAdd... |
@Override
public String builder(final String paramName, final ServerWebExchange exchange) {
return HostAddressUtils.acquireHost(exchange);
} | @Test
public void testBuilderWithAnyParamName() {
assertEquals(testhost, hostParameterData.builder(UUIDUtils.getInstance().generateShortUuid(), exchange));
} |
@Override
public String getResourceInputNodeType() {
return DictionaryConst.NODE_TYPE_FILE_FIELD;
} | @Test
public void testGetResourceInputNodeType() throws Exception {
assertEquals( DictionaryConst.NODE_TYPE_FILE_FIELD, analyzer.getResourceInputNodeType() );
} |
@Override
public MailAccountDO getMailAccount(Long id) {
return mailAccountMapper.selectById(id);
} | @Test
public void testGetMailAccount() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailAccount.getId();
// 调用
MailAccountDO mailAccount = mailAcco... |
public static <K, N, V, S extends State>
InternalKvState<K, N, ?> createStateAndWrapWithLatencyTrackingIfEnabled(
InternalKvState<K, N, ?> kvState,
StateDescriptor<S, V> stateDescriptor,
LatencyTrackingStateConfig latencyTrackingStateConfig)
... | @TestTemplate
@SuppressWarnings("unchecked")
<K, N> void testTrackAggregatingState() throws Exception {
InternalAggregatingState<K, N, Long, Long, Long> aggregatingState =
mock(InternalAggregatingState.class);
AggregatingStateDescriptor<Long, Long, Long> aggregatingStateDescripto... |
@Override
public void run() {
doHealthCheck();
} | @Test
void testRunHealthyInstanceWithHeartBeat() {
injectInstance(true, System.currentTimeMillis());
when(globalConfig.isExpireInstance()).thenReturn(true);
beatCheckTask.run();
assertFalse(client.getAllInstancePublishInfo().isEmpty());
assertTrue(client.getInstancePublishInf... |
@Override
public Node upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("multipart", con... | @Test
public void testUploadMissingTargetDirectory() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final SDSDirectS3UploadFeature feature = new SDSDirectS3UploadFeature(session, nodeid, new SDSDelegatingWriteFeature(session, nodeid, new SDSDirectS3WriteFeature(s... |
public static String[] parseUri(String uri) {
return doParseUri(uri, false);
} | @Test
public void testParseUri() {
String[] out1 = CamelURIParser.parseUri("smtp://localhost?username=davsclaus&password=secret");
assertEquals("smtp", out1[0]);
assertEquals("localhost", out1[1]);
assertEquals("username=davsclaus&password=secret", out1[2]);
} |
public GaugeProducer(MetricsEndpoint endpoint) {
super(endpoint);
Gauge<?> gauge = endpoint.getRegistry().getGauges().get(endpoint.getMetricsName());
if (gauge instanceof CamelMetricsGauge) {
CamelMetricsGauge camelMetricsGauge = (CamelMetricsGauge) gauge;
if (endpoint.ge... | @Test
public void testGaugeProducer() {
assertThat(producer.getEndpoint().equals(endpoint), is(true));
} |
@Override
public void configure(ResourceGroup group, SelectionContext<VariableMap> criteria)
{
Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry = getMatchingSpec(group, criteria);
if (groups.putIfAbsent(group.getId(), group) == null) {
// If a new spec replaces the spec re... | @Test
public void testConfiguration()
{
H2DaoProvider daoProvider = setup("test_configuration");
H2ResourceGroupsDao dao = daoProvider.get();
dao.createResourceGroupsGlobalPropertiesTable();
dao.createResourceGroupsTable();
dao.createSelectorsTable();
dao.insertRe... |
public HsDataView registerNewConsumer(
int subpartitionId,
HsConsumerId consumerId,
HsSubpartitionConsumerInternalOperations operation)
throws IOException {
synchronized (lock) {
checkState(!isReleased, "HsFileDataManager is already released.");
... | @Test
void testRunReleaseUnusedBuffers() throws Exception {
TestingHsSubpartitionFileReader reader = new TestingHsSubpartitionFileReader();
CompletableFuture<Void> prepareForSchedulingFinished = new CompletableFuture<>();
reader.setPrepareForSchedulingRunnable(() -> prepareForSchedulingFini... |
public static Builder forPage(int page) {
return new Builder(page);
} | @Test
void andSize_fails_with_IAE_if_size_is_0() {
Pagination.Builder builder = forPage(1);
assertThatThrownBy(() -> builder.andSize(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("page size must be >= 1");
} |
@Override
public KTable<K, V> reduce(final Reducer<V> adder,
final Reducer<V> subtractor,
final Materialized<K, V, KeyValueStore<Bytes, byte[]>> materialized) {
return reduce(adder, subtractor, NamedInternal.empty(), materialized);
} | @Test
public void shouldThrowNullPointerOnReduceWhenAdderIsNull() {
assertThrows(NullPointerException.class, () -> groupedTable.reduce(
null,
MockReducer.STRING_REMOVER,
Materialized.as("store")));
} |
public static <T> T checkNotNull(final T obj) {
return checkNotNull(obj, VALIDATE_IS_NOT_NULL_EX_MESSAGE);
} | @Test
public void testCheckNotNullSuccess() {
Preconditions.checkNotNull(NON_NULL_STRING);
// null supplier
Preconditions.checkNotNull(NON_NULL_STRING, null);
// ill-formated string supplier
Preconditions.checkNotNull(NON_NULL_STRING, ()-> String.format("%d",
NON_INT_STRING));
// null ... |
@Override
public <T> Serde<T> createSerde(
final Schema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srFactory,
final Class<T> targetType,
final boolean isKey
) {
validateSchema(schema);
final Optional<Schema> physicalSchema;
if (useSchemaRegis... | @Test
public void shouldThrowOnMapWithNoneStringKeys() {
// Given:
final ConnectSchema schemaOfInvalidMap = (ConnectSchema) SchemaBuilder
.map(Schema.OPTIONAL_BOOLEAN_SCHEMA, Schema.OPTIONAL_STRING_SCHEMA)
.build();
// When:
final Exception e = assertThrows(
KsqlException.clas... |
@Override
public String name() {
return internal.name();
} | @Test
public void shouldDelegateName() {
when(inner.name()).thenReturn(STORE_NAME);
assertThat(store.name(), is(STORE_NAME));
} |
@Override
public Collection<DatabasePacket> execute() throws SQLException {
switch (packet.getType()) {
case PREPARED_STATEMENT:
connectionSession.getServerPreparedStatementRegistry().removePreparedStatement(packet.getName());
break;
case PORTAL:
... | @Test
void assertExecuteClosePreparedStatement() throws SQLException {
when(connectionSession.getServerPreparedStatementRegistry()).thenReturn(new ServerPreparedStatementRegistry());
when(packet.getType()).thenReturn(PostgreSQLComClosePacket.Type.PREPARED_STATEMENT);
when(packet.getName()).t... |
public List<IntermediateRecord> trimInSegmentResults(GroupKeyGenerator groupKeyGenerator,
GroupByResultHolder[] groupByResultHolders, int size) {
// Should not reach here when numGroups <= heap size because there is no need to create a heap
assert groupKeyGenerator.getNumKeys() > size;
Iterator<GroupK... | @Test
public void testInSegmentTrim() {
TableResizer tableResizer =
new TableResizer(DATA_SCHEMA, QueryContextConverterUtils.getQueryContext(QUERY_PREFIX + "d3 DESC"));
List<IntermediateRecord> results =
tableResizer.trimInSegmentResults(_groupKeyGenerator, _groupByResultHolders, TRIM_TO_SIZE)... |
@Override
public <T> List<ExtensionWrapper<T>> find(Class<T> type) {
log.debug("Finding extensions of extension point '{}'", type.getName());
Map<String, Set<String>> entries = getEntries();
List<ExtensionWrapper<T>> result = new ArrayList<>();
// add extensions found in classpath a... | @Test
public void testFindFromPlugin() {
ExtensionFinder instance = new AbstractExtensionFinder(pluginManager) {
@Override
public Map<String, Set<String>> readPluginsStorages() {
Map<String, Set<String>> entries = new LinkedHashMap<>();
Set<String> b... |
public static Map<String, String> getMaskedConnectConfig(final Map<String, String> config) {
return config.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> {
if (ALLOWED_KEYS.contains(e.getKey())) {
return e.getValue();
}
return MASKED_STRING;
}));
} | @Test
public void shouldMaskConfigMap() {
// Given
final ImmutableMap<String, String> config = ImmutableMap.of(
"connector.class", "someclass",
"model", "somemode",
"key", "somekey"
);
// When
final Map<String, String> maskedConfig = QueryMask.getMaskedConnectConfig(config... |
public static <T> Collection<T> nullToEmpty(Collection<T> collection) {
return collection == null ? Collections.emptyList() : collection;
} | @Test
public void testNullToEmpty_whenNotNull() {
List<Integer> result = asList(1, 2, 3, 4, 5);
assertEquals(result, nullToEmpty(result));
} |
@Override
public double read() {
return gaugeSource.read();
} | @Test
public void whenNotVisitedWithCachedMetricSourceReadsDefault() {
DoubleGaugeImplTest.SomeObject someObject = new DoubleGaugeImplTest.SomeObject();
someObject.doubleField = 42.42D;
metricsRegistry.registerDynamicMetricsProvider(someObject);
DoubleGauge doubleGauge = metricsRegis... |
public Result resolve(List<PluginDescriptor> plugins) {
// create graphs
dependenciesGraph = new DirectedGraph<>();
dependentsGraph = new DirectedGraph<>();
// populate graphs
Map<String, PluginDescriptor> pluginByIds = new HashMap<>();
for (PluginDescriptor plugin : plu... | @Test
void goodDependencyVersion() {
PluginDescriptor pd1 = new DefaultPluginDescriptor()
.setPluginId("p1")
.setDependencies("p2@2.0.0");
PluginDescriptor pd2 = new DefaultPluginDescriptor()
.setPluginId("p2")
.setPluginVersion("2.0.0");
Lis... |
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
} | @Test
public void testExceptionInAbortSuppressed() throws Exception {
Operation o1 = Mockito.mock(Operation.class);
Operation o2 = Mockito.mock(Operation.class);
Operation o3 = Mockito.mock(Operation.class);
Operation o4 = Mockito.mock(Operation.class);
Mockito.doThrow(new Exception("in finish")).... |
public boolean matchNotification(StageConfigIdentifier stageIdentifier, StageEvent event,
MaterialRevisions materialRevisions) {
if (!shouldSendEmailToMe()) {
return false;
}
for (NotificationFilter filter : notificationFilters) {
if (... | @Test
void shouldReturnFalseWhenEmailIsEmpty() {
assertThat(new User("UserName", new String[]{"README"}, null, true).matchNotification(null, StageEvent.All, null)).isFalse();
assertThat(new User("UserName", new String[]{"README"}, "", true).matchNotification(null, StageEvent.All, null)).isFalse();
... |
@Override
@SuppressWarnings("unchecked")
public <T> T get(final PluginConfigSpec<T> configSpec) {
if (rawSettings.containsKey(configSpec.name())) {
Object o = rawSettings.get(configSpec.name());
if (configSpec.type().isAssignableFrom(o.getClass())) {
return (T) o;... | @Test
public void testDefaultCodec() {
PluginConfigSpec<Codec> codecConfig = PluginConfigSpec.codecSetting("codec", "java-line");
Configuration config = new ConfigurationImpl(Collections.emptyMap(), new TestPluginFactory());
Codec codec = config.get(codecConfig);
Assert.assertTrue(co... |
@Override
public Path copy(final Path source, final Path copy, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final String target = new DefaultUrlProvider(session.getHost()).toUrl(copy).find(DescriptiveUrl.Type.pr... | @Test
public void testCopyToExistingFile() throws Exception {
final Path folder = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
new DAVDirectoryFeature(session).mkdir(folder, new TransferStatus());
fin... |
@Override
public JobDetails postProcess(JobDetails jobDetails) {
if (isNotNullOrEmpty(substringBetween(jobDetails.getClassName(), "$$", "$$"))) {
return new JobDetails(
substringBefore(jobDetails.getClassName(), "$$"),
jobDetails.getStaticFieldName(),
... | @Test
void postProcessWithCGLibReturnsUpdatedJobDetails() {
// GIVEN
final JobDetails jobDetails = defaultJobDetails().withClassName(TestService.class.getName() + "$$EnhancerByCGLIB$$6aee664d").build();
// WHEN
final JobDetails result = cgLibPostProcessor.postProcess(jobDetails);
... |
public static List<CharSequence> unescapeCsvFields(CharSequence value) {
List<CharSequence> unescaped = new ArrayList<CharSequence>(2);
StringBuilder current = InternalThreadLocalMap.get().stringBuilder();
boolean quoted = false;
int last = value.length() - 1;
for (int i = 0; i <... | @Test
public void testUnescapeCsvFields() {
assertEquals(Collections.singletonList(""), unescapeCsvFields(""));
assertEquals(Arrays.asList("", ""), unescapeCsvFields(","));
assertEquals(Arrays.asList("a", ""), unescapeCsvFields("a,"));
assertEquals(Arrays.asList("", "a"), unescapeCsv... |
public static Predicate parse(String expression)
{
final Stack<Predicate> predicateStack = new Stack<>();
final Stack<Character> operatorStack = new Stack<>();
final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll("");
final StringTokenizer tokenizer = new StringTokenizer(tr... | @Test
public void testNotAndParenOr()
{
final Predicate parsed = PredicateExpressionParser.parse("!com.linkedin.data.it.AlwaysTruePredicate & !(com.linkedin.data.it.AlwaysTruePredicate | com.linkedin.data.it.AlwaysFalsePredicate)");
Assert.assertEquals(parsed.getClass(), AndPredicate.class);
final List... |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testNot() {
Evaluator evaluator = new Evaluator(STRUCT, not(equal("x", 7)));
assertThat(evaluator.eval(TestHelpers.Row.of(7))).as("not(7 == 7) => false").isFalse();
assertThat(evaluator.eval(TestHelpers.Row.of(8))).as("not(8 == 7) => false").isTrue();
Evaluator structEvaluator = new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.