focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Description("Infinity")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double infinity()
{
return Double.POSITIVE_INFINITY;
} | @Test
public void testInfinity()
{
assertFunction("infinity()", DOUBLE, Double.POSITIVE_INFINITY);
assertFunction("-rand() / 0.0", DOUBLE, Double.NEGATIVE_INFINITY);
} |
public static boolean equal(Number lhs, Number rhs) {
Class lhsClass = lhs.getClass();
Class rhsClass = rhs.getClass();
assert lhsClass != rhsClass;
if (isDoubleRepresentable(lhsClass)) {
if (isDoubleRepresentable(rhsClass)) {
return equalDoubles(lhs.doubleVa... | @Test
public void testEqual() {
assertNotEqual(1L, 2);
assertEqual(1, 1L);
assertEqual(1, (short) 1);
assertEqual(1, (byte) 1);
assertNotEqual(new AtomicLong(1), new AtomicInteger(1));
assertNotEqual(1, 1.1);
// 1.10000000000000008881784197001252323389053344... |
public void generateResponse(HttpServletResponse response, ArtifactResolveRequest artifactResolveRequest) throws SamlParseException {
try {
final var context = new MessageContext();
final var signType = determineSignType(artifactResolveRequest.getSamlSession());
String entity... | @Test
void generateResponseBVD() throws SamlParseException, MetadataException, BvdException, JsonProcessingException, UnsupportedEncodingException {
when(bvdClientMock.retrieveRepresentationAffirmations(anyString())).thenReturn(getBvdResponse());
when(bvdMetadataServiceMock.generateMetadata()).thenR... |
@Deprecated
@VisibleForTesting
static native void nativeVerifyChunkedSums(
int bytesPerSum, int checksumType,
ByteBuffer sums, int sumsOffset,
ByteBuffer data, int dataOffset, int dataLength,
String fileName, long basePos) throws ChecksumException; | @Test
@SuppressWarnings("deprecation")
public void testNativeVerifyChunkedSumsFail() {
allocateDirectByteBuffers();
fillDataAndInvalidChecksums();
assertThrows(ChecksumException.class,
() -> NativeCrc32.nativeVerifyChunkedSums(bytesPerChecksum,
checksumType.id, checksums, checksums.p... |
@Override
public V load(K key) {
awaitSuccessfulInit();
try (SqlResult queryResult = sqlService.execute(queries.load(), key)) {
Iterator<SqlRow> it = queryResult.iterator();
V value = null;
if (it.hasNext()) {
SqlRow sqlRow = it.next();
... | @Test
public void whenSetNonExistingColumn_thenFailToInitialize() {
ObjectSpec spec = objectProvider.createObject(mapName, false);
objectProvider.insertItems(spec, 1);
Properties properties = new Properties();
properties.setProperty(DATA_CONNECTION_REF_PROPERTY, TEST_DATABASE_REF);
... |
public String getName() {
return name;
} | @Test
public void getName() {
JobScheduleParam jobScheduleParam = mock( JobScheduleParam.class );
when( jobScheduleParam.getName() ).thenCallRealMethod();
String name = "hitachi";
ReflectionTestUtils.setField( jobScheduleParam, "name", name );
Assert.assertEquals( name, jobScheduleParam.getName() ... |
@Override
public void destroy() {
if (this.pubSubClient != null) {
try {
this.pubSubClient.shutdown();
this.pubSubClient.awaitTermination(1, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("Failed to shutdown PubSub client during d... | @Test
public void givenPubSubClientIsNull_whenDestroy_thenShutDownAndAwaitTermination() {
ReflectionTestUtils.setField(node, "pubSubClient", null);
node.destroy();
then(pubSubClientMock).shouldHaveNoInteractions();
} |
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
... | @Test
public void testObjectNotDefined() {
Dummy dummy = SingletonServiceFactory.getBean(Dummy.class);
Assert.assertNull(dummy);
} |
public int getPartitionId() {
return partitionId;
} | @Test
public void testGetPartitionId() {
assertEquals(42, dataEvent.getPartitionId());
assertEquals(42, objectEvent.getPartitionId());
} |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testRunBatchJobThatFails() throws Exception {
Pipeline p = TestPipeline.create(options);
PCollection<Integer> pc = p.apply(Create.of(1, 2, 3));
PAssert.that(pc).containsInAnyOrder(1, 2, 3);
DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class);
when(mockJob.getSt... |
public void removePublisherIndexesByEmptyService(Service service) {
if (publisherIndexes.containsKey(service) && publisherIndexes.get(service).isEmpty()) {
publisherIndexes.remove(service);
}
} | @Test
void testRemovePublisherIndexesByEmptyService() throws NoSuchFieldException, IllegalAccessException {
clientServiceIndexesManager.removePublisherIndexesByEmptyService(service);
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
... |
public static long parseBytesToLong(List<Byte> data) {
return parseBytesToLong(data, 0);
} | @Test
public void parseBytesToLong() {
byte[] longValByte = {64, -101, 4, -79, 12, -78, -107, -22};
Assertions.assertEquals(longVal, TbUtils.parseBytesToLong(longValByte, 0, 8));
Bytes.reverse(longValByte);
Assertions.assertEquals(longVal, TbUtils.parseBytesToLong(longValByte, 0, 8, ... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(new DefaultPathContainerService().isContainer(file)) {
return PathAttributes.EMPTY;
}
... | @Test
public void testFindRoot() throws Exception {
final DriveAttributesFinderFeature f = new DriveAttributesFinderFeature(session, new DriveFileIdProvider(session));
assertEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.volume, Path.Type.directory))));
} |
@Override
public List<Plugin> plugins() {
List<Plugin> plugins = configurationParameters.get(PLUGIN_PROPERTY_NAME, s -> Arrays.stream(s.split(","))
.map(String::trim)
.map(PluginOption::parse)
.map(pluginOption -> (Plugin) pluginOption)
.collec... | @Test
void getPluginNamesWithPublishQuiteEnabled() {
ConfigurationParameters config = new MapConfigurationParameters(
Constants.PLUGIN_PUBLISH_QUIET_PROPERTY_NAME, "true");
assertThat(new CucumberEngineOptions(config).plugins().stream()
.map(Options.Plugin::pluginString)... |
public static String getUserId() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
return request.getHeader(CommonConstants.USER_ID_HEADER... | @Test
public void testGetUserIdFromHeader() {
// Set up the expected user ID in the mock request object
String expectedUserId = "12345";
when(request.getHeader(CommonConstants.USER_ID_HEADER)).thenReturn(expectedUserId);
// Call the method under test
String userId = HeaderUt... |
public LongValue increment(long increment) {
this.value += increment;
this.set = true;
return this;
} | @Test
public void multiples_calls_to_increment_long_increment_the_value() {
LongValue variationValue = new LongValue()
.increment(10L)
.increment(95L);
verifySetVariationValue(variationValue, 105L);
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final Map<String, Object> event;
try {
event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT);
} catch (IOException e) {
... | @Test
public void decodeMessagesHandlesGenericBeatWithKubernetes() throws Exception {
final Message message = codec.decode(messageFromJson("generic-with-kubernetes.json"));
assertThat(message).isNotNull();
assertThat(message.getMessage()).isEqualTo("null");
assertThat(message.getSour... |
public synchronized void reset() {
if (trackedThread != null) {
CURRENT_TRACKERS.remove(trackedThread.getId());
trackedThread = null;
}
currentState = null;
numTransitions = 0;
millisSinceLastTransition = 0;
transitionsAtLastSample = 0;
nextLullReportMs = LULL_REPORT_MS;
} | @Test
public void testReset() throws Exception {
ExecutionStateTracker tracker = createTracker();
try (Closeable c1 = tracker.activate(new Thread())) {
try (Closeable c2 = tracker.enterState(testExecutionState)) {
sampler.doSampling(400);
assertThat(testExecutionState.totalMillis, equalT... |
@Override
public void commit(Commit commit) {
commitQueue.put(commit);
} | @Test
public void testCommit() {
List<CompleteCommit> completeCommits = new ArrayList<>();
workCommitter = createWorkCommitter(completeCommits::add);
List<Commit> commits = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
Work work = createMockWork(i);
Windmill.WorkItemCommitRequest commi... |
public static StructType convert(Schema schema) {
return (StructType) TypeUtil.visit(schema, new TypeToSparkType());
} | @Test
public void testSchemaConversionWithMetaDataColumnSchema() {
StructType structType = SparkSchemaUtil.convert(TEST_SCHEMA_WITH_METADATA_COLS);
List<AttributeReference> attrRefs =
scala.collection.JavaConverters.seqAsJavaList(DataTypeUtils.toAttributes(structType));
for (AttributeReference att... |
@Override
public boolean apply(InputFile f) {
if (path == null) {
return false;
}
return path.equals(f.relativePath());
} | @Test
public void returns_true_if_matches() {
RelativePathPredicate predicate = new RelativePathPredicate("path");
InputFile inputFile = mock(InputFile.class);
when(inputFile.relativePath()).thenReturn("path");
assertThat(predicate.apply(inputFile)).isTrue();
} |
public static <T> CompressedSource<T> from(FileBasedSource<T> sourceDelegate) {
return new CompressedSource<>(sourceDelegate, CompressionMode.AUTO);
} | @Test
public void testGzipProgress() throws IOException {
int numRecords = 3;
File tmpFile = tmpFolder.newFile("nonempty.gz");
String filename = tmpFile.toPath().toString();
writeFile(tmpFile, new byte[numRecords], Compression.GZIP);
PipelineOptions options = PipelineOptionsFactory.create();
... |
public static URI parse(String featureIdentifier) {
requireNonNull(featureIdentifier, "featureIdentifier may not be null");
if (featureIdentifier.isEmpty()) {
throw new IllegalArgumentException("featureIdentifier may not be empty");
}
// Legacy from the Cucumber Eclipse plug... | @Test
@EnabledOnOs(WINDOWS)
void can_parse_windows_absolute_path_form() {
URI uri = FeaturePath.parse("C:\\path\\to\\file.feature");
assertAll(
() -> assertThat(uri.getScheme(), is(is("file"))),
() -> assertThat(uri.getSchemeSpecificPart(), is("/C:/path/to/file.feature")... |
@Override
public InterpreterResult interpret(final String st, final InterpreterContext context)
throws InterpreterException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("st:\n{}", st);
}
final FormType form = getFormType();
RemoteInterpreterProcess interpreterProcess = null;
try {
... | @Test
void testFailToLaunchInterpreterProcess_Timeout() {
try {
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_REMOTE_RUNNER.getVarName(),
zeppelinHome.getAbsolutePath() + "/zeppelin-zengine/src/test/resources/bin/interpreter_timeout.sh");
System.setProperty(Zeppe... |
public static None createNoneHealthChecker() {
return new None();
} | @Test
void testCreateNoneHealthChecker() {
assertEquals(AbstractHealthChecker.None.class, HealthCheckerFactory.createNoneHealthChecker().getClass());
} |
@Config("failure-resolver.enabled")
public FailureResolverConfig setEnabled(boolean enabled)
{
this.enabled = enabled;
return this;
} | @Test
public void testDefault()
{
assertRecordedDefaults(recordDefaults(FailureResolverConfig.class)
.setEnabled(true));
} |
@Override
public <VAgg> KTable<K, VAgg> aggregate(final Initializer<VAgg> initializer,
final Aggregator<? super K, ? super V, VAgg> adder,
final Aggregator<? super K, ? super V, VAgg> subtractor,
... | @Test
public void shouldNotAllowNullInitializerOnAggregate() {
assertThrows(NullPointerException.class, () -> groupedTable.aggregate(
null,
MockAggregator.TOSTRING_ADDER,
MockAggregator.TOSTRING_REMOVER,
Materialized.as("store")));
} |
public void setSortKey(SortKey sortkey) {
if (Objects.equals(this.sortkey, sortkey)) {
return;
}
invalidate();
if (sortkey != null) {
int column = sortkey.getColumn();
if (valueComparators[column] == null) {
throw new IllegalArgumentEx... | @Test
public void sortValueDescending() {
sorter.setSortKey(new SortKey(1, SortOrder.DESCENDING));
assertRowOrderAndIndexes(asList(d4(), a3(), b2(), c1()));
} |
@Override
public AWSCredentials getCredentials() {
Credentials sessionCredentials = credentials.get();
if (Duration.between(clock.instant(), sessionCredentials.expiry).compareTo(REFRESH_INTERVAL)<0) {
refresh();
sessionCredentials = credentials.get();
}
return... | @Test
void deserializes_credentials() throws IOException {
Instant originalExpiry = clock.instant().plus(Duration.ofHours(12));
writeCredentials(credentialsPath, originalExpiry);
VespaAwsCredentialsProvider credentialsProvider = new VespaAwsCredentialsProvider(credentialsPath, clock);
... |
public static Schema create(Type type) {
switch (type) {
case STRING:
return new StringSchema();
case BYTES:
return new BytesSchema();
case INT:
return new IntSchema();
case LONG:
return new LongSchema();
case FLOAT:
return new FloatSchema();
case DOUBLE:
... | @Test
void validLongAsIntDefaultValue() {
Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.INT), "doc", 1L);
assertTrue(field.hasDefaultValue());
assertEquals(1, field.defaultVal());
assertEquals(1, GenericData.get().getDefaultValue(field));
field = new Schema.Field("myF... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
return doSharding(availableTargetNames, Range.singleton(sh... | @Test
void assertLowerHalfRangeDoSharding() {
Collection<String> actual = shardingAlgorithmByQuarter.doSharding(availableTablesForQuarterDataSources,
new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.atLeast("2018-10-15 10:59:08")));
assertThat(actual.size(), i... |
@Override
public KeyValue<Bytes, byte[]> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return currentIterator.next();
} | @Test
public void shouldThrowNoSuchElementOnNextIfNoNext() {
iterator = new SegmentIterator<>(
Arrays.asList(segmentOne, segmentTwo).iterator(),
hasNextCondition,
Bytes.wrap("f".getBytes()),
Bytes.wrap("h".getBytes()),
true);
assertThrows(... |
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smpp... | @Test
public void createSmppMessageFromDeliveryReceiptShouldReturnASmppMessage() throws Exception {
DeliverSm deliverSm = new DeliverSm();
deliverSm.setSmscDeliveryReceipt();
deliverSm.setShortMessage(
"id:2 sub:001 dlvrd:001 submit date:0908312310 done date:0908312311 stat:D... |
@Override
public void run() {
final Instant now = time.get();
try {
final Collection<PersistentQueryMetadata> queries = engine.getPersistentQueries();
final Optional<Double> saturation = queries.stream()
.collect(Collectors.groupingBy(PersistentQueryMetadata::getQueryApplicationId))
... | @Test
public void shouldIgnoreSamplesOutsideMargin() {
// Given:
final Instant start = Instant.now();
when(clock.get()).thenReturn(start);
givenMetrics(kafkaStreams1)
.withThreadStartTime("t1", start.minus(WINDOW.multipliedBy(2)))
.withBlockedTime("t1", Duration.ofMinutes(2));
coll... |
public SubscriptionGroupConfig getSubscriptionGroupConfig(final String brokerAddr, String group,
long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
GetSubscriptionGroupConfigRequestHeader header =... | @Test
public void assertGetAllSubscriptionGroupForSubscriptionGroupConfig() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
SubscriptionGroupConfig responseBody = new SubscriptionGroupConfig();
responseBody.setGroupName(group);
responseBody.setBr... |
@Override
public Map<String, String> loadNamespaceMetadata(Namespace namespace)
throws NoSuchNamespaceException {
if (!namespaceExists(namespace)) {
throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace);
}
Map<String, String> properties = Maps.newHashMap();
propert... | @Test
public void testLoadNamespaceMeta() {
TableIdentifier tbl1 = TableIdentifier.of("db", "ns1", "ns2", "metadata");
TableIdentifier tbl2 = TableIdentifier.of("db", "ns2", "ns3", "tbl2");
TableIdentifier tbl3 = TableIdentifier.of("db", "ns3", "tbl4");
TableIdentifier tbl4 = TableIdentifier.of("db", ... |
public static <T> void swapTo(List<T> list, T element, Integer targetIndex) {
if (CollUtil.isNotEmpty(list)) {
final int index = list.indexOf(element);
if (index >= 0) {
Collections.swap(list, index, targetIndex);
}
}
} | @Test
public void swapIndex() {
final List<Integer> list = Arrays.asList(7, 2, 8, 9);
ListUtil.swapTo(list, 8, 1);
assertEquals(8, (int) list.get(1));
} |
@Override
public boolean tableExists(String dbName, String tblName) {
return hmsOps.tableExists(dbName, tblName);
} | @Test
public void testTableExists() {
boolean exists = hudiMetadata.tableExists("db1", "table1");
Assert.assertTrue(exists);
} |
@Override
public double d(double[] x, double[] y) {
return cor.applyAsDouble(x, y);
} | @Test
public void testDistance() {
System.out.println("distance");
double[] x = {1.0, 2.0, 3.0, 4.0};
double[] y = {4.0, 3.0, 2.0, 1.0};
double[] z = {4.0, 2.0, 3.0, 1.0};
double[] w = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
double[] v = {-1.7781... |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnInconsistentMethodWithTooManyCallbackParams() {
@RestLiCollection(name = "tooManyCallbacks")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord>
{
@Action(name = "tooManyCallbacks")
public void too... |
@Override
public boolean expireEntryIfNotSet(K key, Duration ttl) {
return get(expireEntryIfNotSetAsync(key, ttl));
} | @Test
public void testExpireEntryIfNotSet() {
RMapCacheNative<String, String> testMap = redisson.getMapCacheNative("map");
testMap.put("key", "value");
testMap.expireEntryIfNotSet("key", Duration.ofMillis(20000));
assertThat(testMap.remainTimeToLive("key")).isBetween(19800L, 20000L);... |
public void pushWithCallback(String connectionId, ServerRequest request, PushCallBack requestCallBack,
Executor executor) {
Connection connection = connectionManager.getConnection(connectionId);
if (connection != null) {
try {
connection.asyncRequest(request, new ... | @Test
void testPushWithCallback() {
try {
Mockito.when(connectionManager.getConnection(Mockito.any())).thenReturn(null);
rpcPushService.pushWithCallback(connectId, null, new PushCallBack() {
@Override
public long getTimeout() {
retu... |
public String toJson()
{
return JsonCodec.jsonCodec(DruidIngestTask.class).toJson(this);
} | @Test
public void testDruidIngestTaskToJson()
{
DruidIngestTask ingestTask = new DruidIngestTask.Builder()
.withDataSource("test_table_name")
.withInputSource(new Path("file://test_path"), Collections.emptyList())
.withTimestampColumn("__time")
... |
public void set(int index, Object val) {
values[index] = val;
} | @Test
public void testSerialization() {
HeapRow original = new HeapRow(2);
original.set(0, 1);
original.set(1, new SqlCustomClass(1));
HeapRow restored = serializeAndCheck(original, JetSqlSerializerHook.ROW_HEAP);
checkEquals(original, restored, true);
} |
public static long parseTimeoutMs(Property property, String value) {
long l = Long.parseLong(value);
checkState(l >= 1, "value of %s must be >= 1", property);
return l;
} | @Test
public void parseTimeoutMs_throws_ISE_if_value_is_0() {
assertThatThrownBy(() -> parseTimeoutMs(ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT, 0 + ""))
.isInstanceOf(IllegalStateException.class)
.hasMessage("value of WEB_GRACEFUL_STOP_TIMEOUT must be >= 1");
} |
@Override
public void stdOutput(String line) {
consumer.stdOutput(cropLongLine(line));
} | @Test
public void shouldNotCropShortLines() {
InMemoryStreamConsumer actualConsumer = ProcessOutputStreamConsumer.inMemoryConsumer();
BoundedOutputStreamConsumer streamConsumer = new BoundedOutputStreamConsumer(actualConsumer, 30);
streamConsumer.stdOutput("A short line");
assertTh... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void power2() {
String inputExpression = "(y * 5) ** 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix).isInstanceOf(InfixOpNode.class);
assertThat( infix.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertThat( ... |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
if (isGrayImage(image))
{
return createFromGrayImage(image, document);
}
// We try to encode the image with predictor
if (USE_PREDICTOR_ENCODER... | @Test
void testCreateLosslessFromImageRGB() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));
PDImageXObject ximage1 = LosslessFactory.createFromImage(document, image);
validate(ximage... |
public String[] getSupportedExtensions() {
return new String[] { "ktr", "xml" };
} | @Test
public void testGetSupportedExtensions() throws Exception {
String[] extensions = transFileListener.getSupportedExtensions();
assertNotNull( extensions );
assertEquals( 2, extensions.length );
assertEquals( "ktr", extensions[0] );
assertEquals( "xml", extensions[1] );
} |
@Override
public Result detect(ChannelBuffer in) {
int prefaceLen = Preface.readableBytes();
int bytesRead = min(in.readableBytes(), prefaceLen);
if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, Preface, bytesRead)) {
return Result.UNRECOGNIZED;
}
if (bytes... | @Test
void testDetect_NeedMoreData() {
DubboDetector detector = new DubboDetector();
ChannelBuffer in = ChannelBuffers.wrappedBuffer(new byte[] {(byte) 0xda});
assertEquals(DubboDetector.Result.NEED_MORE_DATA, detector.detect(in));
} |
public static long getTileIndex(final int pZoom, final int pX, final int pY) {
checkValues(pZoom, pX, pY);
return (((long) pZoom) << (mMaxZoomLevel * 2))
+ (((long) pX) << mMaxZoomLevel)
+ (long) pY;
} | @Test
public void testIndex() {
final int iterations = 1000;
for (int i = 0; i < iterations; i++) {
final int zoom = getRandomZoom();
final int x = getRandomXY(zoom);
final int y = getRandomXY(zoom);
final long index = MapTileIndex.getTileIndex(zoom, x... |
public Schema getSchema() {
return context.getSchema();
} | @Test
public void testWktMessageSchema() {
ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(WktMessage.getDescriptor());
Schema schema = schemaProvider.getSchema();
assertEquals(WKT_MESSAGE_SCHEMA, schema);
} |
@Override
protected Map<String, Object> getBeans(final ApplicationContext context) {
// Filter out is not controller out
if (Boolean.TRUE.equals(isFull)) {
LOG.info("init spring websocket client success with isFull mode");
publisher.publishEvent(buildURIRegisterDTO(context, C... | @Test
public void testGetBeans() {
Map<String, Object> beans = eventListener.getBeans(applicationContext);
assertNotNull(beans);
verify(publisher, never()).publishEvent(any());
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
if(containerService.isContainer(file)) {
final Storage.Buckets.Get request ... | @Test(expected = NotfoundException.class)
public void testDeleted() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new GoogleStorageTouchFeature(session).touch(new Path(container, new AlphanumericRandomStr... |
public static ScanReport fromJson(String json) {
return JsonUtil.parse(json, ScanReportParser::fromJson);
} | @Test
public void extraFields() {
ScanMetrics scanMetrics = ScanMetrics.of(new DefaultMetricsContext());
scanMetrics.totalPlanningDuration().record(10, TimeUnit.MINUTES);
scanMetrics.resultDataFiles().increment(5L);
scanMetrics.resultDeleteFiles().increment(5L);
scanMetrics.scannedDataManifests().... |
@Override
public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets,
ListOffsetsOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future =
ListOffsetsHandler.newFuture(topicParti... | @Test
public void testListOffsetsPartialResponse() throws Exception {
Node node0 = new Node(0, "localhost", 8120);
Node node1 = new Node(1, "localhost", 8121);
List<Node> nodes = asList(node0, node1);
List<PartitionInfo> pInfos = new ArrayList<>();
pInfos.add(new PartitionInf... |
public Matrix getStateTransitionProbabilities() {
return a;
} | @Test
public void testGetStateTransitionProbabilities() {
System.out.println("getStateTransitionProbabilities");
HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b));
Matrix result = hmm.getStateTransitionProbabilities();
for (int i = 0; i < a.length; i++) {
for (int j = 0; ... |
private void clear() {
garbageCollectionTypeForwardReference = null;
gcCauseForwardReference = GCCause.UNKNOWN_GCCAUSE;
fullGCTimeStamp = null;
scavengeTimeStamp = null;
youngMemoryPoolSummaryForwardReference = null;
tenuredForwardReference = null;
heapForwardRefe... | @Test
public void testThat2CMFDoNotHappen() {
String[][] lines = new String[][]{
{
"57721.729: [GC [1 CMS-initial-mark: 763361K(786432K)] 767767K(1022400K), 0.0022735 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]",
"57721.732: [CMS-concurre... |
@Override
public AppendFiles appendManifest(ManifestFile manifest) {
Preconditions.checkArgument(
!manifest.hasExistingFiles(), "Cannot append manifest with existing files");
Preconditions.checkArgument(
!manifest.hasDeletedFiles(), "Cannot append manifest with deleted files");
Preconditio... | @TestTemplate
public void testMergedAppendManifestCleanupWithSnapshotIdInheritance() throws IOException {
table.updateProperties().set(TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED, "true").commit();
assertThat(listManifestFiles()).isEmpty();
assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0)... |
@Nonnull
public static Number and(@Nonnull Number first, @Nonnull Number second) {
// Check for widest types first, go down the type list to narrower types until reaching int.
if (second instanceof Long || first instanceof Long) {
return first.longValue() & second.longValue();
} else {
return first.intValu... | @Test
void testAnd() {
assertEquals(0b00100, NumberUtil.and(0b11100, 0b00111));
assertEquals(0b00100L, NumberUtil.and(0b11100, 0b00111L));
} |
public static short translateBucketAcl(GSAccessControlList acl, String userId) {
short mode = (short) 0;
for (GrantAndPermission gp : acl.getGrantAndPermissions()) {
Permission perm = gp.getPermission();
GranteeInterface grantee = gp.getGrantee();
if (perm.equals(Permission.PERMISSION_READ)) {... | @Test
public void translateEveryoneWritePermission() {
GroupGrantee allUsersGrantee = GroupGrantee.ALL_USERS;
mAcl.grantPermission(allUsersGrantee, Permission.PERMISSION_WRITE);
assertEquals((short) 0200, GCSUtils.translateBucketAcl(mAcl, ID));
assertEquals((short) 0200, GCSUtils.translateBucketAcl(mA... |
public boolean matches(@Nullable final String hostOrIp) {
if (pattern == null) {
LOG.debug("No proxy host pattern defined");
return false;
}
if (isNullOrEmpty(hostOrIp)) {
LOG.debug("Host or IP address <{}> doesn't match <{}>", hostOrIp, noProxyHosts);
... | @Test
public void matches() {
assertPattern(null, "127.0.0.1").isFalse();
assertPattern("", "127.0.0.1").isFalse();
assertPattern(",,", "127.0.0.1").isFalse();
assertPattern("127.0.0.1", "127.0.0.1").isTrue();
assertPattern("127.0.0.1", "127.0.0.2").isFalse();
assert... |
@Override
public void start() {
this.executorService.scheduleAtFixedRate(this::tryBroadcastEvents, getInitialDelay(), getPeriod(), TimeUnit.SECONDS);
} | @Test
public void scheduler_should_be_resilient_to_failures() {
when(clientsRegistry.getClients()).thenThrow(new RuntimeException("I have a bad feelings about this"));
var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config);
underTest.start();
... |
void reset() {
int count = 0;
for (int i = 0; i < table.length; i++) {
count += Long.bitCount(table[i] & ONE_MASK);
table[i] = (table[i] >>> 1) & RESET_MASK;
}
size = (size - (count >>> 2)) >>> 1;
} | @Test
public void reset() {
boolean reset = false;
var sketch = new FrequencySketch<Integer>();
sketch.ensureCapacity(64);
for (int i = 1; i < 20 * sketch.table.length; i++) {
sketch.increment(i);
if (sketch.size != i) {
reset = true;
break;
}
}
assertThat(re... |
public Encoding getEncoding() {
return encoding;
} | @Test
public void testNonAsciiEncoding() {
MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
String testString = "こんにちは"; // Non-ASCII string
MetaString encodedMetaString = encoder.encode(testString);
assertEquals(encodedMetaString.getEncoding(), MetaString.Encoding.UTF_8);
} |
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) );
}
... | @Test
public void testGetLegacyColumnNameDriverGreaterThanThreeFieldFirstName() throws Exception {
DatabaseMetaData databaseMetaData = mock( DatabaseMetaData.class );
doReturn( 5 ).when( databaseMetaData ).getDriverMajorVersion();
assertEquals( "FIRST_NAME", new MySQLDatabaseMeta().getLegacyColumnName( d... |
private DbProviderConfig() {
this(CONFIG_NAME);
} | @Test
public void testDbProviderConfig() {
} |
public COM verifyCom(byte[] data, Class<? extends COM> type) throws RdaException {
final COM com = read(data, type);
if (!com.getDataGroups().containsAll(com.getRdaDataGroups())) {
throw new RdaException(
RdaError.COM, String.format("Not all data groups are available: %s"... | @Test
public void shouldThrowErrorIfBasicDataGroupsAreMissingFromDrivingLicence() throws Exception {
final CardVerifier verifier = verifier(null, null);
final byte[] com = readFixture("dl2/efCom");
com[1] -= 2;
com[8] -= 2;
Exception exception = assertThrows(RdaException.clas... |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateComparisons_bytes() {
// Given:
final Expression expression1 = new ComparisonExpression(
ComparisonExpression.Type.GREATER_THAN,
BYTESCOL,
new BytesLiteral(ByteBuffer.wrap(new byte[] {123}))
);
final Expression expression2 = new ComparisonExpress... |
@Override
public Optional<String> validate(String password) {
return password.matches(DIGIT_REGEX)
? Optional.empty()
: Optional.of(DIGIT_REASONING);
} | @Test
public void testValidateFailure() {
Optional<String> result = digitValidator.validate("Password");
Assert.assertTrue(result.isPresent());
Assert.assertEquals(result.get(), "must contain at least one digit between 0 and 9");
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetcherMetricsTemplates() {
Map<String, String> clientTags = Collections.singletonMap("client-id", "clientA");
buildFetcher(new MetricConfig().tags(clientTags), OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_V... |
private static String getHost(String contMgrAddress) {
String host = contMgrAddress;
String[] hostport = host.split(":");
if (hostport.length == 2) {
host = hostport[0];
}
return host;
} | @Test
public void testBlackListedNodesWithSchedulingToThatNode() throws Exception {
LOG.info("Running testBlackListedNodesWithSchedulingToThatNode");
Configuration conf = new Configuration();
conf.setBoolean(MRJobConfig.MR_AM_JOB_NODE_BLACKLISTING_ENABLE, true);
conf.setInt(MRJobConfig.MAX_TASK_FAILU... |
@Override
public Iterable<K> get() {
return StateFetchingIterators.readAllAndDecodeStartingFrom(
cache, beamFnStateClient, keysRequest, keyCoder);
} | @Test
public void testGet() throws Exception {
FakeBeamFnStateClient fakeBeamFnStateClient =
new FakeBeamFnStateClient(
ImmutableMap.of(
keysStateKey(), KV.of(ByteArrayCoder.of(), asList(A, B)),
key(A), KV.of(StringUtf8Coder.of(), asList("A1", "A2", "A3")),
... |
public static void unloadAll() {
InnerEnhancedServiceLoader.removeAllServiceLoader();
} | @Test
public void testUnloadAll() throws NoSuchFieldException, IllegalAccessException {
Hello hello = EnhancedServiceLoader.load(Hello.class);
assertThat(hello).isInstanceOf(Hello.class);
Hello2 hello2 = EnhancedServiceLoader.load(Hello2.class, "JapaneseHello", new Object[]{"msg"});
... |
StringBuilder codeForScalarFieldExtraction(Descriptors.FieldDescriptor desc, String fieldNameInCode, int indent) {
StringBuilder code = new StringBuilder();
if (desc.isRepeated()) {
code.append(addIndent(String.format("if (msg.%s() > 0) {", getCountMethodName(fieldNameInCode)), indent));
code.append... | @Test
public void testCodeForScalarFieldExtraction() {
MessageCodeGen messageCodeGen = new MessageCodeGen();
// Simple field
Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(STRING_FIELD);
String fieldNameInCode = ProtobufInternalUtils.und... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testDowngradeWithAllVersions(VertxTestContext context) {
String oldKafkaVersion = KafkaVersionTestUtils.LATEST_KAFKA_VERSION;
String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.PREVIOUS_PROTOCOL_VERSION;
String oldLogMessageFormatVersion = KafkaVersionTestUtils.PR... |
@Override
public void abort(long checkpointId, Throwable cause, boolean cleanup) {
LOG.debug("{} aborting, checkpoint {}", taskName, checkpointId);
enqueue(
ChannelStateWriteRequest.abort(jobVertexID, subtaskIndex, checkpointId, cause),
true); // abort already started... | @Test
void testAbort() throws Exception {
NetworkBuffer buffer = getBuffer();
executeCallbackWithSyncWorker(
(writer, worker) -> {
callStart(writer);
ChannelStateWriteResult result = writer.getAndRemoveWriteResult(CHECKPOINT_ID);
... |
@Override
public LispLcafAddress mapMappingAddress(ExtensionMappingAddress mappingAddress) {
ExtensionMappingAddressType type = mappingAddress.type();
if (type.equals(LIST_ADDRESS.type())) {
LispListAddress listAddress = (LispListAddress) mappingAddress;
LispAfiAddress ipv4... | @Test
public void testMapMappingAddress() {
new EqualsTester()
.addEqualityGroup(listLcafAddress, interpreter.mapMappingAddress(listExtAddress))
.addEqualityGroup(segmentLcafAddress, interpreter.mapMappingAddress(segmentExtAddress))
.addEqualityGroup(asLcafAd... |
public JWTValidator validateAlgorithm() throws ValidateException {
return validateAlgorithm(null);
} | @Test
public void validateAlgorithmTest() {
final String token = JWT.create()
.setNotBefore(DateUtil.date())
.setKey("123456".getBytes())
.sign();
// 验证算法
JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256("123456".getBytes()));
} |
@Override
public void handleSavepointCreation(
CompletedCheckpoint completedSavepoint, Throwable throwable) {
if (throwable != null) {
checkArgument(
completedSavepoint == null,
"No savepoint should be provided if a throwable is passed.");
... | @Test
void testSavepointCreationParameterBothNull() {
assertThatThrownBy(
() ->
createTestInstanceFailingOnGlobalFailOver()
.handleSavepointCreation(null, null))
.isInstanceOf(NullPointerException... |
public static <T> T convert(Class<T> type, Object value) throws ConvertException {
return convert((Type) type, value);
} | @Test
public void toHashtableTest() {
final Map<String, String> map = MapUtil.newHashMap();
map.put("a1", "v1");
map.put("a2", "v2");
map.put("a3", "v3");
@SuppressWarnings("unchecked") final Hashtable<String, String> hashtable = Convert.convert(Hashtable.class, map);
assertEquals("v1", hashtable.get("a1"... |
public PGReplicationStream createReplicationStream(final Connection connection, final String slotName, final BaseLogSequenceNumber startPosition) throws SQLException {
return connection.unwrap(PGConnection.class).getReplicationAPI()
.replicationStream()
.logical()
... | @Test
void assertCreateReplicationStreamFailure() throws SQLException {
when(connection.unwrap(PGConnection.class)).thenThrow(new SQLException(""));
assertThrows(SQLException.class, () -> logicalReplication.createReplicationStream(connection, "", new PostgreSQLLogSequenceNumber(LogSequenceNumber.val... |
@Override
public Runner get() {
return runners.get();
} | @Test
void should_create_a_runner_per_thread() throws InterruptedException {
final Runner[] runners = new Runner[2];
Thread thread0 = new Thread(() -> runners[0] = runnerSupplier.get());
Thread thread1 = new Thread(() -> runners[1] = runnerSupplier.get());
thread0.start();
... |
public boolean compatibleVersion(String acceptableVersionRange, String actualVersion) {
V pluginVersion = parseVersion(actualVersion);
// Treat a single version "1.4" as a left bound, equivalent to "[1.4,)"
if (acceptableVersionRange.matches(VERSION_REGEX)) {
return ge(pluginVersion, parseVersion(acc... | @Test
public void testRange_rightOpen_exact() {
Assert.assertFalse(checker.compatibleVersion("[2.3,4.3)", "4.3"));
Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "4.3"));
Assert.assertFalse(checker.compatibleVersion("[,4.3)", "4.3"));
Assert.assertFalse(checker.compatibleVersion("(,4.3)", "... |
public static String encode(Event event) {
String methodSignature = buildMethodSignature(event.getName(), event.getParameters());
return buildEventSignature(methodSignature);
} | @Test
public void testEncode() {
Event event =
new Event(
"Notify",
Arrays.<TypeReference<?>>asList(
new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));
assertEquals(
Even... |
List<Set<UiNode>> splitByLayer(List<String> layerTags,
Set<? extends UiNode> nodes) {
final int nLayers = layerTags.size();
if (!layerTags.get(nLayers - 1).equals(LAYER_DEFAULT)) {
throw new IllegalArgumentException(E_DEF_NOT_LAST);
}
List<... | @Test
public void threeLayers() {
title("threeLayers()");
List<Set<UiNode>> result = t2.splitByLayer(ALL_TAGS, NODES);
print(result);
assertEquals("wrong split size", 3, result.size());
Set<UiNode> opt = result.get(0);
Set<UiNode> pkt = result.get(1);
Set<Ui... |
@Override
public String getName() {
return "CircleCI";
} | @Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("CircleCI");
} |
@Override
protected ReadableByteChannel open(LocalResourceId resourceId) throws IOException {
LOG.debug("opening file {}", resourceId);
@SuppressWarnings("resource") // The caller is responsible for closing the channel.
FileInputStream inputStream = new FileInputStream(resourceId.getPath().toFile());
... | @Test
public void testReadWithExistingFile() throws Exception {
String expected = "my test string";
File existingFile = temporaryFolder.newFile();
Files.asCharSink(existingFile, StandardCharsets.UTF_8).write(expected);
String data;
try (Reader reader =
Channels.newReader(
local... |
public static IntervalSet intersect(List<IntervalSet> intervalSets) {
if (intervalSets.isEmpty()) {
return IntervalSet.NEVER;
}
if (intervalSets.size() == 1) {
return intervalSets.get(0);
}
// at least 2 lists of intervals
IntervalSet intersection = intervalSets.get(0);
// scan... | @Test
public void intersect() {
IntervalSet s1;
IntervalSet s2;
Set<Interval> s;
s1 = new IntervalSet(Arrays.asList(Interval.between(1, 3), Interval.between(11, 13)));
s = Sets.newHashSet(
IntervalUtils.intersect(Arrays.asList(s1, IntervalSet.NEVER)).getIntervals());
Assert.assertEqua... |
public static ScmInfo create(ScannerReport.Changesets changesets) {
requireNonNull(changesets);
Changeset[] lineChangesets = new Changeset[changesets.getChangesetIndexByLineCount()];
LineIndexToChangeset lineIndexToChangeset = new LineIndexToChangeset(changesets);
for (int i = 0; i < changesets.getChan... | @Test
public void return_changeset_for_a_given_line() {
ScmInfo scmInfo = ReportScmInfo.create(ScannerReport.Changesets.newBuilder()
.setComponentRef(FILE_REF)
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
.setDate(123456789L)
.setRevision("re... |
public static void trim(String[] strs) {
if (null == strs) {
return;
}
String str;
for (int i = 0; i < strs.length; i++) {
str = strs[i];
if (null != str) {
strs[i] = trim(str);
}
}
} | @Test
public void trimNewLineTest() {
String str = "\r\naaa";
assertEquals("aaa", StrUtil.trim(str));
str = "\raaa";
assertEquals("aaa", StrUtil.trim(str));
str = "\naaa";
assertEquals("aaa", StrUtil.trim(str));
str = "\r\n\r\naaa";
assertEquals("aaa", StrUtil.trim(str));
} |
public static boolean isValidRootUrl(String url) {
UrlValidator validator = new CustomUrlValidator();
return validator.isValid(url);
} | @Test
@Issue("JENKINS-31661")
public void regularCases() {
assertTrue(UrlHelper.isValidRootUrl("http://www.google.com"));
// trailing slash is optional
assertTrue(UrlHelper.isValidRootUrl("http://www.google.com/"));
// path is allowed
assertTrue(UrlHelper.isValidRootUrl("... |
public static UserOperatorConfig buildFromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(UserOperatorConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return new UserOperatorC... | @Test
public void testInvalidOperationTimeout() {
Map<String, String> envVars = new HashMap<>(UserOperatorConfigTest.ENV_VARS);
envVars.put(UserOperatorConfig.OPERATION_TIMEOUT_MS.key(), "abcdefg");
assertThrows(InvalidConfigurationException.class, () -> UserOperatorConfig.buildFromMap(e... |
public static String substVars(String val, PropertyContainer pc1) throws ScanException {
return substVars(val, pc1, null);
} | @Test
public void testSubstVarsVariableNotClosed() throws ScanException {
String noSubst = "testing if ${v1 works";
try {
@SuppressWarnings("unused")
String result = OptionHelper.substVars(noSubst, context);
fail();
} catch (IllegalArgumentException e) {
... |
@Override
public String getSessionId() {
return sessionID;
} | @Test
public void testGetRequest() {
log.info("Starting get async");
assertNotNull("Incorrect sessionId", session1.getSessionId());
try {
assertTrue("NETCONF get running command failed. ",
GET_REPLY_PATTERN.matcher(session1.get(SAMPLE_REQUEST, null)).matches()... |
@Override
public TaskAttemptID acquireTaskAttemptIdLock(Configuration conf, int taskId) {
String jobJtIdentifier = getJobJtIdentifier(conf);
JobID jobId = HadoopFormats.getJobId(conf);
int taskAttemptCandidate = 0;
boolean taskAttemptAcquired = false;
while (!taskAttemptAcquired) {
taskAtte... | @Test
public void testTaskAttemptIdAcquire() {
int tasksCount = 100;
int taskId = 25;
for (int i = 0; i < tasksCount; i++) {
TaskAttemptID taskAttemptID = tested.acquireTaskAttemptIdLock(configuration, taskId);
assertTrue(isFileExists(getTaskAttemptIdPath(taskId, taskAttemptID.getId())));
... |
public String getString(HazelcastProperty property) {
String value = properties.getProperty(property.getName());
if (value != null) {
return value;
}
value = property.getSystemProperty();
if (value != null) {
return value;
}
HazelcastProp... | @Test
public void setProperty_ensureUsageOfSystemProperty() {
ENTERPRISE_LICENSE_KEY.setSystemProperty("systemValue");
HazelcastProperties hazelcastProperties = new HazelcastProperties(config);
String value = hazelcastProperties.getString(ENTERPRISE_LICENSE_KEY);
System.clearProper... |
private ContentType getContentType(Exchange exchange) throws ParseException {
String contentTypeStr = ExchangeHelper.getContentType(exchange);
if (contentTypeStr == null) {
contentTypeStr = DEFAULT_CONTENT_TYPE;
}
ContentType contentType = new ContentType(contentTypeStr);
... | @Test
@Disabled("Fails on CI servers and some platforms - maybe due locale or something")
public void roundtripWithTextAttachmentsAndSpecialCharacters() throws IOException {
String attContentType = "text/plain";
String attText = "Attachment Text with special characters: \u00A9";
String a... |
public static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName)
throws Exception {
ClusterInfo clusterInfoSerializeWrapper = adminExt.examineBrokerClusterInfo();
Set<String> brokerNameSet = clusterInfoSerializeWrapper.getClusterAddrTable().get(clusterN... | @Test
public void testFetchBrokerNameByClusterName() throws Exception {
Set<String> result = CommandUtil.fetchBrokerNameByClusterName(defaultMQAdminExtImpl, "default-cluster");
assertThat(result.contains("default-broker")).isTrue();
assertThat(result.contains("default-broker-one")).isTrue();... |
public CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageAsync(String topic, long offset, int queueId, String brokerName, boolean deCompressBody) {
MessageStore messageStore = brokerController.getMessageStoreByBrokerName(brokerName);
if (messageStore != null) {
return messageS... | @Test
public void getMessageAsyncTest_localStore_message_found() throws Exception {
when(brokerController.getMessageStoreByBrokerName(any())).thenReturn(defaultMessageStore);
when(defaultMessageStore.getMessageAsync(anyString(), anyString(), anyInt(), anyLong(), anyInt(), any()))
.th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.