focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static String formatPercent(double value) {
DecimalFormat percentFormatter = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
return percentFormatter.format(value) + "%";
} | @Test
public void format_percent() {
assertThat(formatPercent(0d)).isEqualTo("0%");
assertThat(formatPercent(12.345)).isEqualTo("12.3%");
assertThat(formatPercent(12.56)).isEqualTo("12.6%");
} |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void readOutOfBoundByteBuffer() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE);
ByteBuffer buffer = ByteBuffer.allocate(CHUNK_SIZE * 2);
try (FileInStream inStream = getStream(ufsPath)) {
assertEquals(CHUNK_SIZE, inStream.re... |
@Override
void onFailure(Throwable cause, CompletableFuture<Map<String, String>> failureLabels) {
if (hasPendingStateTransition) {
// the error handling remains the same independent of how many tasks have failed
// we don't want to initiate the same state transition multiple times, s... | @Test
void testConcurrentSavepointFailureAndGloballyTerminalStateCauseRestart() throws Exception {
try (MockStopWithSavepointContext ctx = new MockStopWithSavepointContext()) {
CheckpointScheduling mockStopWithSavepointOperations = new MockCheckpointScheduling();
CompletableFuture<St... |
@Override
public void trackEvent(InputData input) {
process(input);
} | @Test
public void trackEventH5() {
initSensors();
SensorsDataAPI.sharedInstance().setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
assertEquals("$WebClick", eventN... |
public static <T, S> T copy(S source, T target, String... ignore) {
return copy(source, target, DEFAULT_CONVERT, ignore);
} | @Test
public void testProxy() {
AtomicReference<Object> reference = new AtomicReference<>();
ProxyTest test = (ProxyTest) Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(),
new Class[]{ProxyTest.class}, (proxy, method, args) -> {
... |
static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options)
throws FormatterException {
Context context = new Context();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
context.put(DiagnosticListener.class, diagnostics);
Options... | @Test
public void testFormatOffsetOutOfRange() throws Exception {
String input = "class Foo{}\n";
Path tmpdir = testFolder.newFolder().toPath();
Path path = tmpdir.resolve("Foo.java");
Files.writeString(path, input);
StringWriter out = new StringWriter();
StringWriter err = new StringWriter(... |
public boolean isCurrentOSValidForThisPlugin(String currentOS) {
if (about == null || about.targetOperatingSystems.isEmpty()) {
return true;
}
for (String targetOperatingSystem : about.targetOperatingSystems) {
if (targetOperatingSystem.equalsIgnoreCase(currentOS)) {
... | @Test
void shouldDoACaseInsensitiveMatchForValidOSesAgainstCurrentOS() {
assertThat(descriptorWithTargetOSes("linux").isCurrentOSValidForThisPlugin("Linux")).isTrue();
assertThat(descriptorWithTargetOSes("LiNuX").isCurrentOSValidForThisPlugin("Linux")).isTrue();
assertThat(descriptorWithTarg... |
public static String getKeyTenant(String dataId, String group, String tenant) {
return doGetKey(dataId, group, tenant);
} | @Test
public void getKeyTenant() {
String dataId = "dataId";
String group = "group";
String datumStr = "datumStr";
String expected = "dataId+group+datumStr";
String keyTenant = GroupKey.getKeyTenant(dataId, group, datumStr);
Assert.isTrue(keyTenant.equals(expected));... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_map_with_null_value() {
Map<String, Object> original = new HashMap<>();
original.put("null", null);
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
} |
public static String nullToEmpty( String source ) {
if ( source == null ) {
return EMPTY_STRING;
}
return source;
} | @Test
public void testNullToEmpty() {
assertEquals( "", Const.nullToEmpty( null ) );
assertEquals( "value", Const.nullToEmpty( "value" ) );
} |
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(PushNotification pushNotification) {
Message.Builder builder = Message.builder()
.setToken(pushNotification.deviceToken())
.setAndroidConfig(AndroidConfig.builder()
.setPriority(pushNotification.urgent() ? ... | @Test
void testSendMessageUnregistered() {
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true);
final FirebaseMessagingException unregisteredException = mock(FirebaseMessagingException.cl... |
public static <T, R> CheckedFunction0<R> andThen(CheckedFunction0<T> function,
CheckedFunction2<T, Throwable, R> handler) {
return () -> {
try {
return handler.apply(function.apply(), null);
} catch (Throwable throwable) {
return handler.apply(null... | @Test
public void shouldRecoverFromException2() throws Throwable {
CheckedFunction0<String> callable = () -> {
throw new IllegalArgumentException("BAM!");
};
CheckedFunction0<String> callableWithRecovery = VavrCheckedFunctionUtils.andThen(callable, (result, ex) -> {
i... |
@Override
public List<Object> getAll() {
List<Object> r = new ArrayList<Object>(this.size());
for (int i = 0; i < this.size(); i++){
r.add(i, get(i));
}
return r;
} | @Test
public void testGetAll() throws Exception {
HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector());
List<Object> list = r.getAll();
Assert.assertEquals(INT_CONST, ((Integer) list.get(0)).intValue());
Assert.assertEquals(LONG_CONST, ((Long) list.get(1)).longValue());
Assert.... |
@VisibleForTesting
static Map<String, Long> getExternalResourceAmountMap(Configuration config) {
final Set<String> resourceSet = getExternalResourceSet(config);
if (resourceSet.isEmpty()) {
return Collections.emptyMap();
}
final Map<String, Long> externalResourceAmountM... | @Test
public void testGetExternalResourceAmountMapWithIllegalAmount() {
final Configuration config = new Configuration();
config.set(
ExternalResourceOptions.EXTERNAL_RESOURCE_LIST,
Collections.singletonList(RESOURCE_NAME_1));
config.setLong(
E... |
public ImmutableSortedSet<Name> snapshot() {
ImmutableSortedSet.Builder<Name> builder =
new ImmutableSortedSet.Builder<>(Name.displayOrdering());
for (DirectoryEntry entry : this) {
if (!isReserved(entry.name())) {
builder.add(entry.name());
}
}
return builder.build();
} | @Test
public void testSnapshot() {
root.link(Name.simple("bar"), regularFile(10));
root.link(Name.simple("abc"), regularFile(10));
// does not include . or .. and is sorted by the name
assertThat(root.snapshot())
.containsExactly(Name.simple("abc"), Name.simple("bar"), Name.simple("foo"))
... |
public boolean sync() throws IOException {
if (!preSyncCheck()) {
return false;
}
if (!getAllDiffs()) {
return false;
}
List<Path> sourcePaths = context.getSourcePaths();
final Path sourceDir = sourcePaths.get(0);
final Path targetDir = context.getTargetPath();
final FileSy... | @Test
public void testSync() throws Exception {
initData(source);
initData(target);
enableAndCreateFirstSnapshot();
// make changes under source
int numCreatedModified = changeData(dfs, source);
dfs.createSnapshot(source, "s2");
// before sync, make some further changes on source. this s... |
public static int doMain(String[] args) throws Exception {
Arguments arguments = new Arguments();
CommandLine commander = new CommandLine(arguments);
try {
commander.parseArgs(args);
if (arguments.help) {
commander.usage(commander.getOut());
... | @Test
public void testMainGenerateDocs() throws Exception {
PrintStream oldStream = System.out;
try {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(baoStream));
Class argumentsClass =
Class.forNam... |
public CardinalityEstimatorConfig setBackupCount(int backupCount) {
this.backupCount = checkBackupCount(backupCount, asyncBackupCount);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testSetBackupCount_withInvalidValue() {
config.setBackupCount(7);
} |
public static boolean isFourDigitsAsciiEncodedNumber(final int value)
{
return 0 == ((((value + 0x46464646) | (value - 0x30303030)) & 0x80808080));
} | @Test
void shouldDetectFourDigitsAsciiEncodedNumbers()
{
final int index = 2;
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[8]);
for (int i = 0; i < 1000; i++)
{
buffer.putIntAscii(index, i);
assertFalse(isFourDigitsAsciiEncodedNumber(buffer.getIn... |
@Deprecated(forRemoval = true)
public SystemInfo(ApplicationId application, Zone zone, Cluster cluster, Node node) {
this(application, zone, new Cloud(""), cluster.id(), node);
} | @Test
@SuppressWarnings("removal")
void testSystemInfo() {
ApplicationId application = new ApplicationId("tenant1", "application1", "instance1");
Zone zone = new Zone(Environment.dev, "us-west-1");
Cloud cloud = new Cloud("aws");
String cluster = "clusterName";
Node node ... |
@Override
protected void validateDataImpl(TenantId tenantId, WidgetsBundle widgetsBundle) {
validateString("Widgets bundle title", widgetsBundle.getTitle());
if (widgetsBundle.getTenantId() == null) {
widgetsBundle.setTenantId(TenantId.fromUUID(ModelConstants.NULL_UUID));
}
... | @Test
void testValidateNameInvocation() {
WidgetsBundle widgetsBundle = new WidgetsBundle();
widgetsBundle.setTitle("my fancy WB");
widgetsBundle.setTenantId(tenantId);
validator.validateDataImpl(tenantId, widgetsBundle);
verify(validator).validateString("Widgets bundle titl... |
private MsgAllocator allocator(Class<?> clazz)
{
try {
Class<? extends MsgAllocator> msgAllocator = clazz.asSubclass(MsgAllocator.class);
return msgAllocator.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgu... | @Test
public void testAllocator()
{
options.setSocketOpt(ZMQ.ZMQ_MSG_ALLOCATOR, new MsgAllocatorDirect());
assertThat(options.getSocketOpt(ZMQ.ZMQ_MSG_ALLOCATOR), is(options.allocator));
} |
public MethodBuilder onthrowMethod(String onthrowMethod) {
this.onthrowMethod = onthrowMethod;
return getThis();
} | @Test
void onthrowMethod() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.onthrowMethod("on-throw-method");
Assertions.assertEquals("on-throw-method", builder.build().getOnthrowMethod());
} |
public static Read read() {
return new Read(null, "", new Scan());
} | @Test
public void testReading() throws Exception {
final String table = tmpTable.getName();
final int numRows = 1001;
createAndWriteData(table, numRows);
runReadTestLength(HBaseIO.read().withConfiguration(conf).withTableId(table), false, numRows);
} |
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException {
final String httpSessionId = authenticationRequest.getRequest().getSession().getId();
if (authenticationRequest.getFederationName() !... | @Test
public void noValidRequesterIdIsPresentTest() throws SamlSessionException, SharedServiceClientException {
RequesterID requesterID = OpenSAMLUtils.buildSAMLObject(RequesterID.class);
requesterID.setRequesterID("requesterId");
Scoping scoping = OpenSAMLUtils.buildSAMLObject(Scoping.clas... |
@Override
public void rotate(IndexSet indexSet) {
indexRotator.rotate(indexSet, this::shouldRotate);
} | @Test
public void testRotationOnEmptyIndexSetWhenEnabled() {
final DateTime initialTime = new DateTime(2022, 7, 21, 13, 00, 00, 0, DateTimeZone.UTC);
final Period period = hours(1);
final InstantMillisProvider clock = new InstantMillisProvider(initialTime);
DateTimeUtils.setCurrentMi... |
@SneakyThrows({SystemException.class, RollbackException.class})
@Override
public void enlistResource(final SingleXAResource singleXAResource) {
transactionManager.getTransaction().enlistResource(singleXAResource.getDelegate());
} | @Test
void assertEnlistResource() throws SystemException, RollbackException {
SingleXAResource singleXAResource = mock(SingleXAResource.class);
Transaction transaction = mock(Transaction.class);
when(transactionManager.getTransaction()).thenReturn(transaction);
transactionManagerProv... |
public Map<String, String> getParams() {
return params;
} | @Test
void testRequestUrlParams() {
RequestUrl requestUrl = new MatchUrl("/api/jobs/enqueued?offset=2&limit=2").toRequestUrl("/api/jobs/:state");
assertThat(requestUrl.getParams()).containsEntry(":state", "enqueued");
} |
@Override
public String name() {
return this.name;
} | @Test
void testName() {
String name = "test";
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
builder.setName(name);
DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) builder.build();
assertEquals(name, config.name());
} |
boolean isReassignmentInProgress() {
return isReassignmentInProgress(
removing,
adding);
} | @Test
public void testIsReassignmentInProgress() {
assertTrue(PartitionReassignmentReplicas.isReassignmentInProgress(
new PartitionRegistration.Builder().
setReplicas(new int[]{0, 1, 3, 2}).
setDirectories(new Uuid[]{
Uuid.fromString("HEKOeWDdQ... |
private StringBuilder read(int n) throws IOException {
// Input stream finished?
boolean eof = false;
// Read that many.
final StringBuilder s = new StringBuilder(n);
while (s.length() < n && !eof) {
// Always get from the pushBack buffer.
if (pushBack.len... | @Test
public void testRead_3args() throws Exception {
byte[] data = new byte[10];
int offset = 0;
int length = 10;
byte[] expected = "abcdefghij".getBytes(StandardCharsets.UTF_8);
String text = "abcdefghijklmnopqrstuvwxyz";
InputStream stream = new ByteArrayInputStrea... |
@Override
public Type[] getActualTypeArguments() {
return typeArguments;
} | @Test
void getActualTypeArguments() {
List<Type> typeArguments = Arrays.asList(String.class, Boolean.class, Long.class);
EfestoClassKey keyListWithTypes = new EfestoClassKey(List.class, typeArguments.toArray(new Type[0]));
Type[] retrieved = keyListWithTypes.getActualTypeArguments();
... |
@Override
public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) {
return isArrayType(type);
} | @Test
void testAccept() {
assertTrue(builder.accept(processingEnv, integersField.asType()));
assertTrue(builder.accept(processingEnv, stringsField.asType()));
assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType()));
assertTrue(builder.accept(processingEnv, models... |
public SubscriptionName createSubscription(TopicName topicName, String subscriptionName) {
checkArgument(!subscriptionName.isEmpty(), "subscriptionName can not be empty");
checkIsUsable();
if (!createdTopics.contains(topicName)) {
throw new IllegalArgumentException(
"Can not create a subscr... | @Test
public void testCreateSubscriptionWithInvalidNameShouldFail() {
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class,
() -> testManager.createSubscription(TopicName.of(PROJECT_ID, "topic-a"), ""));
assertThat(exception).hasMessageThat().contai... |
@Override
public void send(Object message) throws RemotingException {
send(message, false);
} | @Test
void sendTest04() throws RemotingException {
String message = "this is a test message";
header.send(message);
List<Object> objects = channel.getSentObjects();
Assertions.assertEquals(objects.get(0), "this is a test message");
} |
@Override
public void requestDeferredDeepLink(JSONObject params) {
} | @Test
public void requestDeferredDeepLink() {
mSensorsAPI.requestDeferredDeepLink(new JSONObject());
} |
@ScalarOperator(DIVIDE)
@SqlType(StandardTypes.TINYINT)
public static long divide(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right)
{
try {
return left / right;
}
catch (ArithmeticException e) {
throw new PrestoException(DI... | @Test
public void testDivide()
{
assertFunction("TINYINT'37' / TINYINT'37'", TINYINT, (byte) 1);
assertFunction("TINYINT'37' / TINYINT'17'", TINYINT, (byte) (37 / 17));
assertFunction("TINYINT'17' / TINYINT'37'", TINYINT, (byte) (17 / 37));
assertFunction("TINYINT'17' / TINYINT'1... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testStaticMemberReJoinWithIllegalStateAsUnknownMember() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
context.staticMembersJoinAndRebalance(
"group-id",
"leader-instance-id",... |
public synchronized CryptoKey getOrCreateCryptoKey(String keyRingId, String keyName) {
// Get the keyring, creating it if it does not already exist
if (keyRing == null) {
maybeCreateKeyRing(keyRingId);
}
try (KeyManagementServiceClient client = clientFactory.getKMSClient()) {
// Build the... | @Test
public void testGetOrCreateCryptoKeyShouldCreateCryptoKeyWhenItDoesNotExist() {
KeyRing keyRing =
KeyRing.newBuilder()
.setName(KeyRingName.of(PROJECT_ID, REGION, KEYRING_ID).toString())
.build();
when(kmsClientFactory.getKMSClient()).thenReturn(serviceClient);
when(s... |
public abstract boolean isEmpty() throws IOException; | @Test
public void testIsEmpty() throws Exception {
File tmpFile = tmpFolder.newFile();
List<IsmRecord<byte[]>> data = new ArrayList<>();
writeElementsToFile(data, tmpFile);
IsmReader<byte[]> reader =
new IsmReaderImpl<byte[]>(
FileSystems.matchSingleFileSpec(tmpFile.getAbsolutePat... |
@Override
public PostgreSQLPacketPayload createPacketPayload(final ByteBuf message, final Charset charset) {
return new PostgreSQLPacketPayload(message, charset);
} | @Test
void assertCreatePacketPayload() {
assertThat(new PostgreSQLPacketCodecEngine().createPacketPayload(byteBuf, StandardCharsets.UTF_8).getByteBuf(), is(byteBuf));
} |
public boolean checkStateUpdater(final long now,
final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) {
addTasksToStateUpdater();
if (stateUpdater.hasExceptionsAndFailedTasks()) {
handleExceptionsFromStateUpdater();
}
if ... | @Test
public void shouldRethrowTaskCorruptedExceptionFromStateUpdater() {
final StreamTask statefulTask0 = statefulTask(taskId00, taskId00ChangelogPartitions)
.inState(State.RESTORING)
.withInputPartitions(taskId00Partitions).build();
final StreamTask statefulTask1 = stateful... |
@Override
public void setConf(Configuration conf) {
if (conf != null) {
conf = addSecurityConfiguration(conf);
}
super.setConf(conf);
} | @Test
public void testFailoverWithForceActive() throws Exception {
Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus();
HdfsConfiguration conf = getHAConf();
conf.set(DFSConfigKeys.DFS_HA_FENCE_METHODS_KEY, getFencerTrueCommand());
tool.setConf(conf);
assertEquals(0, runTo... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testPartitionedDays() throws Exception {
createPartitionedTable(spark, tableName, "days(ts)");
SparkScanBuilder builder = scanBuilder();
DaysFunction.TimestampToDaysFunction function = new DaysFunction.TimestampToDaysFunction();
UserDefinedScalarFunc udf = toUDF(function, expressio... |
static int computeRawVarint32Size(final int value) {
if ((value & (0xffffffff << 7)) == 0) {
return 1;
}
if ((value & (0xffffffff << 14)) == 0) {
return 2;
}
if ((value & (0xffffffff << 21)) == 0) {
return 3;
}
if ((value & (0x... | @Test
public void testSize3Varint() {
final int size = 3;
final int num = 0x4000;
assertThat(ProtobufVarint32LengthFieldPrepender.computeRawVarint32Size(num), is(size));
final byte[] buf = new byte[size + num];
/**
* 8 0 8 0 0 1
* 1000 0000 10... |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeExcludingMetadataColumnsDuplicate() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.columnByMetadata("two", DataTypes.INT())
.build();
List<SqlNode> derivedColumns =
... |
public static void checkValid(boolean isValid, String argName) {
checkArgument(isValid, "'%s' is invalid.", argName);
} | @Test
public void testCheckValidWithValues() throws Exception {
String validValues = "foo, bar";
// Should not throw.
Validate.checkValid(true, "arg", validValues);
// Verify it throws.
intercept(IllegalArgumentException.class,
"'arg' is invalid. Valid values are: foo, bar",
() ... |
@Override
public void register() {
client.register();
} | @Test
public void register() {
nacosRegister.register();
Mockito.verify(client, Mockito.times(1)).register();
} |
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_NoArgConstructorNotFound() {
Map<String, String> options = Maps.newHashMap();
options.put("key", "val");
Configuration hadoopConf = new Configuration();
String name = "custom";
assertThatThrownBy(
() ->
CatalogUtil.loadCatalog(
... |
public static Map<String, ResourceModel> buildResourceModels(final Set<Class<?>> restliAnnotatedClasses)
{
Map<String, ResourceModel> rootResourceModels = new HashMap<>();
Map<Class<?>, ResourceModel> resourceModels = new HashMap<>();
for (Class<?> annotatedClass : restliAnnotatedClasses)
{
pro... | @Test
public void testProcessResource()
{
Set<Class<?>> set = new HashSet<>();
set.add(ParentResource.class);
set.add(TestResource.class);
Map<String, ResourceModel> models = RestLiApiBuilder.buildResourceModels(set);
ResourceModel parentResource = models.get("/ParentResource");
Assert.asse... |
@VisibleForTesting
List<Image> getCachedBaseImages()
throws IOException, CacheCorruptedException, BadContainerConfigurationFormatException,
LayerCountMismatchException, UnlistedPlatformInManifestListException,
PlatformNotFoundInBaseImageException {
ImageReference baseImage = buildContext... | @Test
public void testGetCachedBaseImages_manifestCached()
throws InvalidImageReferenceException, IOException, CacheCorruptedException,
UnlistedPlatformInManifestListException, BadContainerConfigurationFormatException,
LayerCountMismatchException, PlatformNotFoundInBaseImageException {
I... |
@VisibleForTesting
RoleDO validateRoleForUpdate(Long id) {
RoleDO role = roleMapper.selectById(id);
if (role == null) {
throw exception(ROLE_NOT_EXISTS);
}
// 内置角色,不允许删除
if (RoleTypeEnum.SYSTEM.getType().equals(role.getType())) {
throw exception(ROLE_C... | @Test
public void testValidateUpdateRole_roleIdNotExist() {
assertServiceException(() -> roleService.validateRoleForUpdate(randomLongId()), ROLE_NOT_EXISTS);
} |
@Override
public Timer timer(String name, TimeUnit unit) {
return new DefaultTimer(unit);
} | @Test
public void timer() {
MetricsContext metricsContext = new DefaultMetricsContext();
Timer timer = metricsContext.timer("test", TimeUnit.MICROSECONDS);
timer.record(10, TimeUnit.MINUTES);
assertThat(timer.totalDuration()).isEqualTo(Duration.ofMinutes(10L));
} |
protected final AnyKeyboardViewBase getMiniKeyboard() {
return mMiniKeyboard;
} | @Test
public void testLongPressWhenNoPrimaryKeyAndNoPopupItemsButLongPressCodeShouldOutputLongPress()
throws Exception {
ExternalAnyKeyboard anyKeyboard =
new ExternalAnyKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
... |
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFindSessions(final Bytes key,
final long earliestSessionEndTime,
final long latestSessionStartTime) {... | @Test
public void shouldDelegateToUnderlyingStoreWhenBackwardFindingSessionRange() {
store.backwardFindSessions(bytesKey, bytesKey, 0, 1);
verify(inner).backwardFindSessions(bytesKey, bytesKey, 0, 1);
} |
public MastershipInfo() {
this(0, Optional.empty(), ImmutableMap.of());
} | @Test
public void testMastershipInfo() throws Exception {
assertEquals(1, mastershipInfo.term());
assertEquals(node1, mastershipInfo.master().get());
assertEquals(Lists.newArrayList(node1), mastershipInfo.getRoles(MastershipRole.MASTER));
assertEquals(Lists.newArrayList(node2, node3)... |
@Override
public void setProperties(final Properties properties) {
} | @Test
public void setPropertiesTest() {
final OracleSQLPrepareInterceptor oracleSQLPrepareInterceptor = new OracleSQLPrepareInterceptor();
Assertions.assertDoesNotThrow(() -> oracleSQLPrepareInterceptor.setProperties(mock(Properties.class)));
} |
@Override
public Response request(Request request, long timeouts) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
Payload grpcResponse;
try {
if (timeouts <= 0)... | @Test
void testRequestSuccessSync() throws NacosException {
Response response = connection.request(new HealthCheckRequest(), -1);
assertTrue(response instanceof HealthCheckResponse);
} |
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception {
LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation);
MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con... | @Test
public void shouldNotAllowMultipleRepositoriesWithSameName() throws Exception {
Configuration packageConfiguration = new Configuration(getConfigurationProperty("name", false, "go-agent"));
Configuration repositoryConfiguration = new Configuration(getConfigurationProperty("url", false, "http://... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertRemoveInfo() throws Exception {
String connectionId = "myConnectionId";
RemoveInfo dataStructure = new RemoveInfo(new ConnectionId(connectionId));
ActiveMQMessage outbound = createMessage();
Map<String, String> properties = new HashMap<String, String>();
... |
protected JsonNode jsonLinks(List<UiSynthLink> links) {
return collateSynthLinks(links);
} | @Test
public void encodeSynthLinks() {
title("encodeSynthLinks()");
ArrayNode array = (ArrayNode) t2.jsonLinks(createSynthLinks());
print(array);
assertEquals("wrong size", 2, array.size());
ObjectNode first = (ObjectNode) array.get(0);
ObjectNode second = (ObjectNod... |
@VisibleForTesting
void removeDisableUsers(Set<Long> assigneeUserIds) {
if (CollUtil.isEmpty(assigneeUserIds)) {
return;
}
Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(assigneeUserIds);
assigneeUserIds.removeIf(id -> {
AdminUserRespDTO user = ... | @Test
public void testRemoveDisableUsers() {
// 准备参数. 1L 可以找到;2L 是禁用的;3L 找不到
Set<Long> assigneeUserIds = asSet(1L, 2L, 3L);
// mock 方法
AdminUserRespDTO user1 = randomPojo(AdminUserRespDTO.class, o -> o.setId(1L)
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
... |
@Override
public <T> T persist(T detachedObject) {
Map<Object, Object> alreadyPersisted = new HashMap<Object, Object>();
return persist(detachedObject, alreadyPersisted, RCascadeType.PERSIST);
} | @Test
public void testPersist() {
RLiveObjectService service = redisson.getLiveObjectService();
TestClass ts = new TestClass(new ObjectId(100));
ts.setValue("VALUE");
ts.setContent(new TestREntity("123"));
ts.addEntry("1", "2");
TestClass persisted = service.persist(... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final FileEntity entity = new FilesApi(new BrickApiClient(session))
.download(StringUtils.removeStart(file.getAbsolute(), String.v... | @Test
public void testReadCloseReleaseEntity() throws Exception {
final TransferStatus status = new TransferStatus();
final byte[] content = RandomUtils.nextBytes(32769);
final TransferStatus writeStatus = new TransferStatus();
writeStatus.setLength(content.length);
final Pat... |
@Override
protected void refresh() {
Iterable<ServerConfig> dbConfigs = serverConfigRepository.findAll();
Map<String, Object> newConfigs = Maps.newHashMap();
//default cluster's configs
for (ServerConfig config : dbConfigs) {
if (Objects.equals(ConfigConsts.CLUSTER_NAME_DEFAULT, config.getClust... | @Test
public void testGetNull() {
propertySource.refresh();
assertNull(propertySource.getProperty("noKey"));
} |
public static void extendActiveLock(Duration lockAtMostFor, Duration lockAtLeastFor) {
SimpleLock lock = locks().peekLast();
if (lock == null) throw new NoActiveLockException();
Optional<SimpleLock> newLock = lock.extend(lockAtMostFor, lockAtLeastFor);
if (newLock.isPresent()) {
... | @Test
void shouldFailIfLockCanNotBeExtended() {
when(lock.extend(extendBy, ZERO)).thenReturn(Optional.empty());
Runnable task = () -> LockExtender.extendActiveLock(extendBy, ZERO);
assertThatThrownBy(() -> executor.executeWithLock(task, configuration))
.isInstanceOf(LockCan... |
@SuppressWarnings("unchecked")
public DynamicDestinations<UserT, DestinationT, OutputT> getDynamicDestinations() {
return (DynamicDestinations<UserT, DestinationT, OutputT>) dynamicDestinations;
} | @Test
public void testGenerateOutputFilenamesWithoutExtension() {
List<ResourceId> expected;
List<ResourceId> actual;
ResourceId root = getBaseOutputDirectory();
SimpleSink<Void> sink =
SimpleSink.makeSimpleSink(root, "file", "-SSSSS-of-NNNNN", "", Compression.UNCOMPRESSED);
FilenamePolicy... |
public byte[] getByteArray()
{
return slice.byteArray();
} | @Test
public void testGetByteArray()
{
int numElements = 100;
Slice slice = Slices.allocate(2 * numElements);
byte[] expected = new byte[2 * numElements];
int offset = 0;
for (int i = 0; i < numElements; i++) {
String str = "" + i;
slice.setBytes(... |
@Override
protected void write(final PostgreSQLPacketPayload payload) {
payload.writeInt4(AUTH_REQ_SHA256);
payload.writeInt4(PASSWORD_STORED_METHOD_SHA256);
payload.writeBytes(authHexData.getSalt().getBytes());
payload.writeBytes(authHexData.getNonce().getBytes());
if (versi... | @Test
void assertWriteProtocol350Packet() {
PostgreSQLPacketPayload payload = mock(PostgreSQLPacketPayload.class);
OpenGaussAuthenticationSCRAMSha256Packet packet = new OpenGaussAuthenticationSCRAMSha256Packet(OpenGaussProtocolVersion.PROTOCOL_350.getVersion(), 2048, authHexData, "");
packet... |
@Override
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
int nextValue = nextValue(topic);
List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic);
if (!availablePartitions.isEmpty()) {
... | @Test
public void testRoundRobinWithUnavailablePartitions() {
// Intentionally make the partition list not in partition order to test the edge
// cases.
List<PartitionInfo> partitions = asList(
new PartitionInfo("test", 1, null, NODES, NODES),
new PartitionInf... |
@VisibleForTesting
public static boolean isDateAfterOrSame( String date1, String date2 ) {
return date2.compareTo( date1 ) >= 0;
} | @Test
public void isDateAfterOrSame_AfterTest() {
assertFalse( TransPreviewProgressDialog.isDateAfterOrSame( AFTER_DATE_STR, BEFORE_DATE_STR ) );
} |
@Override
public String dumpSchedulerLogs(String time, HttpServletRequest hsr)
throws IOException {
// Step1. We will check the time parameter to
// ensure that the time parameter is not empty and greater than 0.
if (StringUtils.isBlank(time)) {
routerMetrics.incrDumpSchedulerLogsFailedRetri... | @Test
public void testDumpSchedulerLogsError() throws Exception {
HttpServletRequest mockHsr = mockHttpServletRequestByUserName("admin");
// time is empty
LambdaTestUtils.intercept(IllegalArgumentException.class,
"Parameter error, the time is empty or null.",
() -> interceptor.dumpSchedul... |
public HeartbeatV2Result sendHeartbeatV2(
final String addr,
final HeartbeatData heartbeatData,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, new He... | @Test
public void assertSendHeartbeatV2() throws MQBrokerException, RemotingException, InterruptedException {
mockInvokeSync();
HeartbeatData heartbeatData = new HeartbeatData();
HeartbeatV2Result actual = mqClientAPI.sendHeartbeatV2(defaultBrokerAddr, heartbeatData, defaultTimeout);
... |
void load() {
loadClusterMembers();
loadRegions();
loadDevices();
loadDeviceLinks();
loadHosts();
} | @Test
public void load() {
title("load");
cache.load();
print(cache.dumpString());
// See mock service bundle for expected values (AbstractTopoModelTest)
assertEquals("unex # cnodes", 3, cache.clusterMemberCount());
assertEquals("unex # regions", 3, cache.regionCount... |
@Nonnull
@Override
public Optional<MessageDigest> parse(
@Nullable final String str, @Nonnull DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
return switch (str.toUpperCase().trim()) {
case "MD2" -> Optional.of(new... | @Test
void base() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaMessageDigestMapper jcaMessageDigestMapper = new JcaMessageDigestMapper();
Optional<MessageDigest> messageDigestOptional =
... |
public List<DateGroup> parseSyntax(String language)
{
language = words2numbers(language);
List<DateGroup> result = new ArrayList<DateGroup>();
List<com.joestelmach.natty.DateGroup> groups = parser.parse(language);
Date now = new Date();
for (com.joestelmach.natty.DateGroup group : grou... | @Test
public void testParseSyntax()
{
List<DateGroup> parse = new PrettyTimeParser().parseSyntax("I did it three days ago");
Assert.assertFalse(parse.isEmpty());
String formatted = new PrettyTime(Locale.ENGLISH).format(parse.get(0).getDates().get(0));
Assert.assertEquals("3 days ago", form... |
void onAvailableImage(
final long correlationId,
final int sessionId,
final long subscriptionRegistrationId,
final int subscriberPositionId,
final String logFileName,
final String sourceIdentity)
{
final Subscription subscription = (Subscription)resourceByRegI... | @Test
void shouldIgnoreUnknownNewImage()
{
conductor.onAvailableImage(
CORRELATION_ID_2,
SESSION_ID_2,
SUBSCRIPTION_POSITION_REGISTRATION_ID,
SUBSCRIPTION_POSITION_ID,
SESSION_ID_2 + "-log",
SOURCE_INFO);
verify(logBuffersF... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertLong() {
Column column = PhysicalColumn.builder().name("test").dataType(BasicType.LONG_TYPE).build();
BasicTypeDefine typeDefine = SapHanaTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName());
Asserti... |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed.");
return;
}
final LegacyAWSPluginConfiguration legacyConfiguration = clusterConfigService.get(
CLUSTER_CONFIG_... | @Test
public void doesNotDoAnyThingForExistingPluginConfigWithoutSecretKey() {
mockExistingConfig(V20200505121200_EncryptAWSSecretKey.LegacyAWSPluginConfiguration.create(
true,
"lookupRegions",
"something",
"",
true
));
... |
@Override
public void appendEdge(E edge) {
checkNotNull(edge, "Edge cannot be null");
checkArgument(edges.isEmpty() || dst().equals(edge.src()),
"Edge source must be the same as the current path destination");
edges.add(edge);
} | @Test
public void appendEdge() {
MutablePath<TestVertex, TestEdge> p = new DefaultMutablePath<>();
p.appendEdge(new TestEdge(A, B));
p.appendEdge(new TestEdge(B, C));
validatePath(p, A, C, 2);
} |
@Operation(summary = "Get single organization")
@GetMapping(value = "{id}", produces = "application/json")
@ResponseBody
public Organization getById(@PathVariable("id") Long id) {
return organizationService.getOrganizationById(id);
} | @Test
public void getOrganizationById() {
when(organizationServiceMock.getOrganizationById(1L)).thenReturn(newOrganization());
Organization result = controllerMock.getById(1L);
assertEquals(newOrganization().getName(), result.getName());
verify(organizationServiceMock, times(1)).ge... |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitMulti[] submitMulties = createSubmitMulti(exchange);
List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length);
for (SubmitMulti submitMulti : submitMulties) {
SubmitMultiResult result;
... | @Test
public void executeWithOptionalParameterNewStyle() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitMulti");
exchange.getIn().setHeader(SmppConstants.ID, "1");
... |
public <V> V retryCallable(
Callable<V> callable, Set<Class<? extends Exception>> exceptionsToIntercept) {
return RetryHelper.runWithRetries(
callable,
getRetrySettings(),
getExceptionHandlerForExceptions(exceptionsToIntercept),
NanoClock.getDefaultClock());
} | @Test
public void testRetryCallable_ReturnsExpected() {
AtomicInteger executeCounter = new AtomicInteger(0);
Callable<Integer> incrementingFunction =
() -> {
executeCounter.incrementAndGet();
if (executeCounter.get() < 2) {
throw new MyException();
}
... |
Set<SourceName> analyzeExpression(
final Expression expression,
final String clauseType
) {
final Validator extractor = new Validator(clauseType);
extractor.process(expression, null);
return extractor.referencedSources;
} | @Test
public void shouldThrowOnPossibleSyntheticKeyColumnIfQualifiedColumnReference() {
// Given:
when(sourceSchemas.isJoin()).thenReturn(true);
final Expression notSyntheticKey = new QualifiedColumnReferenceExp(
SourceName.of("Bob"), ColumnName.of("ROWKEY")
);
// When:
final Excepti... |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void contextNameTest() {
pl.setPattern("%contextName");
loggerContext.setName("aValue");
pl.start();
String val = pl.doLayout(getEventObject());
assertEquals("aValue", val);
} |
public static ComposeCombineFnBuilder compose() {
return new ComposeCombineFnBuilder();
} | @Test
public void testDuplicatedTags() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("it is already present in the composition");
TupleTag<Integer> tag = new TupleTag<>();
CombineFns.compose()
.with(new GetIntegerFunction(), Max.ofIntegers(), tag)... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testClearBufferedDataForTopicPartitions() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
// normal fetch
assertEquals(1, sendFetches());
assertFalse(fetcher.hasCompletedFetches());
client.prepareResponse(full... |
public static String normalizeSpringBootResourceUrlPath(String resourceUrlPath) {
if (resourceUrlPath.startsWith(SPRING_BOOT_URL_PREFIX)) {
return resourceUrlPath.replace(SPRING_BOOT_URL_PREFIX, SPRING_BOOT_PREFIX); // Remove "!"
} else {
return resourceUrlPath;
}
} | @Test
public void normalizeSpringBootResourceUrlPath() {
String normalized = JarUtils.normalizeSpringBootResourceUrlPath("BOOT-INF/classes!/org/example/MyClass.class");
assertThat(normalized).isEqualTo("BOOT-INF/classes/org/example/MyClass.class");
} |
@Override
public Map<String, String> findBundlesToSplit(final LoadData loadData, final PulsarService pulsar) {
bundleCache.clear();
namespaceBundleCount.clear();
final ServiceConfiguration conf = pulsar.getConfiguration();
int maxBundleCount = conf.getLoadBalancerNamespaceMaximumBund... | @Test
public void testSplitTaskWhenTopicJustOne() {
final BundleSplitterTask bundleSplitterTask = new BundleSplitterTask();
LoadData loadData = new LoadData();
LocalBrokerData brokerData = new LocalBrokerData();
Map<String, NamespaceBundleStats> lastStats = new HashMap<>();
... |
@Override
public String getFileId(final DriveItem.Metadata metadata) {
final ItemReference parent = metadata.getParentReference();
if(metadata.getRemoteItem() != null) {
final DriveItem.Metadata remoteMetadata = metadata.getRemoteItem();
final ItemReference remoteParent = rem... | @Test
public void testSharedFolderIdInSharedWithMeDrive() throws Exception {
final DriveItem.Metadata metadata;
try (final InputStream test = getClass().getResourceAsStream("/SharedFolderIdInSharedWithMeDrive.json")) {
final InputStreamReader reader = new InputStreamReader(test);
... |
public static void addApplicationIdMetric(final StreamsMetricsImpl streamsMetrics, final String applicationId) {
streamsMetrics.addClientLevelImmutableMetric(
APPLICATION_ID,
APPLICATION_ID_DESCRIPTION,
RecordingLevel.INFO,
applicationId
);
} | @Test
public void shouldAddApplicationIdMetric() {
final String name = "application-id";
final String description = "The application ID of the Kafka Streams client";
final String applicationId = "thisIsAnID";
setUpAndVerifyImmutableMetric(
name,
description,
... |
@Override
public String arguments() {
ArrayList<String> args = new ArrayList<>();
if (buildFile != null) {
args.add("-f \"" + FilenameUtils.separatorsToUnix(buildFile) + "\"");
}
if (target != null) {
args.add(target);
}
return StringUtils.jo... | @Test
public void shouldUseRakeFileFromAnyDirectoryUnderRoot() throws Exception {
RakeTask rakeTask = new RakeTask();
String rakeFile = "build/myrakefile.rb";
rakeTask.setBuildFile(rakeFile);
rakeTask.setTarget("db:migrate VERSION=0");
assertThat(rakeTask.arguments(), is("-f... |
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
@Override
protected SchemaTransform from(KafkaReadSchemaTransformConfiguration configuration) {
return new KafkaReadSchemaTransform(configuration);
} | @Test
public void testBuildTransformWithAvroSchema() {
ServiceLoader<SchemaTransformProvider> serviceLoader =
ServiceLoader.load(SchemaTransformProvider.class);
List<SchemaTransformProvider> providers =
StreamSupport.stream(serviceLoader.spliterator(), false)
.filter(provider -> pr... |
MetricsType getMetricsType(String remaining) {
String name = StringHelper.before(remaining, ":");
MetricsType type;
if (name == null) {
type = DEFAULT_METRICS_TYPE;
} else {
type = MetricsType.getByName(name);
}
if (type == null) {
thro... | @Test
public void testGetMetricsTypeNotSet() {
assertThat(component.getMetricsType("no-metrics-type"), is(MetricsComponent.DEFAULT_METRICS_TYPE));
} |
int run() {
final Map<String, String> configProps = options.getConfigFile()
.map(Ksql::loadProperties)
.orElseGet(Collections::emptyMap);
final Map<String, String> sessionVariables = options.getVariables();
try (KsqlRestClient restClient = buildClient(configProps)) {
try (Cli cli = c... | @Test
public void shouldRunInteractively() {
// When:
ksql.run();
// Then:
verify(cli).runInteractively();
} |
@Override
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
Map<String, Subscription> subscriptions) {
Map<String, List<TopicPartition>> assignment = new HashMap<>();
List<MemberInfo> memberInfoList = new Arra... | @Test
public void testOneConsumerNoTopic() {
Map<String, Integer> partitionsPerTopic = new HashMap<>();
Map<String, List<TopicPartition>> assignment = assignor.assign(partitionsPerTopic,
Collections.singletonMap(consumerId, new Subscription(Collections.emptyList())));
assert... |
public JsonNode getJson() {
return json;
} | @Test
void testCopyConstructor() {
assertEquals("{}", new JsonHttpResult(new HttpResult()).getJson().toString());
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldInjectValueForCsas() {
// Given:
givenFormatsAndProps("kafka", "protobuf",
ImmutableMap.of("VALUE_SCHEMA_ID", new IntegerLiteral(42)));
givenDDLSchemaAndFormats(LOGICAL_SCHEMA_VALUE_MISSING, "kafka", "protobuf",
SerdeFeature.WRAP_SINGLES, SerdeFeature.WRAP_SINGLES);... |
@Override
public String toString(Charset charset) {
return toString(readerIndex, readableBytes(), charset);
} | @Test
public void testToString() {
ByteBuf copied = copiedBuffer("Hello, World!", CharsetUtil.ISO_8859_1);
buffer.clear();
buffer.writeBytes(copied);
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
copied.release();
} |
@Bean
@ConditionalOnMissingBean(WebsocketDataChangedListener.class)
public DataChangedListener websocketDataChangedListener() {
return new WebsocketDataChangedListener();
} | @Test
public void testWebsocketDataChangedListener() {
WebSocketSyncConfiguration websocketListener = new WebSocketSyncConfiguration();
assertNotNull(websocketListener.websocketDataChangedListener());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.