focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public long count() { return this.byteBufferHeader.limit() + this.selectMappedBufferResult.getSize(); }
@Test public void OneMessageTransferCountTest() { ByteBuffer byteBuffer = ByteBuffer.allocate(20); byteBuffer.putInt(20); SelectMappedBufferResult selectMappedBufferResult = new SelectMappedBufferResult(0,byteBuffer,20,new DefaultMappedFile()); OneMessageTransfer manyMessageTransfer ...
public static SerializableFunction<Row, Mutation> beamRowToMutationFn( Mutation.Op operation, String table) { return (row -> { switch (operation) { case INSERT: return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row); case DELETE: return...
@Test public void testCreateInsertMutationFromRow() { Mutation expectedMutation = createMutation(Mutation.Op.INSERT); Mutation mutation = beamRowToMutationFn(Mutation.Op.INSERT, TABLE).apply(WRITE_ROW); assertEquals(expectedMutation, mutation); }
@Override public long nextDelayDuration(int reconsumeTimes) { if (reconsumeTimes < 0) { reconsumeTimes = 0; } if (reconsumeTimes > 32) { reconsumeTimes = 32; } return Math.min(max, initial * (long) Math.pow(multiplier, reconsumeTimes)); }
@Test public void testNextDelayDuration() { ExponentialRetryPolicy exponentialRetryPolicy = new ExponentialRetryPolicy(); long actual = exponentialRetryPolicy.nextDelayDuration(0); assertThat(actual).isEqualTo(TimeUnit.SECONDS.toMillis(5)); actual = exponentialRetryPolicy.nextDelayDu...
public static <T> File appendLines(Collection<T> list, String path, String charset) throws IORuntimeException { return writeLines(list, path, charset, true); }
@Test @Disabled public void appendLinesTest(){ final List<String> list = ListUtil.toList("a", "b", "c"); FileUtil.appendLines(list, FileUtil.file("d:/test/appendLines.txt"), CharsetUtil.CHARSET_UTF_8); }
private static void instanceTrackingConfig(XmlGenerator gen, InstanceTrackingConfig trackingConfig) { gen.open("instance-tracking", "enabled", trackingConfig.isEnabled()) .node("file-name", trackingConfig.getFileName()) .node("format-pattern", trackingConfig.getFormatPattern()) ...
@Test public void testInstanceTrackingConfig() { clientConfig.getInstanceTrackingConfig() .setEnabled(true) .setFileName("/dummy/file") .setFormatPattern("dummy-pattern with $HZ_INSTANCE_TRACKING{placeholder} and $RND{placeholder}"); Insta...
public RandomForest merge(RandomForest other) { if (!formula.equals(other.formula)) { throw new IllegalArgumentException("RandomForest have different model formula"); } Model[] forest = new Model[models.length + other.models.length]; System.arraycopy(models, 0, forest, 0, mo...
@Test public void testMerge() { System.out.println("merge"); RandomForest forest1 = RandomForest.fit(Segment.formula, Segment.train, 100, 16, SplitRule.GINI, 20, 100, 5, 1.0, null, Arrays.stream(seeds)); RandomForest forest2 = RandomForest.fit(Segment.formula, Segment.train, 100, 16, SplitR...
public static <T> List<LocalProperty<T>> grouped(Collection<T> columns) { return ImmutableList.of(new GroupingProperty<>(columns)); }
@Test public void testGroupedTuple() { List<LocalProperty<String>> actual = builder() .grouped("a", "b", "c") .build(); assertMatch( actual, builder().grouped("a", "b", "c", "d").build(), Optional.of(grouped("d")));...
@Description("constant representing not-a-number") @ScalarFunction("nan") @SqlType(StandardTypes.DOUBLE) public static double NaN() { return Double.NaN; }
@Test public void testNaN() { assertFunction("nan()", DOUBLE, Double.NaN); assertFunction("0.0E0 / 0.0E0", DOUBLE, Double.NaN); }
@Override public KsqlVersionMetrics collectMetrics() { final KsqlVersionMetrics metricsRecord = new KsqlVersionMetrics(); metricsRecord.setTimestamp(TimeUnit.MILLISECONDS.toSeconds(clock.millis())); metricsRecord.setConfluentPlatformVersion(AppInfo.getVersion()); metricsRecord.setKsqlComponentType(mod...
@Test public void shouldReportComponentType() { // When: final KsqlVersionMetrics metrics = basicCollector.collectMetrics(); // Then: assertThat(metrics.getKsqlComponentType(), is(MODULE_TYPE.name())); }
@Override public void append(LogEvent event) { all.mark(); switch (event.getLevel().getStandardLevel()) { case TRACE: trace.mark(); break; case DEBUG: debug.mark(); break; case INFO: i...
@Test public void metersWarnEvents() { when(event.getLevel()).thenReturn(Level.WARN); appender.append(event); assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) .isEqualTo(1); assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) ...
public Server getServer() { return server; }
@Test public void testJettyOption_LowResourceMaxIdleTimeSetUp() throws Exception { LowResourceMonitor lowResourceMonitor = webServer.getServer().getBean( LowResourceMonitor.class ); assertNotNull( lowResourceMonitor ); assertEquals( EXPECTED_RES_MAX_IDLE_TIME, lowResourceMonitor.getLowResourcesIdleTimeout...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("brick.listing.chunksize")); }
@Test public void testListEqualChunkSize() throws Exception { final Path directory = new BrickDirectoryFeature(session).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)), new TransferStatus()); final Path f1 = new BrickTouchFeature(session).touch...
public static Map<String, Collection<String>> caseInsensitiveCopyOf(Map<String, Collection<String>> map) { if (map == null) { return Collections.emptyMap(); } Map<String, Collection<String>> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, Collection<String>>...
@Test void nullMap() { // Act Map<String, Collection<String>> actualMap = caseInsensitiveCopyOf(null); // Assert result assertThat(actualMap) .isNotNull() .isEmpty(); }
public static ObjectNode json(Highlights highlights) { ObjectNode payload = objectNode(); ArrayNode devices = arrayNode(); ArrayNode hosts = arrayNode(); ArrayNode links = arrayNode(); payload.set(DEVICES, devices); payload.set(HOSTS, hosts); payload.set(LINKS, ...
@Test public void basicHighlights() { Highlights h = new Highlights(); payload = TopoJson.json(h); checkEmptyArrays(); String subdue = JsonUtils.string(payload, TopoJson.SUBDUE); assertEquals("subdue", "", subdue); }
@Override public Optional<QueryId> chooseQueryToKill(List<QueryMemoryInfo> runningQueries, List<MemoryInfo> nodes) { Map<QueryId, Long> memoryReservationOnBlockedNodes = new HashMap<>(); for (MemoryInfo node : nodes) { MemoryPoolInfo generalPool = node.getPools().get(GENERAL_POOL); ...
@Test public void testGeneralPoolHasNoReservation() { int reservePool = 10; int generalPool = 12; Map<String, Map<String, Long>> queries = ImmutableMap.<String, Map<String, Long>>builder() .put("q_1", ImmutableMap.of("n1", 0L, "n2", 0L, "n3", 0L, "n4", 0L, "n5", 0L)) ...
UriEndpoint createUriEndpoint(String url, boolean isWs) { return createUriEndpoint(url, isWs, connectAddress); }
@Test void createUriEndpointRelativeWithPort() { String test = this.builder .host("example.com") .port(443) .sslSupport() .build() .createUriEndpoint("/foo", false) .toExternalForm(); assertThat(test).isEqualTo("https://example.com/foo"); }
@Nullable public static Method findPropertySetter( @Nonnull Class<?> clazz, @Nonnull String propertyName, @Nonnull Class<?> propertyType ) { String setterName = "set" + toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); Method method; tr...
@Test public void when_findPropertySetter_public_wrongReturnType_then_returnsNull() { assertNull(findPropertySetter(JavaProperties.class, "intWithParameter", int.class)); }
public static <T> Bounded<T> from(BoundedSource<T> source) { return new Bounded<>(null, source); }
@Test public void failsWhenCustomUnboundedSourceIsNotSerializable() { thrown.expect(IllegalArgumentException.class); Read.from(new NotSerializableUnboundedSource()); }
public static String readUtf8Str(String resource) { return getResourceObj(resource).readUtf8Str(); }
@Test public void readXmlTest(){ final String str = ResourceUtil.readUtf8Str("test.xml"); assertNotNull(str); Resource resource = new ClassPathResource("test.xml"); final String xmlStr = resource.readUtf8Str(); assertEquals(str, xmlStr); }
@Override protected String buildUndoSQL() { TableRecords beforeImage = sqlUndoLog.getBeforeImage(); List<Row> beforeImageRows = beforeImage.getRows(); if (CollectionUtils.isEmpty(beforeImageRows)) { throw new ShouldNeverHappenException("Invalid UNDO LOG"); } Row r...
@Test public void buildUndoSQL() { String sql = executor.buildUndoSQL().toUpperCase(); Assertions.assertNotNull(sql); Assertions.assertTrue(sql.contains("INSERT")); Assertions.assertTrue(sql.contains("TABLE_NAME")); Assertions.assertTrue(sql.contains("ID")); }
public void unschedule(String eventDefinitionId) { final EventDefinitionDto eventDefinition = getEventDefinitionOrThrowIAE(eventDefinitionId); if (SystemNotificationEventEntityScope.NAME.equals(eventDefinition.scope())) { LOG.debug("Ignoring disable for system notification events"); ...
@Test @MongoDBFixtures("event-processors.json") public void unscheduleRemovesNotifications() { assertThat(jobTriggerService.get("61fbcca5b2507945cc120001")).isPresent(); assertThat(jobTriggerService.get("61fbcca5b2507945cc120002")).isPresent(); handler.unschedule("54e3deadbeefdeadbeef00...
public Set<String> getApplicationNames() { ImmutableSet.Builder<String> names = ImmutableSet.builder(); File[] files = appsDir.listFiles(File::isDirectory); if (files != null) { for (File file : files) { names.add(file.getName()); } } retur...
@Test public void getAppNames() throws IOException { saveZippedApp(); Set<String> names = aar.getApplicationNames(); assertEquals("incorrect names", ImmutableSet.of(APP_NAME), names); }
@Override public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) { //This code path cannot accept content types or accept types that contain //multipart/related. This is because these types of requests will usually have very large payloads and therefor...
@Test public void testStreamRequestMultiplexedRequestMultiPartAcceptType() throws Exception { //This test verifies that a StreamRequest sent to the RestLiServer throws an exception if the accept type contains //multipart/related. StreamRequest streamRequestMux = new StreamRequestBuilder(new URI("/mux"))...
@Override public boolean upload(String destPath, File file) { put(FileUtil.getAbsolutePath(file), destPath); return true; }
@Test @Disabled public void uploadTest() { sshjSftp.upload("/home/test/temp/", new File("C:\\Users\\akwangl\\Downloads\\temp\\辽宁_20190718_104324.CIME")); }
public static void setContext(RpcInvokeContext context) { LOCAL.set(RpcInvokeContext.clone(context)); }
@Test public void testSetContext() { RpcInvokeContext context = new RpcInvokeContext(); context.setTargetGroup("target"); context.setTargetURL("url"); context.setTimeout(111); context.addCustomHeader("A", "B"); context.put("C", "D"); RpcInvokeContext.setContex...
public static <T extends Enum<T>> T getForNameIgnoreCase(final @Nullable String value, final @NotNull Class<T> enumType) { return getForNameIgnoreCase(value, enumType, Map.of()); }
@Test void shouldGetEnumForNameIgnoreCaseForFallback() { TestEnum result = Enums.getForNameIgnoreCase("LEGACY", TestEnum.class, Map.of("legacy", TestEnum.ENUM2)); Assertions.assertEquals(TestEnum.ENUM2, result); }
@VisibleForTesting static EnumSet<MetricType> parseMetricTypes(String typeComponent) { final String[] split = typeComponent.split(LIST_DELIMITER); if (split.length == 1 && split[0].equals("*")) { return ALL_METRIC_TYPES; } return EnumSet.copyOf( Arrays.s...
@Test void testParseMetricTypesSingle() { final EnumSet<MetricType> types = DefaultMetricFilter.parseMetricTypes("meter"); assertThat(types).containsExactly(MetricType.METER); }
public boolean resetPendingIndex(final long newPendingIndex) { final long stamp = this.stampedLock.writeLock(); try { if (!(this.pendingIndex == 0 && this.pendingMetaQueue.isEmpty())) { LOG.error("Node {} resetPendingIndex fail, pendingIndex={}, pendingMetaQueueSize={}.", ...
@Test public void testResetPendingIndex() { assertEquals(0, closureQueue.getFirstIndex()); assertEquals(0, box.getPendingIndex()); assertTrue(box.resetPendingIndex(1)); assertEquals(0, box.getLastCommittedIndex()); assertEquals(1, closureQueue.getFirstIndex()); assert...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 3) { onInvalidDataReceived(device, data); return; } final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); if (opCode != OP_CODE_NUMBER_OF_...
@Test public void onNumberOfRecordsReceived_uint32() { final Data data = new Data(new byte[] { 5, 0, 4, 3, 2, 1 }); callback.onDataReceived(null, data); assertEquals(numberOfRecords, 16909060); }
public final int decrementAndGet() { return INDEX_UPDATER.decrementAndGet(this) & Integer.MAX_VALUE; }
@Test void testDecrementAndGet() { int get = i1.decrementAndGet(); assertEquals(Integer.MAX_VALUE, get); assertEquals(Integer.MAX_VALUE, i1.get()); get = i2.decrementAndGet(); assertEquals(126, get); assertEquals(126, i2.get()); get = i3.decrementAndGet(); ...
public HealthCheckResponse checkHealth() { final Map<String, HealthCheckResponseDetail> results = DEFAULT_CHECKS.stream() .collect(Collectors.toMap( Check::getName, check -> check.check(this) )); final boolean allHealthy = results.values().stream() .allMatch(Healt...
@Test public void shouldCheckHealth() { // When: final HealthCheckResponse response = healthCheckAgent.checkHealth(); // Then: verify(ksqlClient, atLeastOnce()).makeKsqlRequest(eq(SERVER_URI), any(), eq(REQUEST_PROPERTIES)); assertThat(response.getDetails().get(METASTORE_CHECK_NAME).getIsHealthy(...
@Override public Iterable<Link> getLinks() { return manager.getVirtualLinks(this.networkId()) .stream().collect(Collectors.toSet()); }
@Test(expected = NullPointerException.class) public void testGetLinksByNullId() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); LinkService linkService = manager.get(virtualNetwork...
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testCleanupOptionalEmptyNestedMapMultipleElements() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'data_auditor': {'type': 'MAP','value': {'winston': {'type': 'MAP','value': {}, 'internal_mode': 'OPTIONAL'}, 'audits': {'type': '...
@Override public void renameProject(Project project, final String name) { synchronized (this) { project.getLookup().lookup(ProjectInformationImpl.class).setName(name); fireProjectEvent((pl) -> pl.changed(project)); } }
@Test public void testRenameProject() { ProjectControllerImpl pc = new ProjectControllerImpl(); pc.addProjectListener(projectListener); Project project = pc.newProject(); pc.renameProject(project, "foo"); Assert.assertEquals("foo", project.getName()); Mockito.verify(p...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testNonForwardedPojo() { String[] nonForwardedFields = {"int1; string1"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, null, nonForwardedFields, null, pojoType, pojoType); as...
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_print_output_from_afterStep_hooks() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n" + " When second step\n"); ...
public static VerificationMode atMost(final int count) { checkArgument(count > 0, "Times count must be greater than zero"); return new AtMostVerification(count); }
@Test public void should_verify_expected_request_for_at_most() throws Exception { final HttpServer server = httpServer(port(), hit); server.get(by(uri("/foo"))).response("bar"); running(server, () -> { assertThat(helper.get(remoteUrl("/foo")), is("bar")); assertThat(...
public static Map<String, Map<String, InetSocketAddress>> getNNServiceRpcAddresses( Configuration conf) throws IOException { // Use default address as fall back String defaultAddress; try { defaultAddress = NetUtils.getHostPortString( DFSUtilClient.getNNAddress(conf)); } catch (Ill...
@Test public void testDefaultNamenode() throws IOException { HdfsConfiguration conf = new HdfsConfiguration(); final String hdfs_default = "hdfs://localhost:9999/"; conf.set(FS_DEFAULT_NAME_KEY, hdfs_default); // If DFS_FEDERATION_NAMESERVICES is not set, verify that // default namenode address is...
static PMMLRuntimeContext getPMMLRuntimeContext(PMMLRequestData pmmlRequestData, final Map<String, GeneratedResources> generatedResourcesMap) { String fileName = (String) pmmlRequestData.getMappedRequestParams().get(PMML_FILE_NAME).getValue(); PMMLRequ...
@Test void getPMMLRuntimeContextFromPMMLRequestData() { PMMLRequestData pmmlRequestData = getPMMLRequestDataWithInputData(MODEL_NAME, FILE_NAME); Map<String, ParameterInfo> mappedRequestParams = pmmlRequestData.getMappedRequestParams(); final Map<String, GeneratedResources> generatedResourc...
@Override public void encode(Event event, OutputStream output) throws IOException { String outputString = (format == null ? event.toString() : StringInterpolation.evaluate(event, format)); output.write(outputString.getBytes(charset)); }
@Test public void testEncodeWithFormat() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Plain encoder = new Plain(new ConfigurationImpl(Collections.singletonMap("format", "%{host}-%{message}")), null); String message = "Hello world"; String hos...
public void commitSegmentFile(String realtimeTableName, CommittingSegmentDescriptor committingSegmentDescriptor) throws Exception { Preconditions.checkState(!_isStopping, "Segment manager is stopping"); String rawTableName = TableNameBuilder.extractRawTableName(realtimeTableName); String segmentName ...
@Test public void testCommitSegmentFile() throws Exception { PinotFSFactory.init(new PinotConfiguration()); File tableDir = new File(TEMP_DIR, RAW_TABLE_NAME); String segmentName = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName(); String segmentFileName = SegmentComplet...
@Override public CompletableFuture<Set<AbstractID>> listCompletedClusterDatasetIds() { return sendRequest(ClusterDataSetListHeaders.INSTANCE) .thenApply( clusterDataSetListResponseBody -> clusterDataSetListResponseBody.getDataSets().str...
@Test public void testListCompletedClusterDatasetIds() { Set<AbstractID> expectedCompletedClusterDatasetIds = new HashSet<>(); expectedCompletedClusterDatasetIds.add(new AbstractID()); expectedCompletedClusterDatasetIds.add(new AbstractID()); try (TestRestServerEndpoint restServerEn...
@Override public PageData<User> findCustomerUsers(UUID tenantId, UUID customerId, PageLink pageLink) { return DaoUtil.toPageData( userRepository .findUsersByAuthority( tenantId, customerId, ...
@Test public void testFindCustomerUsers() { PageLink pageLink = new PageLink(40); PageData<User> customerUsers1 = userDao.findCustomerUsers(tenantId, customerId, pageLink); assertEquals(40, customerUsers1.getData().size()); pageLink = pageLink.nextPageLink(); PageData<User> c...
public boolean isUnqualifiedShorthandProjection() { if (1 != projections.size()) { return false; } Projection projection = projections.iterator().next(); return projection instanceof ShorthandProjection && !((ShorthandProjection) projection).getOwner().isPresent(); }
@Test void assertUnqualifiedShorthandProjectionWithWrongShortProjection() { ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.singleton(getShorthandProjection())); assertFalse(projectionsContext.isUnqualifiedShorthandProjection()); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromSnapshotIdWithInvalidIds() throws Exception { appendTwoSnapshots(); // find an invalid snapshotId long invalidSnapshotId = 0L; while (invalidSnapshotId == snapshot1.snapshotId() || invalidSnapshotId == snapshot2.snapshotId()) { invalidSnapshotId++; ...
@Override public void doAlarm(List<AlarmMessage> alarmMessages) throws Exception { Map<String, PagerDutySettings> settingsMap = alarmRulesWatcher.getPagerDutySettings(); if (settingsMap == null || settingsMap.isEmpty()) { return; } Map<String, List<AlarmMessage>> grouped...
@Test @Disabled public void testWithRealAccount() throws Exception { // replace this with your actual integration key(s) and run this test manually List<String> integrationKeys = Arrays.asList( "dummy-integration-key" ); Rules rules = new Rules(); PagerDu...
@Override public double get(int index) { int foundIndex = Arrays.binarySearch(indices, index); if (foundIndex < 0) { return 0; } else { return values[foundIndex]; } }
@Test public void serialization431Test() throws URISyntaxException, IOException { Path vectorPath = Paths.get(SparseVectorTest.class.getResource("sparse-vector-431.tribuo").toURI()); try (InputStream fis = Files.newInputStream(vectorPath)) { TensorProto proto = TensorProto.parseFrom(fis)...
@VisibleForTesting public List<ProjectionContext> planRemoteAssignments(Assignments assignments, VariableAllocator variableAllocator) { ImmutableList.Builder<List<ProjectionContext>> assignmentProjections = ImmutableList.builder(); for (Map.Entry<VariableReferenceExpression, RowExpression> entry...
@Test void testRemoteAndLocal() { PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata()); planBuilder.variable("x", INTEGER); planBuilder.variable("y", INTEGER); PlanRemoteProjections rule = new PlanRemoteProjections(getFunctionAndTypeM...
public static boolean isSymlink(@NonNull File file) throws IOException { return isSymlink(fileToPath(file)); }
@Test public void testIsSymlink_onWindows_junction() throws Exception { assumeTrue("Uses Windows-specific features", Functions.isWindows()); File targetDir = tmp.newFolder("targetDir"); File d = tmp.newFolder("dir"); File junction = WindowsUtil.createJunction(new File(d, "junction"),...
public static CharSequence getCharsetAsSequence(HttpMessage message) { CharSequence contentTypeValue = message.headers().get(HttpHeaderNames.CONTENT_TYPE); if (contentTypeValue != null) { return getCharsetAsSequence(contentTypeValue); } else { return null; } }
@Test public void testGetCharsetAsRawCharSequence() { String QUOTES_CHARSET_CONTENT_TYPE = "text/html; charset=\"utf8\""; String SIMPLE_CONTENT_TYPE = "text/html"; HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); message.headers().set(HttpH...
@Override public void batchRegisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException { redoService.cacheInstanceForRedo(serviceName, groupName, instances); doBatchRegisterService(serviceName, groupName, instances); }
@Test void testBatchRegisterService() throws NacosException { List<Instance> instanceList = new ArrayList<>(); instance.setHealthy(true); instanceList.add(instance); response = new BatchInstanceResponse(); when(this.rpcClient.request(any())).thenReturn(response); clie...
@VisibleForTesting public void validateDictDataExists(Long id) { if (id == null) { return; } DictDataDO dictData = dictDataMapper.selectById(id); if (dictData == null) { throw exception(DICT_DATA_NOT_EXISTS); } }
@Test public void testValidateDictDataExists_success() { // mock 数据 DictDataDO dbDictData = randomDictDataDO(); dictDataMapper.insert(dbDictData);// @Sql: 先插入出一条存在的数据 // 调用成功 dictDataService.validateDictDataExists(dbDictData.getId()); }
@Override public SelType call(String methodName, SelType[] args) { if ("min".equals(methodName) && args.length == 2) { return SelLong.of(Math.min(((SelLong) args[0]).longVal(), ((SelLong) args[1]).longVal())); } else if ("max".equals(methodName) && args.length == 2) { return SelLong.of(Math.max(((...
@Test(expected = UnsupportedOperationException.class) public void testInvalidCallMethod() { SelJavaMath.INSTANCE.call("invalid", new SelType[] {}); }
public static boolean isTrue(Boolean bool) { return Boolean.TRUE.equals(bool); }
@Test public void assertIsTrue() { Assert.assertTrue(BooleanUtil.isTrue(true)); }
@Override public String named() { return PluginEnum.PARAM_MAPPING.getName(); }
@Test public void tesNamed() { assertEquals(this.paramMappingPlugin.named(), PluginEnum.PARAM_MAPPING.getName()); }
public PatternLayoutEncoder getTagEncoder() { return this.tagEncoder; }
@Test public void tagExcludesStackTraces() { // create logging event with throwable LoggingEvent event = new LoggingEvent(); Throwable throwable = new Throwable("throwable"); ThrowableProxy tp = new ThrowableProxy(throwable); event.setThrowableProxy(tp); event.setMessage(TAG); setTagPatte...
public String formatHex() { return ByteUtils.formatHex(bytes); }
@Test @Parameters(method = "bytesToHexStringVectors") public void formatHexValid(byte[] bytes, String expectedHexString) { ByteArray ba = new ByteArray(bytes); assertEquals("incorrect hex formatted string", expectedHexString, ba.formatHex()); }
public static InMemorySorter create(Options options) { return new InMemorySorter(options); }
@Test public void testMultipleIterations() throws Exception { SorterTestUtils.testMultipleIterations(InMemorySorter.create(new InMemorySorter.Options())); }
static void dissectRecordingSessionStateChange( final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int absoluteOffset = offset; absoluteOffset += dissectLogHeader(CONTEXT, RECORDING_SESSION_STATE_CHANGE, buffer, absoluteOffset, builder); final long re...
@Test void recordingSessionStateChange() { final String reason = "some other reason"; internalEncodeLogHeader(buffer, 0, 10, 20, () -> 1_700_000_000L); buffer.putLong(LOG_HEADER_LENGTH, 30_000_000_000L, LITTLE_ENDIAN); buffer.putLong(LOG_HEADER_LENGTH + SIZE_OF_LONG, 40_000_000_0...
@Override public int intersection(String... names) { return get(intersectionAsync(names)); }
@Test public void testIntersection() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); set1.add(3); RSet<Integer> set2 = redisson.getSet("set2"); set2.a...
public V put(final int key, final V value) { final Entry<V>[] table = this.table; final int index = HashUtil.indexFor(key, table.length, mask); for (Entry<V> e = table[index]; e != null; e = e.hashNext) { if (e.key == key) { return e.setValue(value); } ...
@Test public void forEachProcedure() { final IntHashMap<String> tested = new IntHashMap<>(); for (int i = 0; i < 100000; ++i) { tested.put(i, Integer.toString(i)); } final int[] ii = {0}; tested.forEachKey(object -> { ii[0]++; return true; ...
public long put(final long key, final long value) { assert key != missingValue : "Invalid key " + key; assert value != missingValue : "Invalid value " + value; long oldValue = missingValue; int index = evenLongHash(key, mask); long candidateKey; while ((candidateKey = ent...
@Test public void putShouldReturnOldValue() { map.put(1L, 1L); assertEquals(1L, map.put(1L, 2L)); }
public static String before(String text, String before) { if (text == null) { return null; } int pos = text.indexOf(before); return pos == -1 ? null : text.substring(0, pos); }
@Test public void testBefore() { assertEquals("Hello ", StringHelper.before("Hello World", "World")); assertEquals("Hello ", StringHelper.before("Hello World Again", "World")); assertNull(StringHelper.before("Hello Again", "Foo")); assertTrue(StringHelper.before("mykey:ignore", ":",...
@Override public String getStatusText() { return this.response.getStatusLine().getReasonPhrase(); }
@Test void testGetStatusText() { when(statusLine.getReasonPhrase()).thenReturn("test"); assertEquals("test", clientHttpResponse.getStatusText()); }
@Override public Optional<EfestoOutputPMML> evaluateInput(EfestoInput<Map<String, Object>> toEvaluate, EfestoRuntimeContext context) { return executeEfestoInputFromMap(toEvaluate, context); }
@Test void evaluateWrongIdentifier() { modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, "wrongmodel"); inputPMML = new BaseEfestoInput<>(modelLocalUriId, getInputData(MODEL_NAME, FILE_NAME)); efestoRuntimeContext = getEfestoContext(me...
@Override public String buildContext() { final String plugins = ((Collection<?>) getSource()) .stream() .map(s -> ((PluginDO) s).getName()) .collect(Collectors.joining(",")); return String.format("the plugins[%s] is %s", plugins, StringUtils.lowerCase(...
@Test public void batchChangePluginBuildContextTest() { String context = String.format("the plugins[%s] is %s", "test-plugin,test-plugin-two", EventTypeEnum.PLUGIN_DELETE.getType().toString().toLowerCase()); assertEquals(context, deletedEvent.buildContext()); }
public static String getTextValue(final Object jdbcBitValue) { if (null == jdbcBitValue) { return null; } return (Boolean) jdbcBitValue ? "1" : "0"; }
@Test void assertGetTextBitValue() { Object jdbcBitValue = true; String textValue = PostgreSQLTextBitUtils.getTextValue(jdbcBitValue); assertThat(textValue, is("1")); }
@Override public Object toKsqlRow(final Schema connectSchema, final Object connectData) { if (connectData == null) { return null; } return toKsqlValue(schema, connectSchema, connectData, ""); }
@Test public void shouldTranslateNullValueCorrectly() { // Given: final Schema rowSchema = SchemaBuilder.struct() .field("INT", SchemaBuilder.OPTIONAL_INT32_SCHEMA) .optional() .build(); final Struct connectStruct = new Struct(rowSchema); final ConnectDataTranslator connectTo...
@VisibleForTesting static List<String> truncateToMaxWidth(List<String> lines) { List<String> truncatedLines = new ArrayList<>(); for (String line : lines) { if (line.length() > MAX_FOOTER_WIDTH) { truncatedLines.add(line.substring(0, MAX_FOOTER_WIDTH - 3) + "..."); } else { truncat...
@Test public void testTruncateToMaxWidth() { List<String> lines = Arrays.asList( "this line of text is way too long and will be truncated", "this line will not be truncated"); Assert.assertEquals( Arrays.asList( "this line of text is way too long and will be...
public void checkpoint() throws IOException { trashPolicy.createCheckpoint(); }
@Test public void testTrashRestarts() throws Exception { Configuration conf = new Configuration(); conf.setClass("fs.trash.classname", AuditableTrashPolicy.class, TrashPolicy.class); conf.setClass("fs.file.impl", TestLFS.class, FileSystem.class); conf.set(FS_TRASH_INTERVAL_KEY, "50"); ...
@Override public void handlerRule(final RuleData ruleData) { HystrixPropertiesFactory.reset(); Optional.ofNullable(ruleData.getHandle()).ifPresent(rule -> { HystrixHandle hystrixHandle = GsonUtils.getInstance().fromJson(rule, HystrixHandle.class); String key = CacheKeyUtils.I...
@Test public void testHandlerRUle() { hystrixPluginDataHandler.handlerRule(mock(RuleData.class)); assertNotNull(HystrixPropertiesFactory.getCommandProperties(mock(HystrixCommandKey.class), mock(Setter.class))); }
@Override @Transactional(rollbackFor = Exception.class) public void deleteCombinationActivity(Long id) { // 校验存在 CombinationActivityDO activity = validateCombinationActivityExists(id); // 校验状态 if (CommonStatusEnum.isEnable(activity.getStatus())) { throw exception(COMB...
@Test public void testDeleteCombinationActivity_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> combinationActivityService.deleteCombinationActivity(id), COMBINATION_ACTIVITY_NOT_EXISTS); }
@Override public WriteTxnMarkersResponse getErrorResponse(int throttleTimeMs, Throwable e) { Errors error = Errors.forException(e); final Map<Long, Map<TopicPartition, Errors>> errors = new HashMap<>(data.markers().size()); for (WritableTxnMarker markerEntry : data.markers()) { ...
@Test public void testGetErrorResponse() { WriteTxnMarkersRequest.Builder builder = new WriteTxnMarkersRequest.Builder(ApiKeys.WRITE_TXN_MARKERS.latestVersion(), markers); for (short version : ApiKeys.WRITE_TXN_MARKERS.allVersions()) { WriteTxnMarkersRequest request = builder.build(versi...
public boolean isHeaderColumn(final ColumnName columnName) { return findColumnMatching(withNamespace(HEADERS).and(withName(columnName))) .isPresent(); }
@Test public void shouldMatchHeaderColumnName() { assertThat(SOME_SCHEMA.isHeaderColumn(H0), is(true)); assertThat(SOME_SCHEMA.isHeaderColumn(ROWPARTITION_NAME), is(false)); assertThat(SOME_SCHEMA.isHeaderColumn(K0), is(false)); assertThat(SOME_SCHEMA.isHeaderColumn(F0), is(false)); }
@Override public String getName() { return this.name; }
@Test public void keep_500_first_characters_of_name() { String veryLongString = repeat("a", 3_000); ComponentImpl underTest = buildSimpleComponent(FILE, "file") .setName(veryLongString) .build(); String expectedName = repeat("a", 500 - 3) + "..."; assertThat(underTest.getName()).isEqualT...
public static List<ColumnarBatch> readParquetFile(String filePath, StructType physicalSchema, Configuration hadoopConf) { try (Timer ignored = Tracers.watchScope(Tracers.get(), EXTERNAL, "DeltaLakeParquetHandler.readParquetFileAndGetColumnarBatch")) { io.delta.kernel.defaults.interna...
@Test public void testCheckpointCache() throws ExecutionException { LoadingCache<Pair<String, StructType>, List<ColumnarBatch>> checkpointCache = CacheBuilder.newBuilder() .expireAfterWrite(3600, TimeUnit.SECONDS) .weigher((key, value) -> Math.toIntExa...
public static String replaceProperty(String expression, Map<String, String> params) { return replaceProperty(expression, new InmemoryConfiguration(params)); }
@Test void testReplaceProperty() throws Exception { String s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.singletonMap("a.b.c", "ABC")); assertEquals("1ABC2ABC3", s); s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.<String, String>emptyMap()); a...
public static String getMigrationsDir( final String configFilePath, final MigrationConfig config ) { final String migrationsDir = config.getString(MigrationConfig.KSQL_MIGRATIONS_DIR_OVERRIDE); if (migrationsDir != null && !migrationsDir.isEmpty()) { return migrationsDir; } else { ...
@Test public void shouldDefaultMigrationsDirBasedOnConfigPath() { // Given: when(config.getString(MigrationConfig.KSQL_MIGRATIONS_DIR_OVERRIDE)).thenReturn(""); // When / Then: assertThat(MigrationsDirectoryUtil.getMigrationsDir(migrationsConfigPath, config), is(Paths.get(testDir, MigrationsD...
@VisibleForTesting static ResolvingDecoder resolve(Decoder decoder, Schema readSchema, Schema fileSchema) throws IOException { Map<Schema, Map<Schema, ResolvingDecoder>> cache = DECODER_CACHES.get(); Map<Schema, ResolvingDecoder> fileSchemaToResolver = cache.computeIfAbsent(readSchema, k -> new ...
@SuppressWarnings("UnusedAssignment") // the unused assignments are necessary for this test @Test public void testDecoderCachingReadSchemaSameAsFileSchema() throws Exception { Decoder dummyDecoder = DecoderFactory.get().binaryDecoder(new byte[] {}, null); Schema fileSchema = avroSchema(); ResolvingDecod...
Flux<Post> findAll() { return Flux.fromIterable(data.values()); }
@Test public void testGetAllPosts() { StepVerifier.create(posts.findAll()) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post one"))) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post two"))) .expectComplete() .verify(); }
public static Collection<PValue> nonAdditionalInputs(AppliedPTransform<?, ?, ?> application) { ImmutableList.Builder<PValue> mainInputs = ImmutableList.builder(); PTransform<?, ?> transform = application.getTransform(); for (Map.Entry<TupleTag<?>, PCollection<?>> input : application.getInputs().entrySet()) ...
@Test public void nonAdditionalInputsWithOnlyAdditionalInputsThrows() { Map<TupleTag<?>, PCollection<?>> additionalInputs = new HashMap<>(); additionalInputs.put(new TupleTag<String>() {}, pipeline.apply(Create.of("1, 2", "3"))); additionalInputs.put(new TupleTag<Long>() {}, pipeline.apply(GenerateSequenc...
public static int gt0(int value, String name) { return (int) gt0((long) value, name); }
@Test public void checkGTZeroGreater() { assertEquals(Check.gt0(120, "test"), 120); }
@Override public GenericRecordBuilder newRecordBuilder() { return new ProtobufNativeRecordBuilderImpl(this); }
@Test public void testClazzBasedReaderByClazzGenericWriterSchema() { genericmessage = genericProtobufNativeSchema.newRecordBuilder().set("stringField", STRING_FIELD_VLUE).set("doubleField", DOUBLE_FIELD_VLUE).build(); byte[] messageBytes = genericProtobufNativeSchema.encode(genericmessage); ...
public void setComplexProperty(String name, Object complexProperty) { String dName = Introspector.decapitalize(name); PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dName); if (propertyDescriptor == null) { addWarn("Could not find PropertyDescriptor for [" + name + "] in " + ...
@Test public void testSetComplexProperty() { Door door = new Door(); setter.setComplexProperty("door", door); assertEquals(door, house.getDoor()); }
public int deliverAll(Set<EmailDeliveryRequest> deliveries) { if (deliveries.isEmpty() || !isActivated()) { LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG); return 0; } return (int) deliveries.stream() .filter(t -> !t.recipientEmail().isBlank()) .map(t -> { EmailMessage emailM...
@Test public void deliverAll_has_no_effect_if_set_is_empty() { EmailSmtpConfiguration emailSettings = mock(EmailSmtpConfiguration.class); EmailNotificationChannel emailNotificationChannel = new EmailNotificationChannel(emailSettings, server, null, null); int count = emailNotificationChannel.deliverAll(Co...
public TimelineEvent deleteWorkflow(String workflowId, User author) { if (IdHelper.isInlineWorkflowId(workflowId)) { throw new MaestroUnprocessableEntityException( "Cannot delete an inline foreach workflow [%s], please delete its parent concrete workflow instead.", workflowId); } ...
@Test public void testDeleteWorkflow() throws Exception { WorkflowDefinition wfd = loadWorkflow(TEST_WORKFLOW_ID1); workflowDao.addWorkflowDefinition(wfd, wfd.getPropertiesSnapshot().extractProperties()); WorkflowDefinition def = workflowDao.getWorkflowDefinition(TEST_WORKFLOW_ID1, "latest"); assertNo...
@Override public void start() { Collection<ServerPluginInfo> loadedPlugins = pluginJarLoader.loadPlugins(); logInstalledPlugins(loadedPlugins); Collection<ExplodedPlugin> explodedPlugins = extractPlugins(loadedPlugins); Map<String, Plugin> instancesByKey = pluginClassLoader.load(explodedPlugins); ...
@Test public void load_plugins() throws IOException { ServerPluginInfo p1 = newPluginInfo("p1"); ServerPluginInfo p2 = newPluginInfo("p2"); when(jarLoader.loadPlugins()).thenReturn(Arrays.asList(p1, p2)); when(jarExploder.explode(p1)).thenReturn(new ExplodedPlugin(p1, "p1", new File("p1Exploded.jar"),...
public boolean hasCycle() { Set<Node> looped = findCycles(); if (looped.isEmpty()) { return false; } Set<Node> checkingSet = new HashSet<>(looped); checkingSet.retainAll(startingNodes); if (!checkingSet.isEmpty()) { // a starting node is part of the loop return true; } ...
@Test void hasCycle() { CallGraph callGraph = new CallGraph(); callGraph.addEdge("a", "b"); callGraph.addEdge("a", "c"); callGraph.addEdge("b", "d"); callGraph.addEdge("c", "d"); callGraph.addEdge("c", "b"); callGraph.addEdge("d", "b"); callGraph.addStarting(new CallGraph.Node("a")); ...
static boolean isSshUrl(@Nullable String remote) { return remote != null && SSH_URL_PATTERN.matcher(remote).matches(); }
@Test public void testSshUrlChecker() { Assert.assertTrue(GitUtils.isSshUrl("ssh://some-host/some-path")); Assert.assertTrue(GitUtils.isSshUrl("ssh://some-host/some-path/more")); Assert.assertTrue(GitUtils.isSshUrl("ssh://some-host:port/some-path/more")); Assert.assertTrue(GitUtils.i...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testContainsAnd() throws Exception { BinaryColumn col = binaryColumn("binary_field"); // both evaluate to false (no upper-case letters are in the dictionary) Operators.Contains<Binary> B = contains(eq(col, Binary.fromString("B"))); Operators.Contains<Binary> C = contains(eq(col, Bin...
@SuppressWarnings("deprecation") @VisibleForTesting public String getWebSocketReadUri(String topic) { String serviceURLWithoutTrailingSlash = serviceURL.substring(0, serviceURL.endsWith("/") ? serviceURL.length() - 1 : serviceURL.length()); TopicName topicName = TopicName.get(to...
@Test(dataProvider = "startMessageIds") public void testGetWebSocketReadUri(String msgId, String msgIdQueryParam) throws Exception { CmdRead cmdRead = new CmdRead(); cmdRead.updateConfig(null, null, "ws://localhost:8080/"); Field startMessageIdField = CmdRead.class.getDeclaredField("startMes...
public static Expression convert(Filter[] filters) { Expression expression = Expressions.alwaysTrue(); for (Filter filter : filters) { Expression converted = convert(filter); Preconditions.checkArgument( converted != null, "Cannot convert filter to Iceberg: %s", filter); expression =...
@Test public void testLocalDateTimeFilterConversion() { LocalDateTime ldt = LocalDateTime.parse("2018-10-18T00:00:57"); long epochMicros = ChronoUnit.MICROS.between(LocalDateTime.ofInstant(Instant.EPOCH, ZoneId.of("UTC")), ldt); Expression instantExpression = SparkFilters.convert(GreaterThan.appl...
@Override public DataNodeDto resetNode(String nodeId) throws NodeNotFoundException { final DataNodeDto node = nodeService.byNodeId(nodeId); if (node.getDataNodeStatus() != DataNodeStatus.REMOVED) { throw new IllegalArgumentException("Only previously removed data nodes can rejoin the clus...
@Test public void resetNodePublishesClusterEvent() throws NodeNotFoundException { final String testNodeId = "node"; nodeService.registerServer(buildTestNode(testNodeId, DataNodeStatus.REMOVED)); classUnderTest.resetNode(testNodeId); verify(clusterEventBus).post(DataNodeLifecycleEvent...
public static CloudConfiguration buildCloudConfigurationForStorage(Map<String, String> properties) { return buildCloudConfigurationForStorage(properties, false); }
@Test public void testGCPCloudConfiguration() { Map<String, String> map = new HashMap<String, String>() { { put(CloudConfigurationConstants.GCP_GCS_SERVICE_ACCOUNT_PRIVATE_KEY, "XX"); put(CloudConfigurationConstants.GCP_GCS_SERVICE_ACCOUNT_PRIVATE_KEY_ID, "XX"); ...
@Override /** * Parses the given text to transform it to the desired target type. * @param text The LLM output in string format. * @return The parsed output in the desired target type. */ public T convert(@NonNull String text) { try { // Remove leading and trailing whitespace text = text.trim(); /...
@Test public void convertClassType() { var converter = new BeanOutputConverter<>(TestClass.class); var testClass = converter.convert("{ \"someString\": \"some value\" }"); assertThat(testClass.getSomeString()).isEqualTo("some value"); }
@Override public Optional<SchemaDescription> getSchema(String topic, Target type) { String subject = schemaSubject(topic, type); return getSchemaBySubject(subject) .flatMap(schemaMetadata -> //schema can be not-found, when schema contexts configured improperly getSchemaById(sch...
@Test void returnsEmptyDescriptorIfSchemaNotRegisteredInSR() { String topic = "test"; assertThat(serde.getSchema(topic, Serde.Target.KEY)).isEmpty(); assertThat(serde.getSchema(topic, Serde.Target.VALUE)).isEmpty(); }
@Override public MongoDbConnectorEmbeddedDebeziumConfiguration getConfiguration() { return configuration; }
@Test void testIfConnectorEndpointCreatedWithConfig() throws Exception { final Map<String, Object> params = new HashMap<>(); params.put("offsetStorageFileName", "/offset_test_file"); params.put("mongodbConnectionString", "mongodb://localhost:27017/?replicaSet=rs0"); params.put("mongo...
@SuppressWarnings("ResultOfMethodCallIgnored") @SneakyThrows(InterruptedException.class) public void doAwait(final ChannelHandlerContext context) { while (!context.channel().isWritable() && context.channel().isActive()) { context.flush(); lock.lock(); try { ...
@Test void assertDoAwait() throws NoSuchFieldException, IllegalAccessException { when(channel.isWritable()).thenReturn(false); when(channel.isActive()).thenReturn(true); when(channelHandlerContext.channel()).thenReturn(channel); ExecutorService executorService = Executors.newFixedThr...
@PublicAPI(usage = ACCESS) public static PackageMatchers of(String... packageIdentifiers) { return of(ImmutableSet.copyOf(packageIdentifiers)); }
@Test public void matches_any_package() { assertThat(PackageMatchers.of("..match..", "..other..")) .accepts("foo.match.bar") .accepts("foo.other.bar") .accepts("foo.match.other.bar") .rejects("foo.bar") .rejects("matc.hother"); ...
public int getEstimatedRequestedSegmentsUsage() { int totalNumberOfMemorySegments = getTotalNumberOfMemorySegments(); return totalNumberOfMemorySegments == 0 ? 0 : Math.toIntExact( 100L * getEstimatedNumberOfRequeste...
@Test void testEmptyPoolSegmentsUsage() throws IOException { try (CloseableRegistry closeableRegistry = new CloseableRegistry()) { NetworkBufferPool globalPool = new NetworkBufferPool(0, 128); closeableRegistry.registerCloseable(globalPool::destroy); assertThat(globalPool...