focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public Object valueFrom(Struct struct) {
return valueFrom(struct, true);
} | @Test void shouldFindValueInStruct() {
Schema bazSchema = SchemaBuilder.struct()
.field("inner", Schema.STRING_SCHEMA)
.optional()
.build();
Schema barSchema = SchemaBuilder.struct()
.field("bar", Schema.INT32_SCHEMA)
.field("baz", bazSchema)
... |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateCastToTimestamp() {
// Given:
final Expression cast1 = new Cast(
new TimestampLiteral(Timestamp.from(Instant.ofEpochMilli(1000))),
new Type(SqlPrimitiveType.of("TIMESTAMP"))
);
final Expression cast2 = new Cast(
new StringLiteral("2017-11-13T23:5... |
public static int parseInt(String number) throws NumberFormatException {
if (StrUtil.isBlank(number)) {
return 0;
}
if (StrUtil.startWithIgnoreCase(number, "0x")) {
// 0x04表示16进制数
return Integer.parseInt(number.substring(2), 16);
}
if (StrUtil.containsIgnoreCase(number, "E")) {
// 科学计数法忽略支持,科学计数... | @Test
public void parseIntTest2() {
// from 5.4.8 issue#I23ORQ@Gitee
// 千位分隔符去掉
final int v1 = NumberUtil.parseInt("1,482.00");
assertEquals(1482, v1);
} |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testAnalyzePackageLock() throws Exception {
try (Engine engine = new Engine(getSettings())) {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "pip/Pipfile.lock"));
engine.addDependency(result);
analyzer.analyze(result, engine);
... |
@Override
public Set<FSTFlags> getFlags() {
return _flags;
} | @Test
public void testVersion5WithNumbers()
throws IOException {
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data/abc-numbers.native.fst")) {
FST fst = FST.read(inputStream);
assertTrue(fst.getFlags().contains(FSTFlags.NUMBERS));
verifyContent(fst, _expe... |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepWithInteger() {
Object result = Rubyfier.deep(RubyUtil.RUBY, 1);
assertEquals(RubyFixnum.class, result.getClass());
assertEquals(1L, ((RubyFixnum)result).getLongValue());
} |
@VisibleForTesting
static LookupResult parseBody(JsonPath singleJsonPath, @Nullable JsonPath multiJsonPath, InputStream body) {
try {
final DocumentContext documentContext = JsonPath.parse(body);
LookupResult.Builder builder = LookupResult.builder().cacheTTL(Long.MAX_VALUE);
... | @Test
public void parseEmptyBody() throws Exception {
final JsonPath singlePath = JsonPath.compile("$.hello");
final JsonPath multiPath = JsonPath.compile("$.list");
final LookupResult result = HTTPJSONPathDataAdapter.parseBody(singlePath, multiPath, emptyBody);
assertThat(result).i... |
public File zip(File source, File destZipFile, int level) throws IOException {
zipContents(source, new FileOutputStream(destZipFile), level, false);
return destZipFile;
} | @Test
void shouldPreserveFileTimestampWhileGeneratingTheZipFile() throws Exception {
File file = createFileInTempDir();
file.setLastModified(1297989100000L); // Set this to any date in the past which is greater than the epoch
File zip = zipUtil.zip(file, tempDir.resolve("foo.zip").toFile(), ... |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void factValueInt() {
assertThat(fact("foo", "the foo")).factValue("foo", 0).isEqualTo("the foo");
} |
@Override
public String getMediaType() {
return firstNonNull(
mediaTypeFromUrl(source.getRequestURI()),
firstNonNull(
acceptedContentTypeInResponse(),
MediaTypes.DEFAULT));
} | @Test
public void media_type_taken_in_url_first() {
when(source.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaTypes.JSON);
when(source.getRequestURI()).thenReturn("/path/to/resource/search.protobuf");
assertThat(underTest.getMediaType()).isEqualTo(MediaTypes.PROTOBUF);
} |
public List<ChangeStreamRecord> toChangeStreamRecords(
PartitionMetadata partition,
ChangeStreamResultSet resultSet,
ChangeStreamResultSetMetadata resultSetMetadata) {
if (this.isPostgres()) {
// In PostgresQL, change stream records are returned as JsonB.
return Collections.singletonLi... | @Test
public void testMappingStructRowToChildPartitionRecord() {
final ChildPartitionsRecord childPartitionsRecord =
new ChildPartitionsRecord(
Timestamp.ofTimeSecondsAndNanos(10L, 20),
"1",
Arrays.asList(
new ChildPartition("childToken1", Sets.newHashSe... |
public static Queue<Consumer<byte[]>> stopConsumers(final Queue<Consumer<byte[]>> consumers) throws PulsarClientException {
while (!consumers.isEmpty()) {
Consumer<byte[]> consumer = consumers.poll();
if (consumer != null) {
try {
consumer.close();
... | @Test
public void givenConsumerQueueIsNotEmptywhenIStopConsumersverifyEmptyQueueIsReturned() throws PulsarClientException {
Queue<Consumer<byte[]>> consumers = new ConcurrentLinkedQueue<>();
consumers.add(mock(Consumer.class));
Queue<Consumer<byte[]>> expected = PulsarUtils.stopConsumers(co... |
public void logAndProcessFailure(
String computationId,
ExecutableWork executableWork,
Throwable t,
Consumer<Work> onInvalidWork) {
if (shouldRetryLocally(computationId, executableWork.work(), t)) {
// Try again after some delay and at the end of the queue to avoid a tight loop.
... | @Test
public void logAndProcessFailure_doesNotRetryOOM() {
Set<Work> executedWork = new HashSet<>();
ExecutableWork work = createWork(executedWork::add);
WorkFailureProcessor workFailureProcessor =
createWorkFailureProcessor(streamingEngineFailureReporter());
Set<Work> invalidWork = new HashSe... |
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
} | @Test
public void verify_reportFailures_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = ReportAnalysisFailureNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(REPORT_FAILURE_DISPATCHER_KEY);
} |
public ComputeNode getBackendOrComputeNode(long nodeId) {
ComputeNode backend = idToBackendRef.get(nodeId);
if (backend == null) {
backend = idToComputeNodeRef.get(nodeId);
}
return backend;
} | @Test
public void testGetBackendOrComputeNode() {
mockNet();
Backend be = new Backend(10001, "host1", 1000);
service.addBackend(be);
ComputeNode cn = new ComputeNode(10002, "host2", 1000);
cn.setBePort(1001);
service.addComputeNode(cn);
Assert.assertEquals(b... |
@Override
public Class<? extends StorageBuilder> builder() {
return MaxStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), LARGE_VALUE);
function.calculate();
StorageBuilder<MaxFunction> storageBuilder = function.builder().newInstance();
final Has... |
public void deleteShardGroup(List<Long> groupIds) {
prepare();
try {
client.deleteShardGroup(serviceId, groupIds, true);
} catch (StarClientException e) {
LOG.warn("Failed to delete shard group. error: {}", e.getMessage());
}
} | @Test
public void testDeleteShardGroup() throws StarClientException, DdlException {
new Expectations() {
{
client.deleteShardGroup("1", (List<Long>) any, true);
minTimes = 0;
result = null;
}
};
Deencapsulation.setField... |
public List<Bson> parse(final List<String> filterExpressions,
final List<EntityAttribute> attributes) {
if (filterExpressions == null || filterExpressions.isEmpty()) {
return List.of();
}
final Map<String, List<Filter>> groupedByField = filterExpressions.s... | @Test
void returnsEmptyListOnNullFilterList() {
assertThat(toTest.parse(null, List.of()))
.isEmpty();
} |
public PaginatedList<StreamDestinationFilterRuleDTO> findPaginatedForStreamAndTarget(
String streamId,
String targetId,
String queryString,
Bson sort,
int perPage,
int page,
Predicate<String> permissionSelector
) {
final var... | @Test
@MongoDBFixtures("StreamDestinationFilterServiceTest-2024-07-01-1.json")
void findPaginatedForStreamAndTargetWithQuery() {
final var result = service.findPaginatedForStreamAndTarget("54e3deadbeefdeadbeef1000", "indexer", "status:disabled", Sorts.ascending("title"), 10, 1, id -> true);
ass... |
@SuppressWarnings("unchecked")
@Override
public synchronized ProxyInfo<T> getProxy() {
if (currentUsedHandler != null) {
return currentUsedHandler;
}
Map<String, ProxyInfo<T>> targetProxyInfos = new HashMap<>();
StringBuilder combinedInfo = new StringBuilder("[");
for (int i = 0; i < proxi... | @Test
public void testHedgingWhenConnectException() throws Exception {
ClientProtocol active = Mockito.mock(ClientProtocol.class);
Mockito.when(active.getStats()).thenThrow(new ConnectException());
ClientProtocol standby = Mockito.mock(ClientProtocol.class);
Mockito.when(standby.getStats())
.... |
@Override
public HttpResponseOutputStream<Metadata> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final DbxUserFilesRequests files = new DbxUserFilesRequests(session.getClient(file));
final UploadSessionStart... | @Test(expected = AccessDeniedException.class)
public void testWriteDS_Store() throws Exception {
final DropboxWriteFeature write = new DropboxWriteFeature(session);
final TransferStatus status = new TransferStatus();
final byte[] content = RandomUtils.nextBytes(0);
status.setLength(c... |
@Override
public void next(DeviceId deviceId, NextObjective nextObjective) {
process(deviceId, nextObjective);
} | @Test
public void next() {
// Note: ADD operation won't query this
expect(mgr.flowObjectiveStore.getNextGroup(NID1)).andReturn(NGRP1).times(3);
expect(mgr.flowObjectiveStore.getNextGroup(NID2)).andReturn(NGRP2).times(3);
replay(mgr.flowObjectiveStore);
expectNextObjs.forEach... |
@Override
@CheckForNull
public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) {
String bundleKey = propertyToBundles.get(key);
String value = null;
if (bundleKey != null) {
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(bundle... | @Test
public void get_english_labels_when_default_locale_is_not_english() {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.FRENCH);
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
assertThat(underTest.message(Locale.ENGLISH, "sqale.pag... |
void fetchPluginSettingsMetaData(GoPluginDescriptor pluginDescriptor) {
String pluginId = pluginDescriptor.id();
List<ExtensionSettingsInfo> allMetadata = findSettingsAndViewOfAllExtensionsIn(pluginId);
List<ExtensionSettingsInfo> validMetadata = allSettingsAndViewPairsWhichAreValid(allMetadata)... | @Test
public void shouldNotStoreMetadataIfViewTemplateIsMissing() {
GoPluginDescriptor pluginDescriptor = GoPluginDescriptor.builder().id("plugin-id").isBundledPlugin(true).build();
setupSettingsResponses(packageRepositoryExtension, pluginDescriptor.id(), null, null);
metadataLoader.fetchPl... |
public static String getDatabaseName(final SQLStatement sqlStatement, final String currentDatabaseName) {
Optional<DatabaseSegment> databaseSegment = sqlStatement instanceof FromDatabaseAvailable ? ((FromDatabaseAvailable) sqlStatement).getDatabase() : Optional.empty();
return databaseSegment.map(option... | @Test
void assertDatabaseNameWhenNotAvailableInSQLStatement() {
assertThat(DatabaseNameUtils.getDatabaseName(mock(SQLStatement.class), "foo_db"), is("foo_db"));
} |
@Override
public String toString() {
return predicate.toString();
} | @Test
public void testLongPredicate() {
TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();
IMap<Integer, Integer> map = hazelcastInstance.getMap(randomString());
for (int i = 0; i < 8000; ... |
void validateLogLevelConfigs(Collection<AlterableConfig> ops) {
ops.forEach(op -> {
String loggerName = op.name();
switch (OpType.forId(op.configOperation())) {
case SET:
validateLoggerNameExists(loggerName);
String logLevel = op.va... | @Test
public void testValidateRemoveRootLogLevelConfigNotAllowed() {
assertEquals("Removing the log level of the " + Log4jController.ROOT_LOGGER() +
" logger is not allowed",
Assertions.assertThrows(InvalidRequestException.class,
() -> MANAGER.validateLogLevelConfigs(... |
private Set<ServiceInstance> servicesDownAndNotInGroup() {
if (servicesDownAndNotInGroup == null) {
servicesDownAndNotInGroup = servicesNotInGroup.stream().filter(this::serviceEffectivelyDown).collect(Collectors.toSet());
}
return servicesDownAndNotInGroup;
} | @Test
public void testServicesDownAndNotInGroup() {
HostName hostName1 = new HostName("host1");
HostName hostName2 = new HostName("host2");
HostName hostName3 = new HostName("host3");
HostName hostName4 = new HostName("host4");
HostName hostName5 = new HostName("host5");
... |
static Serde<List<?>> createSerde(final PersistenceSchema schema) {
final List<SimpleColumn> columns = schema.columns();
if (columns.isEmpty()) {
// No columns:
return new KsqlVoidSerde<>();
}
if (columns.size() != 1) {
throw new KsqlException("The '" + FormatFactory.KAFKA.name()
... | @Test
public void shouldThroIfBoolean() {
// Given:
final PersistenceSchema schema = schemaWithFieldOfType(SqlTypes.BOOLEAN);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> KafkaSerdeFactory.createSerde(schema)
);
// Then:
assertThat(e.getMessage(),... |
@Override
void put(String name, Mapping mapping) {
storage().put(name, mapping);
} | @Test
public void when_put_then_overridesPrevious() {
String name = randomName();
Mapping originalMapping = mapping(name, "type1");
Mapping updatedMapping = mapping(name, "type2");
storage.put(name, originalMapping);
storage.put(name, updatedMapping);
assertTrue(sto... |
public void addPattern(String pattern) {
final List<String> tokens = splitByCharacter(pattern);
PatternToken current = null;
for (final PatternToken patternToken : roots) {
if (patternToken.isMatch(tokens.get(0))) {
current = patternToken;
break;
... | @Test
public void testTreeBuild() throws NoSuchFieldException, IllegalAccessException {
PatternTree tree = new PatternTree();
tree.addPattern("/products/{var}");
tree.addPattern("/products/{var}/detail");
tree.addPattern("/products/{var}/refund");
tree.addPattern("/products/{... |
@Override
public Map<String, Object> load(String configKey) {
if (targetUri == null) {
return null;
}
// Check for new file every so often
int currentTimeSecs = Time.currentTimeSecs();
if (lastReturnedValue != null && ((currentTimeSecs - lastReturnedTime) < artif... | @Test
public void testMalformedYaml() {
// This is a test where we are configured to point right at a single artifact
Config conf = new Config();
conf.put(DaemonConfig.SCHEDULER_CONFIG_LOADER_URI,
ARTIFACTORY_HTTP_SCHEME_PREFIX + "bogushost.yahoo.com:9999/location/of/this/ar... |
@Override
public boolean enableSendingOldValues(final boolean forceMaterialization) {
if (queryableName != null) {
sendOldValues = true;
return true;
}
if (parent.enableSendingOldValues(forceMaterialization)) {
sendOldValues = true;
}
retu... | @Test
public void shouldEnableSendOldValuesWhenMaterializedAlreadyAndForcedToMaterialize() {
final StreamsBuilder builder = new StreamsBuilder();
final String topic1 = "topic1";
final KTableImpl<String, Integer, Integer> table1 =
(KTableImpl<String, Integer, Integer>) builder.ta... |
public void setDrainEventsOnStop() {
drainEventsOnStop = true;
} | @Test
@Timeout(10000)
void testDispatchStopOnTimeout() throws Exception {
BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>();
eventQueue = spy(eventQueue);
// simulate dispatcher is not drained.
when(eventQueue.isEmpty()).thenReturn(false);
YarnConfiguration conf = new YarnConfi... |
@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 containsExactlyVarargFailureBoth() {
ImmutableMultimap<Integer, String> expected =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ListMultimap<Integer, String> actual = LinkedListMultimap.create(expected);
actual.remove(3, "six");
actual.remove(4, "... |
static Optional<SearchPath> fromString(String path) {
if (path == null || path.isEmpty()) {
return Optional.empty();
}
if (path.indexOf(';') >= 0) {
return Optional.empty(); // multi-level not supported at this time
}
try {
SearchPath sp = pars... | @Test
void invalidRowMustThrowException() {
try {
SearchPath.fromString("1,2,3/r");
fail("Expected exception");
}
catch (InvalidSearchPathException e) {
// success
}
} |
public void retrieveDocuments() throws DocumentRetrieverException {
boolean first = true;
String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster);
MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route);
doc... | @Test
void testPrintIdOnly() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPrintIdsOnly(true)
.build();
when(mockedSession.syncSend(any())).thenReturn(createDocumentReply(DOC... |
static Map<String, String> decodeOpaqueSecrets(Secret secret) {
if (secret == null) {
return Collections.emptyMap();
}
String opaqueIdentities = secret.getData().get("identities.yaml");
String yaml = new String(Base64.getDecoder().decode(opaqueIdentities));
YamlConfigurationReader... | @Test
public void testKubeSecrets() {
Secret secret = new Secret();
secret.setData(Collections.singletonMap("identities.yaml", "Y3JlZGVudGlhbHM6Ci0gdXNlcm5hbWU6IGFkbWluCiAgcGFzc3dvcmQ6IHBhc3N3b3JkCgo="));
Map<String, String> map = Kube.decodeOpaqueSecrets(secret);
assertEquals(1, map.size());... |
public ProjectCleaner purge(DbSession session, String rootUuid, String projectUuid, Configuration projectConfig, Set<String> disabledComponentUuids) {
long start = System.currentTimeMillis();
profiler.reset();
periodCleaner.clean(session, rootUuid, projectConfig);
PurgeConfiguration configuration = ne... | @Test
public void no_profiling_when_property_is_false() {
settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, false);
underTest.purge(mock(DbSession.class), "root", "project", settings.asConfig(), emptySet());
verify(profiler, never()).getProfilingResult(anyLong());
assertThat(logTester.getL... |
protected TransMeta processLinkedTrans( TransMeta transMeta ) {
for ( StepMeta stepMeta : transMeta.getSteps() ) {
if ( stepMeta.getStepID().equalsIgnoreCase( "TransExecutor" ) ) {
TransExecutorMeta tem = (TransExecutorMeta) stepMeta.getStepMetaInterface();
ObjectLocationSpecificationMethod sp... | @Test
public void testProcessLinkedTransWithFilename() {
TransExecutorMeta transExecutorMeta = spy( new TransExecutorMeta() );
transExecutorMeta.setFileName( "/path/to/Transformation2.ktr" );
transExecutorMeta.setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME );
StepMeta transExecutor... |
@Override
public Collection<String> searchServiceName(String namespaceId, String expr) throws NacosException {
String regex = Constants.ANY_PATTERN + expr + Constants.ANY_PATTERN;
Collection<String> result = new HashSet<>();
for (Service each : ServiceManager.getInstance().getSingletons(name... | @Test
void testSearchServiceName() throws NacosException {
Collection<String> res = serviceOperatorV2.searchServiceName("A", "");
assertEquals(1, res.size());
} |
public TargetAssignmentResult build() throws PartitionAssignorException {
Map<String, MemberSubscriptionAndAssignmentImpl> memberSpecs = new HashMap<>();
// Prepare the member spec for all members.
members.forEach((memberId, member) ->
memberSpecs.put(memberId, createMemberSubscript... | @Test
public void testNewMember() {
TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
"my-group",
20
);
Uuid fooTopicId = context.addTopicMetadata("foo", 6, Collections.emptyMap());
Uuid barTopicId = context.addTopicMetadata... |
@Override
public void loadConfiguration(NacosLoggingProperties loggingProperties) {
String location = loggingProperties.getLocation();
configurator.setLoggingProperties(loggingProperties);
LoggerContext loggerContext = loadConfigurationOnStart(location);
if (hasNoListener(loggerConte... | @Test
void testLoadConfigurationFailure() {
assertThrows(IllegalStateException.class, () -> {
System.setProperty("nacos.logging.config", "http://localhost");
loggingProperties = new NacosLoggingProperties("classpath:nacos-logback12.xml", System.getProperties());
logbackNa... |
@Override
public JobState getJobStatus(String project, String region, String jobId) throws IOException {
return handleJobState(getJob(project, region, jobId));
} | @Test
public void testGetJobStatus() throws IOException {
Get get = mock(Get.class);
Job job = new Job().setCurrentState(JobState.RUNNING.toString());
when(getLocationJobs(client).get(any(), any(), any()).setView(any()))
.thenThrow(new RuntimeException("Server is not responding"))
.thenRet... |
private void fail(final ChannelHandlerContext ctx, int length) {
fail(ctx, String.valueOf(length));
} | @Test
public void testTooLongLineWithFailFast() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new LineBasedFrameDecoder(16, false, true));
try {
ch.writeInbound(copiedBuffer("12345678901234567", CharsetUtil.US_ASCII));
fail();
} catch (Exception e) {
... |
@Override public V get(Object o) {
if (o == null) return null; // null keys are not allowed
int i = arrayIndexOfKey(o);
return i != -1 ? value(i + 1) : null;
} | @Test void equalValues() {
array[0] = "1";
array[1] = "1";
array[2] = "2";
array[3] = "2";
array[4] = "3";
array[5] = "3";
Map<String, String> map = builder.build(array);
assertSize(map, 3);
assertBaseCase(map);
assertThat(map).containsOnly(
entry("1", "1"),
ent... |
@Override
public void push(String queueName, String id, long offsetTimeInSecond) {
push(queueName, id, 0, offsetTimeInSecond);
} | @Test
public void testPush() {
String queueName = "test-queue";
String id = "abcd-1234-defg-5678";
queueDao.push(queueName, id, 123);
assertEquals(1, internalQueue.size());
assertTrue(internalQueue.containsKey(queueName));
assertEquals(1, internalQueue.get(queueName).size());
assertEquals(... |
public List<R> scanForClasspathResource(String resourceName, Predicate<String> packageFilter) {
requireNonNull(resourceName, "resourceName must not be null");
requireNonNull(packageFilter, "packageFilter must not be null");
List<URI> urisForResource = getUrisForResource(getClassLoader(), resourc... | @Test
void scanForClasspathPackageResource() {
String resourceName = "io/cucumber/core/resource";
List<URI> resources = resourceScanner.scanForClasspathResource(resourceName, aPackage -> true);
assertThat(resources, containsInAnyOrder(
URI.create("classpath:io/cucumber/core/resou... |
@Override
public int read() throws IOException {
byte[] b = new byte[1];
if (read(b, 0, 1) != 1) {
return -1;
} else {
return b[0];
}
} | @Test
public void testReadEos() throws Exception {
DistributedLogManager dlm = mock(DistributedLogManager.class);
LogReader reader = mock(LogReader.class);
when(dlm.getInputStream(any(DLSN.class))).thenReturn(reader);
when(reader.readNext(anyBoolean())).thenThrow(new EndOfStreamExcep... |
@Override
public void write(int b) throws IOException {
if (buffer.length <= bufferIdx) {
flushInternalBuffer();
}
buffer[bufferIdx] = (byte) b;
++bufferIdx;
} | @Test
void testFailingPrimaryWriteArrayOffsFail() throws Exception {
DuplicatingCheckpointOutputStream duplicatingStream =
createDuplicatingStreamWithFailingPrimary();
testFailingPrimaryStream(
duplicatingStream, () -> duplicatingStream.write(new byte[512], 20, 130));... |
public static Configuration windows() {
return WindowsHolder.WINDOWS;
} | @Test
public void testDefaultWindowsConfiguration() {
Configuration config = Configuration.windows();
assertThat(config.pathType).isEqualTo(PathType.windows());
assertThat(config.roots).containsExactly("C:\\");
assertThat(config.workingDirectory).isEqualTo("C:\\work");
assertThat(config.nameCanon... |
@Override
public CompletableFuture<MetricsResponse> fetchMetrics(ApplicationId application) {
NodeList applicationNodes = nodeRepository.nodes().list().owner(application).state(Node.State.active);
Optional<Node> metricsV2Container = applicationNodes.container()
.matching(this::expec... | @Test
public void testMetricsFetch() throws Exception {
NodeResources resources = new NodeResources(1, 10, 100, 1);
ProvisioningTester tester = new ProvisioningTester.Builder().build();
OrchestratorMock orchestrator = new OrchestratorMock();
MockHttpClient httpClient = new MockHttpCl... |
public List<Release> findByReleaseIds(Set<Long> releaseIds) {
Iterable<Release> releases = releaseRepository.findAllById(releaseIds);
if (releases == null) {
return Collections.emptyList();
}
return Lists.newArrayList(releases);
} | @Test
public void testFindByReleaseIds() throws Exception {
Release someRelease = mock(Release.class);
Release anotherRelease = mock(Release.class);
long someReleaseId = 1;
long anotherReleaseId = 2;
List<Release> someReleases = Lists.newArrayList(someRelease, anotherRelease);
Set<Long> someRe... |
public Encoding getEncoding() {
return encoding;
} | @Test
public void testAsciiEncoding() {
MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
String testString = "asciiOnly";
MetaString encodedMetaString = encoder.encode(testString);
assertNotSame(encodedMetaString.getEncoding(), MetaString.Encoding.UTF_8);
assertEquals(encodedMetaString... |
public static ClusterOperatorConfig buildFromMap(Map<String, String> map) {
warningsForRemovedEndVars(map);
KafkaVersion.Lookup lookup = parseKafkaVersions(map.get(STRIMZI_KAFKA_IMAGES), map.get(STRIMZI_KAFKA_CONNECT_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER... | @Test
public void testImagePullSecretsThrowsWithInvalidCharacter() {
Map<String, String> envVars = new HashMap<>(ClusterOperatorConfigTest.ENV_VARS);
envVars.put(ClusterOperatorConfig.IMAGE_PULL_SECRETS.key(), "secret1, secret2 , secret_3 ");
assertThrows(InvalidConfigurationException.class... |
public Map<String, Parameter> generateMergedWorkflowParams(
WorkflowInstance instance, RunRequest request) {
Workflow workflow = instance.getRuntimeWorkflow();
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
Map<String, ParamDefinition> defaultWorkflowParams =
defaultParamMa... | @Test
public void testWorkflowParamRunParamsUpstreamInitiator() {
Map<String, ParamDefinition> runParams =
singletonMap("p1", ParamDefinition.buildParamDefinition("p1", "d1"));
ParamSource[] expectedSources =
new ParamSource[] {ParamSource.FOREACH, ParamSource.SUBWORKFLOW, ParamSource.TEMPLAT... |
public static BytesInput from(InputStream in, int bytes) {
return new StreamBytesInput(in, bytes);
} | @Test
public void testFromCapacityByteArrayOutputStreamOneSlab() throws IOException {
byte[] data = new byte[1000];
RANDOM.nextBytes(data);
List<CapacityByteArrayOutputStream> toClose = new ArrayList<>();
Supplier<BytesInput> factory = () -> {
CapacityByteArrayOutputStream cbaos = new CapacityBy... |
@VisibleForTesting
ZonedDateTime parseZoned(final String text, final ZoneId zoneId) {
final TemporalAccessor parsed = formatter.parse(text);
final ZoneId parsedZone = parsed.query(TemporalQueries.zone());
ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply(
ObjectUtils.defaultIfNull(parsedZone... | @Test
public void shouldParseFullLocalDateWithTimeZone() {
// Given
// NOTE: a trailing space is required due to JDK bug, fixed in JDK 9b116
// https://bugs.openjdk.java.net/browse/JDK-8154050
final String format = "yyyy-MM-dd HH O ";
final String timestamp = "1605-11-05 10 GMT+3 ";
// When
... |
public void cloneGroupOffset(final String addr, final String srcGroup, final String destGroup, final String topic,
final boolean isOffline,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
CloneGroupOffsetRequestHeader requestHeader = new CloneGroupOf... | @Test
public void testCloneGroupOffset() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
mqClientAPI.cloneGroupOffset(defaultBrokerAddr, "", "", defaultTopic, false, defaultTimeout);
} |
public static Version of(int major, int minor) {
if (major == UNKNOWN_VERSION && minor == UNKNOWN_VERSION) {
return UNKNOWN;
} else {
return new Version(major, minor);
}
} | @Test(expected = IllegalArgumentException.class)
public void ofMalformed() {
Version.of("3,9");
} |
@Override
public Map<String, Integer> getCounts(UUID jobId) {
return counts.computeIfAbsent(jobId, k -> new ConcurrentHashMap<>());
} | @Test
public void canAddExistingKeysToCurrentCountsTest() {
addItemToJobStoreCounts(ITEM_NAME);
addItemToJobStoreCounts(ITEM_NAME);
final Map<String, Integer> counts = localJobStore.getCounts(jobId);
Truth.assertThat(counts.size()).isEqualTo(1);
Truth.assertThat(counts.get(ITEM_NAME)).isEqualTo(2... |
public boolean insertOrReplace(E entry, Predicate<E> entryTest) {
AtomicBoolean updated = new AtomicBoolean(false);
map.compute(checkNotNull(entry), (k, v) -> {
if (v == null || entryTest.test(v)) {
updated.set(true);
return entry;
}
re... | @Test
public void testInsertOrReplace() {
ExtendedSet<TestValue> set = new ExtendedSet<>(Maps.newConcurrentMap());
TestValue small = new TestValue("foo", 1);
TestValue medium = new TestValue("foo", 2);
TestValue large = new TestValue("foo", 3);
// input TestValue will replace... |
@Udf
public String concat(@UdfParameter final String... jsonStrings) {
if (jsonStrings == null) {
return null;
}
final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length);
boolean allObjects = true;
for (final String jsonString : jsonStrings) {
if (jsonString == null) {
... | @Test
public void shouldMergeEmptyArrays() {
// When:
final String result = udf.concat("[]", "[]");
// Then:
assertEquals("[]", result);
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final JsonNode event;
try {
event = objectMapper.readTree(payload);
if (event == null || event.isMissingNode()) {
throw new ... | @Test
public void decodeMessagesHandlesTopbeatMessages() throws Exception {
final Message message = codec.decode(messageFromJson("topbeat-system.json"));
assertThat(message).isNotNull();
assertThat(message.getSource()).isEqualTo("example.local");
assertThat(message.getTimestamp()).is... |
@Override
public int getJDBCMinorVersion() {
return 0;
} | @Test
void assertGetJDBCMinorVersion() {
assertThat(metaData.getJDBCMinorVersion(), is(0));
} |
ImmutableList<PayloadDefinition> validatePayloads(List<PayloadDefinition> payloads) {
for (PayloadDefinition p : payloads) {
checkArgument(p.hasName(), "Parsed payload does not have a name.");
checkArgument(
p.getInterpretationEnvironment()
!= PayloadGeneratorConfig.Interpretatio... | @Test
public void validatePayloads_withoutPayloadString_throwsException() throws IOException {
PayloadDefinition p = goodCallbackDefinition.clearPayloadString().build();
Throwable thrown =
assertThrows(
IllegalArgumentException.class, () -> module.validatePayloads(ImmutableList.of(p)));
... |
@Override
public SchemaResult getValueSchema(
final Optional<String> topicName,
final Optional<Integer> schemaId,
final FormatInfo expectedFormat,
final SerdeFeatures serdeFeatures
) {
return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, false);
} | @Test
public void shouldReturnErrorFromGetValueSchemaIfCanNotConvertToConnectSchema() {
// Given:
when(schemaTranslator.toColumns(any(), any(), anyBoolean()))
.thenThrow(new RuntimeException("it went boom"));
// When:
final SchemaResult result = supplier
.getValueSchema(Optional.of(TO... |
@ExceptionHandler(SoapValidationException.class)
@ResponseBody
public Map<String, String> handleSoapValidationException(SoapValidationException exception) {
Map<String,String> errorResponse = new HashMap<>();
errorResponse.put("status", "NOK");
return errorResponse;
} | @Test
public void handleSoapValidationExceptionShouldReturnStatusNok() {
Map<String, String> controllerResponse = controller.handleSoapValidationException(new SoapValidationException("Soap Validation error"));
assertEquals("NOK", controllerResponse.get("status"));
} |
@Override
public GoPluginApiResponse submitTo(final String pluginId, String extensionType, final GoPluginApiRequest apiRequest) {
return goPluginOSGiFramework.doOn(GoPlugin.class, pluginId, extensionType, (plugin, pluginDescriptor) -> {
ensureInitializerInvoked(pluginDescriptor, plugin, extensio... | @Test
void shouldSubmitPluginApiRequestToGivenPlugin() throws Exception {
String extensionType = "sample-extension";
GoPluginApiRequest request = mock(GoPluginApiRequest.class);
GoPluginApiResponse expectedResponse = mock(GoPluginApiResponse.class);
final GoPlugin goPlugin = mock(GoP... |
@Override
public void prepare() {
boolean isCollectorSealed = collectorSealed.compareAndSet(true, false);
checkState(
isCollectorSealed,
"Failed to prepare the collector. Collector needs to be sealed before prepare() is invoked.");
} | @Test
public void testMultiplePrepareCallsWithoutFinishThrowsException() {
futureCollector.prepare();
try {
futureCollector.prepare();
Assert.fail("Second invocation of prepare should throw IllegalStateException");
} catch (IllegalStateException ex) {
}
} |
public static String schemaToPdl(DataSchema schema, EncodingStyle encodingStyle)
{
StringWriter writer = new StringWriter();
SchemaToPdlEncoder encoder = new SchemaToPdlEncoder(writer);
encoder.setEncodingStyle(encodingStyle);
try
{
encoder.encode(schema);
}
catch (IOException e)
... | @Test
public void testEncodeDefaultValueFieldsInSchemaOrder() throws IOException
{
String inputSchema = String.join("\n",
"record A {",
"",
" b: record B {",
" b1: string",
"",
" c: record C {",
" c2: int",
" c1: boolean",
... |
@Override
public List<String> getKeys() throws IOException {
return doOp(new ProviderCallable<List<String>>() {
@Override
public List<String> call(KMSClientProvider provider) throws IOException {
return provider.getKeys();
}
}, nextIdx(), true);
} | @Test
public void testClientRetriesIdempotentOpWithSocketTimeoutExceptionSucceeds()
throws Exception {
Configuration conf = new Configuration();
conf.setInt(
CommonConfigurationKeysPublic.KMS_CLIENT_FAILOVER_MAX_RETRIES_KEY, 3);
final List<String> keys = Arrays.asList("testKey");
KMSClie... |
public void remove(ConnectorTaskId id) {
final ScheduledFuture<?> task = committers.remove(id);
if (task == null)
return;
try (LoggingContext loggingContext = LoggingContext.forTask(id)) {
task.cancel(false);
if (!task.isDone())
task.get();
... | @Test
public void testRemoveNonExistentTask() {
assertTrue(committers.isEmpty());
committer.remove(taskId);
assertTrue(committers.isEmpty());
} |
@Override
public String named() {
return PluginEnum.SOFA.getName();
} | @Test
public void testNamed() {
final String result = sofaPlugin.named();
assertEquals(PluginEnum.SOFA.getName(), result);
} |
@EventListener
void startup(StartupEvent event) {
if (configuration.getBackgroundJobServer().isEnabled()) {
backgroundJobServer.get().start();
}
if (configuration.getDashboard().isEnabled()) {
dashboardWebServer.get().start();
}
} | @Test
void onStartOptionalsAreNotToBootstrapIfConfigured() {
when(backgroundJobServerConfiguration.isEnabled()).thenReturn(true);
when(dashboardConfiguration.isEnabled()).thenReturn(true);
jobRunrStarter.startup(null);
verify(backgroundJobServer).start();
verify(dashboardWe... |
@Override
public void verify(byte[] data, byte[] signature, MessageDigest digest) {
verify(data, new EcSignature(signature), digest);
} | @Test
public void shouldValidateSignature() {
verify(D, Q, "SHA-256");
} |
public static void reloadFailureRecovery(File indexDir)
throws IOException {
File parentDir = indexDir.getParentFile();
// Recover index directory from segment backup directory if the segment backup directory exists
File segmentBackupDir = new File(parentDir, indexDir.getName() + CommonConstants.Segm... | @Test
public void testReloadFailureRecovery()
throws IOException {
String segmentName = "dummySegment";
String indexFileName = "dummyIndex";
File indexDir = new File(TEST_DIR, segmentName);
File segmentBackupDir = new File(TEST_DIR, segmentName + CommonConstants.Segment.SEGMENT_BACKUP_DIR_SUFFIX... |
private void setConsumeEndTime(SegmentZKMetadata segmentZKMetadata, long now) {
long maxConsumeTimeMillis = _streamConfig.getFlushThresholdTimeMillis();
_consumeEndTime = segmentZKMetadata.getCreationTime() + maxConsumeTimeMillis;
// When we restart a server, the consuming segments retain their creationTim... | @Test
public void testEndCriteriaChecking()
throws Exception {
// test reaching max row limit
try (FakeRealtimeSegmentDataManager segmentDataManager = createFakeSegmentManager()) {
segmentDataManager._state.set(segmentDataManager, RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
Assert.a... |
public EndpointResponse streamQuery(
final KsqlSecurityContext securityContext,
final KsqlRequest request,
final CompletableFuture<Void> connectionClosedFuture,
final Optional<Boolean> isInternalRequest,
final MetricsCallbackHolder metricsCallbackHolder,
final Context context
) {
... | @Test
public void shouldUpdateTheLastRequestTime() {
/// When:
testResource.streamQuery(
securityContext,
new KsqlRequest(PUSH_QUERY_STRING, Collections.emptyMap(), Collections.emptyMap(), null),
new CompletableFuture<>(),
Optional.empty(),
new MetricsCallbackHolder(),
... |
public static List<ColumnType> columnTypesFromStrings(final List<String> columnTypes) {
return columnTypes.stream().map(RowUtil::columnTypeFromString).collect(Collectors.toList());
} | @Test
public void shouldGetColumnTypesFromStrings() {
// Given
final List<String> stringTypes = ImmutableList.of(
"STRING",
"INTEGER",
"BIGINT",
"BOOLEAN",
"DOUBLE",
"ARRAY<STRING>",
"MAP<STRING, STRING>",
"DECIMAL(4, 2)",
"STRUCT<`F1` ST... |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
public void testOrderedListIsEmptyTrue() throws Exception {
StateTag<OrderedListState<String>> addr =
StateTags.orderedList("orderedList", StringUtf8Coder.of());
OrderedListState<String> orderedList = underTest.state(NAMESPACE, addr);
SettableFuture<Iterable<TimestampedValue<String>>> futur... |
static <U, V> ImmutableBiMap<U, V> maximumCardinalityBipartiteMatching(Multimap<U, V> graph) {
return HopcroftKarp.overBipartiteGraph(graph).perform();
} | @Test
public void maximumCardinalityBipartiteMatching_failsWithNullLhs() {
ListMultimap<String, String> edges = LinkedListMultimap.create();
edges.put(null, "R1");
try {
BiMap<String, String> unused = maximumCardinalityBipartiteMatching(edges);
fail("Should have thrown.");
} catch (NullPoi... |
public COSArray toCOSArray()
{
COSArray array = new COSArray();
array.add(new COSFloat(single[0]));
array.add(new COSFloat(single[1]));
array.add(new COSFloat(single[3]));
array.add(new COSFloat(single[4]));
array.add(new COSFloat(single[6]));
array.add(new CO... | @Test
void testPdfbox2872()
{
Matrix m = new Matrix(2, 4, 5, 8, 2, 0);
COSArray toCOSArray = m.toCOSArray();
assertEquals(new COSFloat(2), toCOSArray.get(0));
assertEquals(new COSFloat(4), toCOSArray.get(1));
assertEquals(new COSFloat(5), toCOSArray.get(2));
asser... |
public static List<ExportPackages.Export> parseExports(String exportAttribute) {
ParsingContext p = new ParsingContext(exportAttribute.trim());
List<ExportPackages.Export> exports = parseExportPackage(p);
if (exports.isEmpty()) {
p.fail("Expected a list of exports");
} else ... | @Test
void require_that_spaces_between_separators_are_allowed() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1 , exported.package2 ; version = \"1.2.3.sample\" ");
assertEquals(2, exports.size());
Export export = exports.get(0);
assertTrue(export.g... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateJobStatus(Long id, Integer status) throws SchedulerException {
// 校验 status
if (!containsAny(status, JobStatusEnum.NORMAL.getStatus(), JobStatusEnum.STOP.getStatus())) {
throw exception(JOB_CHANGE_STATUS_INVALI... | @Test
public void testUpdateJobStatus_normalSuccess() throws SchedulerException {
// mock 数据
JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.STOP.getStatus()));
jobMapper.insert(job);
// 调用
jobService.updateJobStatus(job.getId(), JobStatusEnum.NORMAL.getSt... |
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
protected ShenyuAdminResult handleHttpRequestMethodNotSupportedException(final HttpRequestMethodNotSupportedException e) {
LOG.warn("http request method not supported", e);
StringBuilder sb = new StringBuilder();
sb.append(e.get... | @Test
public void testHandleHttpRequestMethodNotSupportedException() {
String[] supportedMethod = new String[]{"POST", "GET"};
HttpRequestMethodNotSupportedException exception = new HttpRequestMethodNotSupportedException("POST" + supportedMethod + "request method", Arrays.asList(supportedMethod));
... |
public static int readVInt(ByteData arr, long position) {
byte b = arr.get(position++);
if(b == (byte) 0x80)
throw new RuntimeException("Attempting to read null value as int");
int value = b & 0x7F;
while ((b & 0x80) != 0) {
b = arr.get(position++);
valu... | @Test(expected = EOFException.class)
public void testReadVIntEmptyHollowBlobInput() throws IOException {
HollowBlobInput hbi = HollowBlobInput.serial(BYTES_EMPTY);
VarInt.readVInt(hbi);
} |
public static boolean isValidRule(ParamFlowRule rule) {
return rule != null && !StringUtil.isBlank(rule.getResource()) && rule.getCount() >= 0
&& rule.getGrade() >= 0 && rule.getParamIdx() != null
&& rule.getBurstCount() >= 0 && rule.getControlBehavior() >= 0
&& rule.getDurat... | @Test
public void testCheckValidHotParamRule() {
// Null or empty resource;
ParamFlowRule rule1 = new ParamFlowRule();
ParamFlowRule rule2 = new ParamFlowRule("");
assertFalse(ParamFlowRuleUtil.isValidRule(null));
assertFalse(ParamFlowRuleUtil.isValidRule(rule1));
ass... |
public static DescriptorDigest fromHash(String hash) throws DigestException {
if (!hash.matches(HASH_REGEX)) {
throw new DigestException("Invalid hash: " + hash);
}
return new DescriptorDigest(hash);
} | @Test
public void testCreateFromHash_fail() {
String badHash = "not a valid hash";
try {
DescriptorDigest.fromHash(badHash);
Assert.fail("Invalid hash should have caused digest creation failure.");
} catch (DigestException ex) {
Assert.assertEquals("Invalid hash: " + badHash, ex.getMess... |
@Override
protected Result[] run(String value) {
final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly);
// the extractor instance is rebuilt every second anyway
final Match match = grok.match(value);
final Map<String, Object> matches = matc... | @Test
public void testDateExtraction() {
final GrokExtractor extractor = makeExtractor("%{GREEDY:timestamp;date;yyyy-MM-dd'T'HH:mm:ss.SSSX}");
final Extractor.Result[] results = extractor.run("2015-07-31T10:05:36.773Z");
assertEquals("ISO date is parsed", 1, results.length);
Object v... |
public void start() {
Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");
Preconditions.checkState(!executorService.isShutdown(), "Already started");
Preconditions.checkState(!hasLeadership, "Already has leadership");
client.g... | @Test
public void testInterruption() throws Exception {
Timing2 timing = new Timing2();
LeaderSelector selector = null;
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
try {
client.start();
CountDow... |
@Override
public int compareTo(Resource other) {
checkArgument(other != null && getClass() == other.getClass() && name.equals(other.name));
return value.compareTo(other.value);
} | @Test
void testCompareToFailNull() {
// new TestResource(0.0).compareTo(null);
assertThatThrownBy(() -> new TestResource(0.0).compareTo(null))
.isInstanceOf(IllegalArgumentException.class);
} |
@Override
public boolean find(Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
try {
final boolean found;
if(containerService.isContainer(file)) {
... | @Test
public void testFindCommonPrefix() throws Exception {
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
assertTrue(new AzureFindFeature(session, null).find(container));
final String prefix = new AlphanumericRandomStringService().random();
... |
public Object get(final Object bean) {
return get(this.patternParts, bean, false);
} | @Test
public void beanPathTest1() {
final BeanPath pattern = new BeanPath("userInfo.examInfoDict[0].id");
assertEquals("userInfo", pattern.patternParts.get(0));
assertEquals("examInfoDict", pattern.patternParts.get(1));
assertEquals("0", pattern.patternParts.get(2));
assertEquals("id", pattern.patternParts.g... |
public static <K, E> Collector<E, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) {
return unorderedIndex(keyFunction, Function.identity());
} | @Test
public void unorderedIndex_parallel_stream() {
SetMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(unorderedIndex(identity()));
assertThat(multimap.keySet()).isEqualTo(HUGE_SET);
} |
@Override
protected DAVClient connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
final HttpClientBuilder configuration = this.getConfiguration(proxy, prompt);
return new DAVClient(new HostUrlProvider().wit... | @Test(expected = ConnectionRefusedException.class)
public void testProxyNoConnect() throws Exception {
final Host host = new Host(new DAVSSLProtocol(), "svn.cyberduck.io");
final DAVSession session = new DAVSession(host, new DefaultX509TrustManager(),
new KeychainX509KeyManager(new D... |
public static byte[] parseMAC(String value) {
final byte[] machineId;
final char separator;
switch (value.length()) {
case 17:
separator = value.charAt(2);
validateMacSeparator(separator);
machineId = new byte[EUI48_MAC_ADDRESS_LENGTH];... | @Test
public void testParseMacEUI48ToEUI64() {
// EUI-48 into an EUI-64
assertArrayEquals(new byte[]{0, (byte) 0xaa, 0x11, (byte) 0xff, (byte) 0xfe, (byte) 0xbb, 0x22, (byte) 0xcc},
parseMAC("00-AA-11-FF-FE-BB-22-CC"));
assertArrayEquals(new byte[]{0, (byte) 0xaa, 0x11, (byte... |
@VisibleForTesting
CompletableFuture<Void> checkPersistencePolicies() {
TopicName topicName = TopicName.get(topic);
CompletableFuture<Void> future = new CompletableFuture<>();
brokerService.getManagedLedgerConfig(topicName).thenAccept(config -> {
// update managed-ledger config a... | @Test
public void testCheckPersistencePolicies() throws Exception {
final String myNamespace = "prop/ns";
admin.namespaces().createNamespace(myNamespace, Sets.newHashSet("test"));
final String topic = "persistent://" + myNamespace + "/testConfig" + UUID.randomUUID();
conf.setForceDel... |
@Override
public void publish(ScannerReportWriter writer) {
Optional<String> targetBranch = getTargetBranch();
if (targetBranch.isPresent()) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
int count = writeChangedLines(scmConfiguration.provider(), writer, targetBranch.get());
... | @Test
public void skip_if_target_branch_is_null() {
when(branchConfiguration.targetBranchName()).thenReturn(null);
publisher.publish(writer);
verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider);
assertNotPublished();
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(!session.getClient().setFileType(FTP.BINARY_FILE_TYPE)) {
throw new FTPException(session.getClient().getReplyCode(), session.ge... | @Test
public void testRead() throws Exception {
final Path home = new FTPWorkdirService(session).find();
final Path test = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
new FTPTouchFeature(session).touch(test, new TransferStatus());
final int length = 3986... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.