focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchOffsetOutOfRangeException() {
buildFetcher(OffsetResetStrategy.NONE, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), 2, IsolationLevel.READ_UNCOMMITTED);
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
sendFetches();
... |
@Override
public <VR> KStream<K, VR> flatMapValues(final ValueMapper<? super V, ? extends Iterable<? extends VR>> mapper) {
return flatMapValues(withKey(mapper));
} | @Test
public void shouldNotAllowNullNameOnFlatMapValuesWithKey() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatMapValues((k, v) -> Collections.emptyList(), null));
assertThat(exception.getMessage(), equalTo("named can'... |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testParseSimpleDateRangeWithoutYear() throws ParseException {
DateRange dateRange = dateRangeParser.getRange("Aug 10-Aug 14");
assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 9)));
assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 10)));
... |
@Override
public void run(Job job) throws Exception {
getBackgroundJobWorker(job).run();
if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
} | @Test
void invokeJobMethodAlwaysResetsJobContextThreadLocal() {
final Job job = aJobInProgress().withJobDetails(this::throwingJobContext).build();
final AbstractBackgroundJobRunner backgroundJobRunner = getJobRunner(BackgroundJobWorker::new);
assertThatCode(() -> backgroundJobRunner.run(jo... |
public static <T> ArrayList<T> distinct(Collection<T> collection) {
if (isEmpty(collection)) {
return new ArrayList<>();
} else if (collection instanceof Set) {
return new ArrayList<>(collection);
} else {
return new ArrayList<>(new LinkedHashSet<>(collection));
}
} | @Test
public void distinctTest() {
final ArrayList<Integer> distinct = CollUtil.distinct(ListUtil.of(5, 3, 10, 9, 0, 5, 10, 9));
assertEquals(ListUtil.of(5, 3, 10, 9, 0), distinct);
} |
@Override
public String toString() {
return getClass().getSimpleName() + "[sessionCount=" + getSessionCount() + ']';
} | @Test
public void testToString() {
final String string = sessionListener.toString();
assertNotNull("toString not null", string);
assertFalse("toString not empty", string.isEmpty());
} |
@Override
public Serde<GenericKey> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> schemaRegistryClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
f... | @Test
public void shouldWrapInLoggingSerdeNonWindowed() {
// When:
factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
verify(innerFactory).wrapInLoggingSerde(any(), eq(LOGGER_PREFIX), eq(processingLogCxt), eq(Optional.of(queryI... |
@Override
public boolean test(Pickle pickle) {
if (expressions.isEmpty()) {
return true;
}
List<String> tags = pickle.getTags();
return expressions.stream()
.allMatch(expression -> expression.evaluate(tags));
} | @Test
void single_tag_predicate_matches_pickle_with_more_tags() {
Pickle pickle = createPickleWithTags("@FOO", "@BAR");
TagPredicate predicate = createPredicate("@FOO");
assertTrue(predicate.test(pickle));
} |
@Override
@Transactional(rollbackFor = Exception.class)
public Long createSpu(ProductSpuSaveReqVO createReqVO) {
// 校验分类、品牌
validateCategory(createReqVO.getCategoryId());
brandService.validateProductBrand(createReqVO.getBrandId());
// 校验 SKU
List<ProductSkuSaveReqVO> skuS... | @Test
public void testCreateSpu_success() {
// 准备参数
ProductSkuSaveReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuSaveReqVO.class, o->{
// 限制范围为正整数
o.setCostPrice(generaInt());
o.setPrice(generaInt());
o.setMarketPrice(generaInt());
o.s... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_PlusMinusZero() {
expectFailureWhenTestingThat(array(0.0f)).isEqualTo(array(-0.0f));
assertFailureValue("expected", "[-0.0]");
assertFailureValue("but was", "[0.0]");
} |
public <TResult> Iterable<TResult> distinct(String fieldName, Class<TResult> tResultClass) {
return delegate.distinct(fieldName, tResultClass);
} | @Test
void distinct() {
final var collection = jacksonCollection("simple", Simple.class);
final List<Simple> items = List.of(
new Simple("000000000000000000000001", "foo"),
new Simple("000000000000000000000002", "bar")
);
collection.insert(items);
... |
@Override
public R apply(R record) {
final Matcher matcher = regex.matcher(record.topic());
if (matcher.matches()) {
final String topic = matcher.replaceFirst(replacement);
log.trace("Rerouting from topic '{}' to new topic '{}'", record.topic(), topic);
return rec... | @Test
public void addPrefix() {
assertEquals("prefix-orig", apply("(.*)", "prefix-$1", "orig"));
} |
protected KllHistogramEstimator mergeHistogramEstimator(
String columnName, KllHistogramEstimator oldEst, KllHistogramEstimator newEst) {
if (oldEst != null && newEst != null) {
if (oldEst.canMerge(newEst)) {
LOG.trace("Merging old sketch {} with new sketch {}...", oldEst.getSketch(), newEst.get... | @Test
public void testMergeNullHistogramEstimators() {
assertNull(MERGER.mergeHistogramEstimator("", null, null));
} |
public static InetSocketAddress getInetSocketAddressFromRpcURL(String rpcURL) throws Exception {
// Pekko URLs have the form schema://systemName@host:port/.... if it's a remote Pekko URL
try {
final Address address = getAddressFromRpcURL(rpcURL);
if (address.host().isDefined() &... | @Test
void getHostFromRpcURLHandlesIPv6AddressesSsl() throws Exception {
final String ipv6Address = "2001:db8:10:11:12:ff00:42:8329";
final int port = 1234;
final InetSocketAddress address = new InetSocketAddress(ipv6Address, port);
final String url =
"pekko.ssl.tcp:... |
static QueryId buildId(
final Statement statement,
final EngineContext engineContext,
final QueryIdGenerator idGenerator,
final OutputNode outputNode,
final boolean createOrReplaceEnabled,
final Optional<String> withQueryId) {
if (withQueryId.isPresent()) {
final String que... | @Test
public void shouldThrowIfWithQueryIdIsNotValid() {
// When:
final Exception e = assertThrows(
Exception.class,
() -> QueryIdUtil.buildId(statement, engineContext, idGenerator, plan,
false, Optional.of("with space"))
);
// Then:
assertThat(e.getMessage(), contains... |
@Override
public String getName() {
return name;
} | @Test
public void namePropagation() {
then(timeLimiter.getName()).isEqualTo(NAME);
} |
@Override
public ClusterInfo clusterGetClusterInfo() {
RFuture<Map<String, String>> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO);
Map<String, String> entries = syncFuture(f);
Properties props = new Properties();
for (Entry<String, Str... | @Test
public void testClusterGetClusterInfo() {
testInCluster(connection -> {
ClusterInfo info = connection.clusterGetClusterInfo();
assertThat(info.getSlotsFail()).isEqualTo(0);
assertThat(info.getSlotsOk()).isEqualTo(MasterSlaveConnectionManager.MAX_SLOT);
a... |
public static Object get(final ConvertedMap data, final FieldReference field) {
final Object target = findParent(data, field);
return target == null ? null : fetch(target, field.getKey());
} | @Test
public void testAbsentBareGet() throws Exception {
Map<Serializable, Object> data = new HashMap<>();
data.put("foo", "bar");
String reference = "baz";
assertNull(get(ConvertedMap.newFromMap(data), reference));
} |
public static String normalizeUri(String uri) throws URISyntaxException {
// try to parse using the simpler and faster Camel URI parser
String[] parts = CamelURIParser.fastParseUri(uri);
if (parts != null) {
// we optimized specially if an empty array is returned
if (part... | @Test
public void testNormalizeEndpointWithEqualSignInParameter() throws Exception {
String out = URISupport.normalizeUri("jms:queue:foo?selector=somekey='somevalue'&foo=bar");
assertNotNull(out);
// Camel will safe encode the URI
assertEquals("jms://queue:foo?foo=bar&selector=someke... |
static InitWriterConfig fromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(InitWriterConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return new InitWriterConfig(generatedMap... | @Test
public void testFromMap() {
InitWriterConfig config = InitWriterConfig.fromMap(ENV_VARS);
assertThat(config.getNodeName(), is("localhost"));
assertThat(config.getRackTopologyKey(), is("failure-domain.beta.kubernetes.io/zone"));
assertThat(config.isExternalAddress(), is(true));... |
@Override
public <V1, R> KTable<K, R> outerJoin(final KTable<K, V1> other,
final ValueJoiner<? super V, ? super V1, ? extends R> joiner) {
return outerJoin(other, joiner, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullJoinerOnOuterJoin() {
assertThrows(NullPointerException.class, () -> table.outerJoin(table, null));
} |
@Override
public long computeLocalQuota(long confUsage, long myUsage, long[] allUsages) throws PulsarAdminException {
// ToDo: work out the initial conditions: we may allow a small number of "first few iterations" to go
// unchecked as we get some history of usage, or follow some other "TBD" method.... | @Test
public void testRQCalcGlobUsedLessThanConfigTest() throws PulsarAdminException {
final long config = 100;
final long localUsed = 20;
final long[] allUsage = { 40 };
final long newQuota = this.rqCalc.computeLocalQuota(config, localUsed, allUsage);
Assert.assertTrue(newQu... |
@Override
public double getStdDev() {
// two-pass algorithm for variance, avoids numeric overflow
if (values.length <= 1) {
return 0;
}
final double mean = getMean();
double sum = 0;
for (long value : values) {
final double diff = value - me... | @Test
public void calculatesAStdDevOfZeroForAnEmptySnapshot() {
final Snapshot emptySnapshot = new UniformSnapshot(new long[]{});
assertThat(emptySnapshot.getStdDev())
.isZero();
} |
public String join(final Stream<?> parts) {
return join(parts.iterator());
} | @Test
public void shouldHandleTwoItems() {
assertThat(joiner.join(ImmutableList.of(1, 2)), is("1 or 2"));
} |
private AlarmId(DeviceId id, String uniqueIdentifier) {
super(id.toString() + ":" + uniqueIdentifier);
checkNotNull(id, "device id must not be null");
checkNotNull(uniqueIdentifier, "unique identifier must not be null");
checkArgument(!uniqueIdentifier.isEmpty(), "unique identifier must ... | @Test
public void testNonEquality() {
final AlarmId id1 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_1);
final AlarmId id2 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_2);
assertThat(id1, is(not(id2)));
} |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
try {
if(containerService.isContainer(folder)) {
final Storage.Buckets.Insert request = session.getClient().buckets().insert(session.getHost().getCredentials().getUsername(),
... | @Test
public void testMakeBucket() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(),
new AsciiRandomStringService().random().toLowerCase(Locale.ROOT), EnumSet.of(Path.Type.directory, Path.Type.volume));
new GoogleStorageDirectoryFeature(sessi... |
public static GetNodesToAttributesResponse mergeNodesToAttributesResponse(
Collection<GetNodesToAttributesResponse> responses) {
Map<String, Set<NodeAttribute>> attributesMap = new HashMap<>();
for (GetNodesToAttributesResponse response : responses) {
if (response != null && response.getNodeToAttrib... | @Test
public void testMergeNodesToAttributesResponse() {
// normal response1
NodeAttribute gpu = NodeAttribute.newInstance(NodeAttribute.PREFIX_CENTRALIZED, "GPU",
NodeAttributeType.STRING, "nvida");
NodeAttribute os = NodeAttribute.newInstance(NodeAttribute.PREFIX_CENTRALIZED, "OS",
NodeA... |
public GetTelemetrySubscriptionsResponse processGetTelemetrySubscriptionRequest(
GetTelemetrySubscriptionsRequest request, RequestContext requestContext) {
long now = time.milliseconds();
Uuid clientInstanceId = Optional.ofNullable(request.data().clientInstanceId())
.filter(id -> !i... | @Test
public void testGetTelemetrySameClientImmediateRetryFail() throws Exception {
GetTelemetrySubscriptionsRequest request = new GetTelemetrySubscriptionsRequest.Builder(
new GetTelemetrySubscriptionsRequestData(), true).build();
GetTelemetrySubscriptionsResponse response = clientMetr... |
public JobStatus getJobStatus(JobID oldJobID) throws IOException {
org.apache.hadoop.mapreduce.v2.api.records.JobId jobId =
TypeConverter.toYarn(oldJobID);
GetJobReportRequest request =
recordFactory.newRecordInstance(GetJobReportRequest.class);
request.setJobId(jobId);
JobReport report = ... | @Test
public void testJobReportFromHistoryServer() throws Exception {
MRClientProtocol historyServerProxy = mock(MRClientProtocol.class);
when(historyServerProxy.getJobReport(getJobReportRequest())).thenReturn(
getJobRep... |
@Override
public State cancel() throws IOException {
// Enforce that a cancel() call on the job is done at most once - as
// a workaround for Dataflow service's current bugs with multiple
// cancellation, where it may sometimes return an error when cancelling
// a job that was already cancelled, but s... | @Test
public void testCancelTerminatedJob() throws IOException {
Dataflow.Projects.Locations.Jobs.Get statusRequest =
mock(Dataflow.Projects.Locations.Jobs.Get.class);
Job statusResponse = new Job();
statusResponse.setCurrentState("JOB_STATE_FAILED");
when(mockJobs.get(PROJECT_ID, REGION_ID, ... |
public static ConfigRepoConfig createConfigRepoConfig(MaterialConfig repo, String pluginId, String id) {
return (ConfigRepoConfig) new ConfigRepoConfig().setRepo(repo).setPluginId(pluginId).setId(id);
} | @Test
public void validateTree_configRepoShouldBeInvalidIfMaterialConfigHasErrors() {
CruiseConfig cruiseConfig = new BasicCruiseConfig();
MaterialConfig materialConfig = new GitMaterialConfig(); // should be invalid since URL is not set
ConfigRepoConfig configRepoConfig = ConfigRepoConfig.... |
@Override
public void decrementOnlyReserved(@Nonnull UUID txnId) {
decrement0(txnId, false);
} | @Test
public void decrementOnlyReserved() {
UUID txnId = UuidUtil.newSecureUUID();
for (int i = 0; i < 11; i++) {
counter.increment(txnId, false);
}
for (int i = 0; i < 11; i++) {
counter.decrementOnlyReserved(txnId);
}
Map<UUID, Long> countP... |
protected final void checkNotClosed() {
if (closed) {
throw new IllegalStateException("This connection manager has already been closed.");
}
} | @Test
void testCheckNotClosed() {
AbstractServiceConnectionManager<Object> connectionManager =
new TestServiceConnectionManager();
connectionManager.checkNotClosed();
connectionManager.connect(new Object());
connectionManager.checkNotClosed();
connectionMan... |
public static FilePredicate create(Collection<FilePredicate> predicates) {
if (predicates.isEmpty()) {
return TruePredicate.TRUE;
}
AndPredicate result = new AndPredicate();
for (FilePredicate filePredicate : predicates) {
if (filePredicate == TruePredicate.TRUE) {
continue;
} ... | @Test
public void simplifyAndExpressionsWhenEmpty() {
FilePredicate andPredicate = AndPredicate.create(Arrays.asList());
assertThat(andPredicate).isEqualTo(TruePredicate.TRUE);
} |
@VisibleForTesting
static int checkJar(Path file) throws Exception {
final URI uri = file.toUri();
int numSevereIssues = 0;
try (final FileSystem fileSystem =
FileSystems.newFileSystem(
new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment... | @Test
void testIgnoreWebThirdPartyLicenses(@TempDir Path tempDir) throws Exception {
assertThat(
JarFileChecker.checkJar(
createJar(
tempDir,
Entry.fileEntry(VALID_NOTICE_C... |
@Override
public boolean createReservation(ReservationId reservationId, String user,
Plan plan, ReservationDefinition contract) throws PlanningException {
LOG.info("placing the following ReservationRequest: " + contract);
try {
boolean res =
planner.createReservation(reservationId, use... | @Test
public void testOrder() throws PlanningException {
prepareBasicPlan();
// create a completely utilized segment around time 30
int[] f = { 100, 100 };
ReservationDefinition rDef =
ReservationSystemTestUtil.createSimpleReservationDefinition(30 * step,
30 * step + f.length * s... |
static Object parseCell(String cell, Schema.Field field) {
Schema.FieldType fieldType = field.getType();
try {
switch (fieldType.getTypeName()) {
case STRING:
return cell;
case INT16:
return Short.parseShort(cell);
case INT32:
return Integer.parseInt(c... | @Test
public void givenValidDoubleCell_parses() {
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("10.05", 10.05);
Schema schema = Schema.builder().addDoubleField("a_double").addStringField("a_string").build();
assertEquals(
cellToExpectedValue.getValue(),
CsvIOParseHelpers.parse... |
public static Type transformTableColumnType(Type srcType) {
return transformTableColumnType(srcType, true);
} | @Test
public void testConvertCatalogMaxStringToOlapMaxString() {
ScalarType catalogString = ScalarType.createDefaultCatalogString();
ScalarType convertedString = (ScalarType) AnalyzerUtils.transformTableColumnType(catalogString);
Assert.assertEquals(ScalarType.getOlapMaxVarcharLength(), conv... |
public static <T> T[] remove(final T[] oldElements, final T elementToRemove)
{
final int length = oldElements.length;
int index = UNKNOWN_INDEX;
for (int i = 0; i < length; i++)
{
if (oldElements[i] == elementToRemove)
{
index = i;
... | @Test
void shouldRemoveByIndex()
{
final Integer[] result = ArrayUtil.remove(values, 0);
assertArrayEquals(new Integer[]{ TWO }, result);
} |
public void complete(T value) {
try {
if (value instanceof RuntimeException)
throw new IllegalArgumentException("The argument to complete can not be an instance of RuntimeException");
if (!result.compareAndSet(INCOMPLETE_SENTINEL, value))
throw new Illega... | @Test
public void testRuntimeExceptionInComplete() {
RequestFuture<Exception> future = new RequestFuture<>();
assertThrows(IllegalArgumentException.class, () -> future.complete(new RuntimeException()));
} |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldNotCastStringNonNumber() {
// When:
assertThrows(
NumberFormatException.class,
() -> cast("abc", 2, 1)
);
} |
@VisibleForTesting
static boolean shouldIncludeRequestMessageHeader(final String header) {
return !HttpHeaders.X_FORWARDED_FOR.equalsIgnoreCase(header.trim());
} | @Test
void testShouldIncludeRequestMessageHeader() {
assertThat(WebSocketResourceProvider.shouldIncludeRequestMessageHeader(HttpHeaders.X_FORWARDED_FOR)).isFalse();
assertThat(WebSocketResourceProvider.shouldIncludeRequestMessageHeader(HttpHeaders.USER_AGENT)).isTrue();
assertThat(WebSocketResourceProvide... |
@Asn1Property(tagNo = 0x30, converter = DigestsConverter.class)
public Map<Integer, byte[]> getDigests() {
return digests;
} | @Test
public void readRvig2014Cms() throws Exception {
final LdsSecurityObject ldsSecurityObject = mapper.read(
readFromCms("rvig2014"), LdsSecurityObject.class);
assertEquals(ImmutableSet.of(1, 2, 3, 14, 15), ldsSecurityObject.getDigests().keySet());
} |
public byte tunGpeNp() {
return tunGpeNp;
} | @Test
public void testConstruction() {
final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1);
assertThat(tunGpeNp1, is(notNullValue()));
assertThat(tunGpeNp1.tunGpeNp(), is(np1));
} |
private ListUtil() {
} | @Test
public void testListUtil() {
Assertions.assertNotNull(ListUtil.emptyIsDefault(Collections.emptyList(), Collections.singletonList(1)));
Assertions.assertNotNull(ListUtil.findFirst(Collections.singletonList(1), res -> res == 1));
Assertions.assertNull(ListUtil.findFirst(Collections.singl... |
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
... | @Test
public void testHashpwSaltIsNull() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class);
BCrypt.hashpw("foo", null);
} |
public static Builder newIntegerColumnDefBuilder() {
return new Builder();
} | @Test
public void builder_setDefaultValue_sets_default_value_field_of_IntegerColumnDef() {
assertThat(newIntegerColumnDefBuilder().setColumnName("a").setDefaultValue(42).build().getDefaultValue()).isEqualTo(42);
} |
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
return usage(args);
}
String action = args[0];
String name = args[1];
int result;
if (A_LOAD.equals(action)) {
result = loadClass(name);
} else if (A_CREATE.equals(action)) {
//first load t... | @Test
public void testCreateFailsNoEmptyConstructor() throws Throwable {
run(FindClass.E_CREATE_FAILED,
FindClass.A_CREATE,
"org.apache.hadoop.util.TestFindClass$NoEmptyConstructor");
} |
public ProtocolBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
} | @Test
void queues() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.queues(30);
Assertions.assertEquals(30, builder.build().getQueues());
} |
public abstract T newEmptyValue(long timeMillis); | @Test
void testNewEmptyValue() {
assertEquals(0L, window.newEmptyValue(System.currentTimeMillis()).sum());
} |
public String getBaseBonitaURI() {
return "http://" + hostname + ":" + port + "/bonita";
} | @Test
public void testBaseBonitaURL() {
BonitaAPIConfig config = new BonitaAPIConfig("host", "port", "username", "password");
assertEquals("http://host:port/bonita", config.getBaseBonitaURI());
} |
@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getChildChannelHandlers(MessageInput input) {
final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>();
final CodecAggregator aggregator = getAggregator();
handlers.put("cha... | @Test
public void getChildChannelHandlersFailsIfTempDirDoesNotExist() throws IOException {
final File tmpDir = temporaryFolder.newFolder();
assumeTrue(tmpDir.delete());
System.setProperty("java.io.tmpdir", tmpDir.getAbsolutePath());
final Configuration configuration = new Configurat... |
public FEELFnResult<Map<String, Object>> invoke(@ParameterName("entries") List<Object> entries) {
if (entries == null) {
return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "entries", "cannot be null"));
}
Map<String, Object> result = new HashMap<>();
... | @Test
void invokeContainsNoKeyAndValue() {
FunctionTestUtil.assertResultError(contextFunction.invoke(List.of(
Map.of("test", "name", "value", "John Doe"),
Map.of("key", "name", "test", "John Doe"))), InvalidParametersEvent.class);
} |
@Override
public KvMetadata resolveMetadata(
boolean isKey,
List<MappingField> resolvedFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void test_resolvePrimitiveMetadata(boolean key, String path) {
Map<String, String> options = Map.of(
(key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT,
(key ? OPTION_KEY_CLAS... |
public void updateTableStatistics(String dbName, String tableName, Function<HivePartitionStats, HivePartitionStats> update) {
org.apache.hadoop.hive.metastore.api.Table originTable = client.getTable(dbName, tableName);
if (originTable == null) {
throw new StarRocksConnectorException("Table '... | @Test
public void testUpdateTableStatistics() {
HiveMetaClient client = new MockedHiveMetaClient();
HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS);
HivePartitionStats partitionStats = HivePartitionStats.empty();
metastore.updateTableStatistics(... |
@Override
public void deconstruct(long generation, List<Object> components, Collection<Bundle> bundles) {
Collection<Deconstructable> destructibleComponents = new ArrayList<>();
for (var component : components) {
if (component instanceof AbstractComponent) {
AbstractCompo... | @Test
void require_abstract_component_destructed() throws InterruptedException {
TestAbstractComponent abstractComponent = new TestAbstractComponent();
deconstructor.deconstruct(0, List.of(abstractComponent), List.of());
waitForDeconstructToComplete(() -> abstractComponent.destructed);
... |
@Override
@SuppressWarnings("checkstyle:magicnumber")
public void process(int ordinal, @Nonnull Inbox inbox) {
try {
switch (ordinal) {
case 0:
process0(inbox);
break;
case 1:
process1(inbox);
... | @Test
public void when_processInbox5_then_tryProcessCalled() {
// When
tryProcessP.process(ORDINAL_5, inbox);
// Then
tryProcessP.validateReceptionOfItem(ORDINAL_5, MOCK_ITEM);
} |
public void recordMetric(long time, String command,
String user, long delta) {
RollingWindow window = getRollingWindow(command, user);
window.incAt(time, delta);
} | @Test
public void windowReset() throws Exception {
Configuration config = new Configuration();
config.setInt(DFSConfigKeys.NNTOP_BUCKETS_PER_WINDOW_KEY, 1);
config.setInt(DFSConfigKeys.NNTOP_NUM_USERS_KEY, N_TOP_USERS);
int period = 2;
RollingWindowManager rollingWindowManager =
new Rollin... |
@Override
public Integer clusterGetSlotForKey(byte[] key) {
RFuture<Integer> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.KEYSLOT, key);
return syncFuture(f);
} | @Test
public void testClusterGetSlotForKey() {
Integer slot = connection.clusterGetSlotForKey("123".getBytes());
assertThat(slot).isNotNull();
} |
@VisibleForTesting
public void doSampling(long millisSinceLastSample) {
for (ExecutionStateTracker tracker : activeTrackers) {
tracker.takeSample(millisSinceLastSample);
}
} | @Test
public void testLullDetectionOccurs() throws Exception {
ExecutionStateTracker tracker1 = createTracker();
try (Closeable t1 = tracker1.activate(new Thread())) {
try (Closeable c = tracker1.enterState(step1act1)) {
sampler.doSampling(TimeUnit.MINUTES.toMillis(6));
}
}
assert... |
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()")
@PostMapping("/users")
public void createOrUpdateUser(
@RequestParam(value = "isCreate", defaultValue = "false") boolean isCreate,
@RequestBody UserPO user) {
if (StringUtils.isContainEmpty(user.getUsername(), user.getPassword())) {
... | @Test(expected = BadRequestException.class)
public void testCreateOrUpdateUserFailed() {
UserPO user = new UserPO();
user.setUsername("username");
user.setPassword("password");
String msg = "fake error message";
Mockito.when(userPasswordChecker.checkWeakPassword(Mockito.anyString()))
.th... |
public void deleteTenant(TenantName name) {
if (name.equals(DEFAULT_TENANT))
throw new IllegalArgumentException("Deleting 'default' tenant is not allowed");
if ( ! tenants.containsKey(name))
throw new IllegalArgumentException("Deleting '" + name + "' failed, tenant does not exist... | @Test
public void testDeleteTenant() throws Exception {
assertZooKeeperTenantPathExists(tenant1);
tenantRepository.deleteTenant(tenant1);
assertFalse(tenantRepository.getAllTenantNames().contains(tenant1));
try {
tenantRepository.deleteTenant(TenantName.from("non-existin... |
public SubscriptionStatsImpl add(SubscriptionStatsImpl stats) {
Objects.requireNonNull(stats);
this.msgRateOut += stats.msgRateOut;
this.msgThroughputOut += stats.msgThroughputOut;
this.bytesOutCounter += stats.bytesOutCounter;
this.msgOutCounter += stats.msgOutCounter;
t... | @Test
public void testAdd_EarliestMsgPublishTimeInBacklogs_Earliest() {
SubscriptionStatsImpl stats1 = new SubscriptionStatsImpl();
stats1.earliestMsgPublishTimeInBacklog = 10L;
SubscriptionStatsImpl stats2 = new SubscriptionStatsImpl();
stats2.earliestMsgPublishTimeInBacklog = 20L;... |
public Publisher<K> keyIterator() {
return keyIterator(null);
} | @Test
public void testPutAll() {
RMapRx<Integer, String> map = redisson.getMap("simple");
sync(map.put(1, "1"));
sync(map.put(2, "2"));
sync(map.put(3, "3"));
Map<Integer, String> joinMap = new HashMap<Integer, String>();
joinMap.put(4, "4");
joinMap.put(5, "... |
public boolean requireStable() {
return data.requireStable();
} | @Test
public void testBuildThrowForUnsupportedRequireStable() {
for (int version : listOfVersionsNonBatchOffsetFetch) {
builder = new OffsetFetchRequest.Builder(group1, true, null, true);
if (version < 7) {
final short finalVersion = (short) version;
a... |
public long accumulateAndGet(long x, LongBinaryOperator f) {
long prev, next;
do {
prev = lvVal();
next = f.applyAsLong(prev, x);
} while (!casVal(prev, next));
return next;
} | @Test
public void testAccumulateAndGet() {
PaddedAtomicLong counter = new PaddedAtomicLong(10);
long value = counter.accumulateAndGet(1, (left, right) -> left+right);
assertEquals(value, 11);
assertEquals(11, counter.get());
} |
public static String formatAnnotation(Annotation annotation) {
String annotationName = annotation.annotationType().getName();
String annotationNameWithoutPackage =
annotationName.substring(annotationName.lastIndexOf('.') + 1).replace('$', '.');
String annotationToString = annotation.toString();
... | @Test
public void testFormatAnnotationJsonIgnore() throws Exception {
assertEquals(
"JsonIgnore(value=true)",
ReflectHelpers.formatAnnotation(Options.class.getMethod("getObject").getAnnotations()[0]));
} |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testJsonPath() {
run(
"def foo = { a: 1, b: { a: 2 } }",
"def res1 = karate.jsonPath(foo, '$..a')",
"def arr = [ {'id': 1, 'name': 'test', 'age': 10}, {'id': 2, 'name': 'test2', 'age': 20} ]",
"def res2 = karate.jsonPath(arr, '$.[?(@... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldFailIfVersionAlreadyExists() throws Exception {
// Given:
givenVersionsExist("12");
command = PARSER.parse(DESCRIPTION, "-v", "12");
// When:
final int result = command.command(migrationsDir);
// Then:
assertThat(result, is(1));
} |
public Optional<Details> runForeachBatch(
Workflow workflow,
Long internalId,
long workflowVersionId,
RunProperties runProperties,
String foreachStepId,
ForeachArtifact artifact,
List<RunRequest> requests,
List<Long> instanceIds,
int batchSize) {
if (ObjectHelpe... | @Test
public void testRestartRunForeachBatch() {
ForeachArtifact artifact = new ForeachArtifact();
artifact.setRunPolicy(RunPolicy.RESTART_FROM_INCOMPLETE);
artifact.setTotalLoopCount(10);
artifact.setForeachWorkflowId(instance.getWorkflowId());
artifact.setForeachRunId(3L);
RunRequest request... |
public void encryptColumns(
String inputFile, String outputFile, List<String> paths, FileEncryptionProperties fileEncryptionProperties)
throws IOException {
Path inPath = new Path(inputFile);
Path outPath = new Path(outputFile);
RewriteOptions options = new RewriteOptions.Builder(conf, inPath, o... | @Test
public void testDifferentCompression() throws IOException {
String[] encryptColumns = {"Links.Forward"};
String[] compressions = {"GZIP", "ZSTD", "SNAPPY", "UNCOMPRESSED"};
for (String compression : compressions) {
testSetup(compression);
columnEncryptor.encryptColumns(
inputFi... |
public int startWithRunStrategy(
@NotNull WorkflowInstance instance, @NotNull RunStrategy runStrategy) {
return withMetricLogError(
() ->
withRetryableTransaction(
conn -> {
final long nextInstanceId =
getLatestInstanceId(conn, instan... | @Test
public void testStartWithRunStrategyForNewStart() {
wfi.setWorkflowInstanceId(0L);
wfi.setWorkflowRunId(0L);
wfi.setWorkflowUuid("test-uuid");
int res = runStrategyDao.startWithRunStrategy(wfi, Defaults.DEFAULT_RUN_STRATEGY);
assertEquals(1, res);
assertEquals(2, wfi.getWorkflowInstanceI... |
public static String getRootNodePath() {
return String.join("/", "", ROOT_NODE);
} | @Test
void assertRooPath() {
assertThat(ListenerAssistedNodePath.getRootNodePath(), is("/listener_assisted"));
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamRangeAndRange() {
FunctionTestUtil.assertResult( finishesFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ),
... |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_duplicated_lines_counts_lines_from_original_and_ignores_CrossProjectDuplicate() {
TextBlock original = new TextBlock(1, 1);
duplicationRepository.addCrossProjectDuplication(FILE_1_REF, original, SOME_FILE_KEY, new TextBlock(2, 2));
setNewLines(FILE_1);
underTest.execute(new ... |
public static Buffer toBuffer(AbstractEvent event, boolean hasPriority) throws IOException {
final ByteBuffer serializedEvent = EventSerializer.toSerializedEvent(event);
MemorySegment data = MemorySegmentFactory.wrap(serializedEvent.array());
final Buffer buffer =
new NetworkBu... | @Test
void testToBuffer() throws IOException {
for (AbstractEvent evt : events) {
Buffer buffer = EventSerializer.toBuffer(evt, false);
assertThat(buffer.isBuffer()).isFalse();
assertThat(buffer.readableBytes()).isGreaterThan(0);
assertThat(buffer.isRecycled(... |
@SuppressWarnings("deprecation")
public boolean setSocketOpt(int option, Object optval)
{
final ValueReference<Boolean> result = new ValueReference<>(false);
switch (option) {
case ZMQ.ZMQ_SNDHWM:
sendHwm = (Integer) optval;
if (sendHwm < 0) {
thro... | @Test(expected = IllegalArgumentException.class)
public void testHeartbeatIvlUnderflow()
{
options.setSocketOpt(ZMQ.ZMQ_HEARTBEAT_IVL, -1);
} |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForStreamGroupBy() {
// Given:
final StreamGroupBy<?> step = new StreamGroupBy<>(
PROPERTIES,
streamSource,
formats,
ImmutableList.of(new UnqualifiedColumnReferenceExp(Optional.empty(), ORANGE_COL))
);
// When:
final LogicalSche... |
public boolean addMetadataString(String rawMetadata) throws UnmarshallingException {
InputStream inputStream = new ByteArrayInputStream(rawMetadata.getBytes(UTF_8));
XMLObject metadata = super.unmarshallMetadata(inputStream);
if (!isValid(metadata)) {
return false;
}
... | @Test
public void addMetadataStringTest() throws UnmarshallingException {
assertTrue(stringMetadataResolver.addMetadataString(metadata));
} |
public List<String> toList(boolean trim) {
return toList((str) -> trim ? StrUtil.trim(str) : str);
} | @Test
public void splitByCharIgnoreCaseTest(){
String str1 = "a, ,,eAedsas, ddf,";
//不忽略""
SplitIter splitIter = new SplitIter(str1,
new CharFinder('a', true),
Integer.MAX_VALUE,
false
);
assertEquals(4, splitIter.toList(false).size());
} |
@Override
public String pwd() {
try {
return client.printWorkingDirectory();
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | @Test
@Disabled
public void existSftpTest() throws Exception {
try (final Sftp ftp = new Sftp("127.0.0.1", 22, "test", "test")) {
Console.log(ftp.pwd());
Console.log(ftp.exist(null));
Console.log(ftp.exist(""));
Console.log(ftp.exist("."));
Console.log(ftp.exist(".."));
Console.log(ftp.exist("/"))... |
@Override
public void createRouter(KubevirtRouter router) {
checkNotNull(router, ERR_NULL_ROUTER);
checkArgument(!Strings.isNullOrEmpty(router.name()), ERR_NULL_ROUTER_NAME);
kubevirtRouterStore.createRouter(router);
log.info(String.format(MSG_ROUTER, router.name(), MSG_CREATED));
... | @Test(expected = IllegalArgumentException.class)
public void createDuplicateRouter() {
target.createRouter(ROUTER);
target.createRouter(ROUTER);
} |
static KiePMMLMissingValueWeights getKiePMMLMissingValueWeights(MissingValueWeights missingValueWeights) {
return missingValueWeights != null ? new KiePMMLMissingValueWeights(getMissingValueWeightsDoubleValues(missingValueWeights)) : null;
} | @Test
void getKiePMMLMissingValueWeights() {
assertThat(KiePMMLClusteringModelFactory.getKiePMMLMissingValueWeights(null)).isNull();
KiePMMLMissingValueWeights retrieved =
KiePMMLClusteringModelFactory.getKiePMMLMissingValueWeights(new MissingValueWeights());
assertThat(retri... |
@Override
public void createLoadBalancer(KubevirtLoadBalancer lb) {
checkNotNull(lb, ERR_NULL_LOAD_BALANCER);
checkArgument(!Strings.isNullOrEmpty(lb.name()), ERR_NULL_LOAD_BALANCER_NAME);
kubevirtLoadBalancerStore.createLoadBalancer(lb);
log.info(String.format(MSG_LOAD_BALANCER, lb... | @Test(expected = NullPointerException.class)
public void testCreateNullLoadBalancer() {
target.createLoadBalancer(null);
} |
@Override
public Map<String, Long> countByType() {
final Map<String, Long> outputsCountByType = new HashMap<>();
try (DBCursor outputTypes = dbCollection.find(null, new BasicDBObject(OutputImpl.FIELD_TYPE, 1))) {
for (DBObject outputType : outputTypes) {
final String typ... | @Test
@MongoDBFixtures("OutputServiceImplTest.json")
public void countByTypeReturnsNumberOfOutputsByType() {
assertThat(outputService.countByType())
.hasSize(2)
.containsEntry("org.graylog2.outputs.LoggingOutput", 1L)
.containsEntry("org.graylog2.outputs.G... |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void parseWindows10WithIe8EmulatorTest() {
final String uaStr = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";
final UserAgent ua = UserAgentUtil.parse(uaStr);
assertEquals("MSIE", ua.getBrowser().toString());
assertEquals("8.0", ua.getVersion());
assertEquals("Trident", ua.g... |
@Override
public Optional<String> getValue(Object arg, String type) {
return arg == null ? Optional.empty() : Optional.of(String.valueOf(arg));
} | @Test
public void testValue() {
TypeStrategy strategy = new EmptyTypeStrategy();
// normal
Assert.assertEquals("foo", strategy.getValue("foo", "").orElse(null));
// normal
Assert.assertEquals("foo", strategy.getValue("foo", null).orElse(null));
// the test is not e... |
@Override
public int delete(String id) {
return this.coll.removeById(id).getN();
} | @Test
@MongoDBFixtures("DecoratorServiceImplTest.json")
public void delete() {
assertThat(decoratorService.findAll()).hasSize(3);
assertThat(decoratorService.delete("588bcafebabedeadbeef0001")).isEqualTo(1);
assertThat(decoratorService.findAll()).hasSize(2);
assertThat(decoratorS... |
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
} | @Test
public void testInvocationWithServiceName() {
RedissonClient server = createInstance();
RedissonClient client = createInstance();
server.getRemoteService("MyServiceNamespace").register(RemoteInterface.class, new RemoteImpl());
RemoteInterface serviceRemoteInterface = client.g... |
public static void log() {
out.println();
} | @Test
public void logTest(){
Console.log();
String[] a = {"abc", "bcd", "def"};
Console.log(a);
Console.log("This is Console log for {}.", "test");
} |
@Override
public void setParentJobMeta( JobMeta parentJobMeta ) {
JobMeta previous = getParentJobMeta();
super.setParentJobMeta( parentJobMeta );
if ( parentJobMeta != null ) {
parentJobMeta.addCurrentDirectoryChangedListener( currentDirListener );
variables.setParentVariableSpace( parentJobM... | @Test
public void testCurrDirListener() throws Exception {
JobMeta meta = mock( JobMeta.class );
JobEntryTrans jet = getJobEntryTrans();
jet.setParentJobMeta( meta );
jet.setParentJobMeta( null );
verify( meta, times( 1 ) ).addCurrentDirectoryChangedListener( any() );
verify( meta, times( 1 ) ... |
@Override
public SchemaResult getKeySchema(
final Optional<String> topicName,
final Optional<Integer> schemaId,
final FormatInfo expectedFormat,
final SerdeFeatures serdeFeatures
) {
return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true);
} | @Test
public void shouldRequestCorrectSchemaOnGetKeySchema() throws Exception {
// When:
supplier.getKeySchema(Optional.of(TOPIC_NAME),
Optional.empty(), expectedFormat, SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES));
// Then:
verify(srClient).getLatestSchemaMetadata(TOPIC_NAME + "-key");
} |
public static void addMaskForCredential(Map<String, String> params) {
params.computeIfPresent(CloudConfigurationConstants.AWS_S3_ACCESS_KEY, (key, value) -> CREDENTIAL_MASK);
params.computeIfPresent(CloudConfigurationConstants.AWS_S3_SECRET_KEY, (key, value) -> CREDENTIAL_MASK);
params.computeIf... | @Test
public void testAddMaskForCredential() {
Map<String, String> storageParams = new HashMap<>();
storageParams.put(AWS_S3_ACCESS_KEY, "accessKey");
storageParams.put(AWS_S3_SECRET_KEY, "secretKey");
storageParams.put(AZURE_BLOB_SAS_TOKEN, "sasToken");
storageParams.put(AZU... |
public static Catalog loadCatalog(
String impl, String catalogName, Map<String, String> properties, Object hadoopConf) {
Preconditions.checkNotNull(impl, "Cannot initialize custom Catalog, impl class name is null");
DynConstructors.Ctor<Catalog> ctor;
try {
ctor = DynConstructors.builder(Catalog... | @Test
public void loadCustomCatalog_withHadoopConfig() {
Map<String, String> options = Maps.newHashMap();
options.put("key", "val");
Configuration hadoopConf = new Configuration();
hadoopConf.set("key", "val");
String name = "custom";
Catalog catalog =
CatalogUtil.loadCatalog(TestCatal... |
@Override
public void handle(LogHandlerEvent event) {
switch (event.getType()) {
case APPLICATION_STARTED:
LogHandlerAppStartedEvent appStartEvent =
(LogHandlerAppStartedEvent) event;
initApp(appStartEvent.getApplicationId(), appStartEvent.getUser(),
appStartEvent.get... | @Test
public void testRemoteRootLogDirIsCreatedWithCorrectGroupOwner()
throws IOException {
this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath());
Path aNewFile = new Path(String.valueOf("tmp"+System.currentTimeMillis()));
this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, ... |
@Override
public Collection<DatabasePacket> execute() {
failedIfContainsMultiStatements();
MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts();
SQLParserRule sqlParserRule = metaDataContexts.getMetaData().getGlobalRuleMetaData().getSingleR... | @Test
void assertPrepareNotAllowedStatement() {
when(packet.getSQL()).thenReturn("begin");
ContextManager contextManager = mockContextManager();
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
assertThrows(UnsupportedPreparedStatementException.class, ... |
public TreeMap<Integer, T_PreKey> generateOmemoPreKeys(int startId, int count) {
return keyUtil().generateOmemoPreKeys(startId, count);
} | @Test
public void generateOmemoPreKeys() {
TreeMap<Integer, T_PreKey> keys = store.generateOmemoPreKeys(31, 49);
assertNotNull("Generated data structure must not be null.", keys);
byte[] lastKey = null;
for (int i = 31; i <= 79; i++) {
assertEquals("Key ids must be asce... |
@Override
public String getManagedUsersSqlFilter(boolean filterByManaged) {
return findManagedInstanceService()
.map(managedInstanceService -> managedInstanceService.getManagedUsersSqlFilter(filterByManaged))
.orElseThrow(() -> NOT_MANAGED_INSTANCE_EXCEPTION);
} | @Test
public void getManagedUsersSqlFilter_delegatesToRightService_andPropagateAnswer() {
AlwaysManagedInstanceService alwaysManagedInstanceService = new AlwaysManagedInstanceService();
DelegatingManagedServices managedInstanceService = new DelegatingManagedServices(Set.of(new NeverManagedInstanceService(), a... |
public CompletableFuture<Set<MessageQueue>> lockBatchMQ(ProxyContext ctx, Set<MessageQueue> mqSet,
String consumerGroup, String clientId, long timeoutMillis) {
CompletableFuture<Set<MessageQueue>> future = new CompletableFuture<>();
try {
Set<MessageQueue> successSet = new CopyOnWrit... | @Test
public void testLockBatchPartialSuccessWithException() throws Throwable {
Set<MessageQueue> mqSet = new HashSet<>();
MessageQueue mq1 = new MessageQueue(TOPIC, "broker1", 0);
AddressableMessageQueue addressableMessageQueue1 = new AddressableMessageQueue(mq1, "127.0.0.1");
Messa... |
@Override
public void setWhereFrom(final Local file, final String dataUrl) throws LocalAccessDeniedException {
synchronized(lock) {
if(StringUtils.isBlank(dataUrl)) {
log.warn("No data url given");
return;
}
if(!this.setWhereFrom(file.getAb... | @Test
public void testSetWhereEmptyUrl() throws Exception {
final QuarantineService q = new LaunchServicesQuarantineService();
q.setWhereFrom(new NullLocal("/", "n"), null);
q.setWhereFrom(new NullLocal("/", "n"), StringUtils.EMPTY);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.