focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public int runScript(final String scriptFile) { int errorCode = NO_ERROR; RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient); try { // RUN SCRIPT calls the `makeKsqlRequest` directly, which does not support PRINT/SELECT. // // To avoid interfere with the RUN SCRIPT ...
@Test public void shouldRunScriptOnRunScript() throws Exception { // Given: final File scriptFile = TMP.newFile("script.sql"); Files.write(scriptFile.toPath(), ("" + "CREATE STREAM shouldRunScript AS SELECT * FROM " + ORDER_DATA_PROVIDER.sourceName() + ";" + "").getBytes(StandardCharsets.U...
@Override public Mono<Void> apply(final ServerWebExchange exchange, final ShenyuPluginChain shenyuPluginChain, final ParamMappingRuleHandle paramMappingRuleHandle) { return exchange.getFormData() .switchIfEmpty(Mono.defer(() -> Mono.just(new LinkedMultiValueMap<>()))) .flatMa...
@Test public void testApply() { when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(formDataOperator.apply(this.exchange, this.chain, paramMappingRuleHandle)).expectSubscription().verifyComplete(); }
@SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "unchecked"}) public E relaxedPeek() { final E[] buffer = consumerBuffer; final long index = consumerIndex; final long mask = consumerMask; final long offset = modifiedCalcElementOffset(index, mask); Object e = lvElement(buffer, offset);...
@Test(dataProvider = "populated") public void relaxedPeek_whenPopulated(MpscGrowableArrayQueue<Integer> queue) { assertThat(queue.relaxedPeek()).isNotNull(); assertThat(queue).hasSize(POPULATED_SIZE); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void tooOldJava1() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/crash-report/too_old_java.txt")), CrashReportAnalyzer.Rule.TOO_OLD_JAVA); assertEquals("52", result.getMatcher().group("exp...
public static Config configFromYaml(File yamlFile) throws Exception { return parseYaml(yamlFile, RunAirborneOnKafkaNop.Config.class); }
@Test public void canBuildConfigFromYaml() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File yamlFile = new File(classLoader.getResource("fullAirborneConfig.yaml").getFile()); RunAirborneOnKafkaNop.Config config = configFromYaml(yamlFile); ...
@Override public Object cloneAggregatedValue(Object value) { return deserializeAggregatedValue(serializeAggregatedValue(value)); }
@Test public void shouldRetainSketchOrdering() { UpdateSketch input = Sketches.updateSketchBuilder().build(); IntStream.range(0, 10).forEach(input::update); Sketch unordered = input.compact(false, null); Sketch ordered = input.compact(true, null); DistinctCountThetaSketchValueAggregator agg = new ...
@PostMapping("/insertOrUpdate") public ShenyuAdminResult createOrUpdate(@Valid @RequestBody final MockRequestRecordDTO mockRequestRecordDTO) { return ShenyuAdminResult.success(ShenyuResultMessage.SUCCESS, mockRequestRecordService.createOrUpdate(mockRequestRecordDTO)); }
@Test public void testCreateOrUpdate() throws Exception { given(mockRequestRecordService.createOrUpdate(any())).willReturn(1); this.mockMvc.perform(MockMvcRequestBuilders.post("/mock/insertOrUpdate") .contentType(MediaType.APPLICATION_JSON) .content(Gs...
@Override public void upgrade() { MongoCollection<Document> roles = mongoDatabase.getCollection("roles"); Document viewsUserRole = roles.findOneAndDelete(eq("name", "Views User")); if (viewsUserRole != null) { removeRoleFromUsers(viewsUserRole); } }
@Test public void removesRoleFromRolesCollection() { insertRole("Views User"); Document otherRole = insertRole("Some Other Role"); migration.upgrade(); assertThat(rolesCollection.find()).containsOnly(otherRole); }
@Override public List<PrivilegedOperation> bootstrap(Configuration conf) throws ResourceHandlerException { super.bootstrap(conf); swappiness = conf .getInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, YarnConfiguration.DEFAULT_NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS); i...
@Test public void testBootstrap() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false); List<PrivilegedOperation> ret = cGroupsMemoryResourceHandler.boot...
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testSingleIdDailyForecastQuery() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setIds("524901"); weatherConfiguration.setMode(WeatherMode.XML); weatherConfiguration.setLanguage(WeatherLanguage.nl); ...
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存 public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) { // 1. 无数据权限 if (CollUtil.isEmpty(rules)) { return Collections.emptyList(); } // 2. 未配置,则默认开启 D...
@Test public void testGetDataPermissionRule_02() { // 准备参数 String mappedStatementId = randomString(); // 调用 List<DataPermissionRule> result = dataPermissionRuleFactory.getDataPermissionRule(mappedStatementId); // 断言 assertSame(rules, result); }
public static String maskJson(String input, String key) { if(input == null) return null; DocumentContext ctx = JsonPath.parse(input); return maskJson(ctx, key); }
@Test public void testMaskIssue942() { String input = "{\"name\":\"Steve\", \"list\":[{\"name\":\"Josh\", \"creditCardNumber\":\"4586996854721123\"}],\"password\":\"secret\"}"; String output = Mask.maskJson(input, "testIssue942"); System.out.println(output); Assert.assertEquals(o...
public static String buildErrorMessage(final Throwable throwable) { if (throwable == null) { return ""; } final List<String> messages = dedup(getErrorMessages(throwable)); final String msg = messages.remove(0); final String causeMsg = messages.stream() .filter(s -> !s.isEmpty()) ...
@Test public void shouldBuildErrorMessageFromExceptionChain() { final Throwable cause = new TestException("Something went wrong"); final Throwable subLevel2 = new TestException("Intermediate message 2", cause); final Throwable subLevel1 = new TestException("Intermediate message 1", subLevel2); final T...
protected AccessControlList toAcl(final Acl acl) { if(Acl.EMPTY.equals(acl)) { return null; } if(Acl.CANNED_PRIVATE.equals(acl)) { return AccessControlList.REST_CANNED_PRIVATE; } if(Acl.CANNED_BUCKET_OWNER_FULLCONTROL.equals(acl)) { return Acce...
@Test public void testInvalidOwner() { final S3AccessControlListFeature f = new S3AccessControlListFeature(session); assertNull(f.toAcl(Acl.EMPTY)); assertNull(f.toAcl(new Acl(new Acl.UserAndRole(new Acl.Owner(""), new Acl.Role(Acl.Role.FULL))))); }
public Optional<Node> node(String listenerName) { Endpoint endpoint = listeners().get(listenerName); if (endpoint == null) { return Optional.empty(); } return Optional.of(new Node(id, endpoint.host(), endpoint.port(), null)); }
@Test public void testToNode() { assertEquals(Optional.empty(), REGISTRATIONS.get(0).node("NONEXISTENT")); assertEquals(Optional.of(new Node(0, "localhost", 9107, null)), REGISTRATIONS.get(0).node("PLAINTEXT")); assertEquals(Optional.of(new Node(0, "localhost", 9207, null)), ...
@Override public boolean match(Message msg, StreamRule rule) { Object rawField = msg.getField(rule.getField()); if (rawField == null) { return rule.getInverted(); } if (rawField instanceof String) { String field = (String) rawField; Boolean resul...
@Test public void testInvertedEmptyStringFieldMatch() throws Exception { String fieldName = "sampleField"; StreamRule rule = getSampleRule(); rule.setField(fieldName); rule.setType(StreamRuleType.PRESENCE); rule.setInverted(true); Message message = getSampleMessage()...
@Override public List<TimelineEntity> getContainerEntities( ApplicationId appId, String fields, Map<String, String> filters, long limit, String fromId) throws IOException { String path = PATH_JOINER.join("clusters", clusterId, "apps", appId, "entities", YARN_CONTAINER); if (fields =...
@Test void testGetContainersForAppAttempt() throws Exception { ApplicationId appId = ApplicationId.fromString("application_1234_0001"); List<TimelineEntity> entities = client.getContainerEntities(appId, null, ImmutableMap.of("infofilters", appAttemptInfoFilter), 0, null); assertEquals(2, e...
@Override public void execute(Exchange exchange) throws SmppException { SubmitSm[] submitSms = createSubmitSm(exchange); List<String> messageIDs = new ArrayList<>(submitSms.length); String messageID = null; for (int i = 0; i < submitSms.length; i++) { SubmitSm submitSm =...
@Test public void bodyWithLatin1DataCodingNarrowedToCharset() throws Exception { final byte dataCoding = (byte) 0x03; /* ISO-8859-1 (Latin1) */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', ...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvWithCarriageReturnAtEnd() { CharSequence value = "testing\r"; CharSequence expected = "\"testing\r\""; escapeCsv(value, expected); }
@Override public <OUT> NonKeyedPartitionStream<OUT> fromSource(Source<OUT> source, String sourceName) { if (source instanceof WrappedSource) { org.apache.flink.api.connector.source.Source<OUT, ?, ?> innerSource = ((WrappedSource<OUT>) source).getWrappedSource(); f...
@Test void testFromSource() { ExecutionEnvironmentImpl env = new ExecutionEnvironmentImpl( new DefaultExecutorServiceLoader(), new Configuration(), null); NonKeyedPartitionStream<Integer> source = env.fromSource( DataStr...
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (isEnabled()) return super.onInterceptTouchEvent(ev); else return false; }
@Test public void onInterceptTouchEventDisabled() throws Exception { mUnderTest.setEnabled(false); Assert.assertFalse( mUnderTest.onInterceptTouchEvent( MotionEvent.obtain(10, 10, MotionEvent.ACTION_DOWN, 1f, 1f, 0))); }
@Override public synchronized Set<InternalNode> getResourceManagers() { return resourceManagers; }
@Test public void testGetResourceManagers() { DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, workerNodeInfo, new NoOpFailureDetector(), Optional.of(host -> false), expectedVersion, testHttpClient, new TestingDriftClient<>(), internalCommunicationConfig); try { asse...
@Override public int addListener(StatusListener listener) { RFuture<Integer> future = addListenerAsync(listener); return commandExecutor.get(future.toCompletableFuture()); }
@Test public void testReattachPatternTopicListenersOnClusterFailover() { withNewCluster((nodes2, redisson) -> { RedisCluster nodes = redisson.getRedisNodes(RedisNodes.CLUSTER); for (RedisClusterMaster master : nodes.getMasters()) { master.setConfig("notify-keyspace-ev...
@ApiOperation(value = "Delete entity view (deleteEntityView)", notes = "Delete the EntityView object based on the provided entity view id. " + TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('TENANT_ADMIN')") @RequestMapping(value = "/entityView/{entityViewId}", method = ...
@Test public void testDeleteEntityView() throws Exception { EntityView view = getNewSavedEntityView("Test entity view"); Customer customer = doPost("/api/customer", getNewCustomer("My customer"), Customer.class); view.setCustomerId(customer.getId()); EntityView savedView = doPost("/a...
static public String map2String(final Map<String, String> tags) { if(tags != null && !tags.isEmpty()) { StringJoiner joined = new StringJoiner(","); for (Object o : tags.entrySet()) { Map.Entry pair = (Map.Entry) o; joined.add(pair.getKey() + "=" + pair.ge...
@Test public void testMap2String() { Map<String, String> map = new LinkedHashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); Assert.assertEquals("key1=value1,key2=value2,key3=value3", InfluxDbPoint.map2String(map)); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testNugetconfAnalysis() throws Exception { try (Engine engine = new Engine(getSettings())) { File file = BaseTest.getResourceAsFile(this, "nugetconf/packages.config"); Dependency toScan = new Dependency(file); NugetconfAnalyzer analyzer = new NugetconfA...
@Override public String resourceNamePrefix() { return appId(); }
@Test void testResourceNamePrefix() { // Resource prefix shall be deterministic per SparkApp per attempt SparkConf sparkConf = new SparkConf(); sparkConf.set("foo", "bar"); sparkConf.set("spark.executor.instances", "1"); String appId = UUID.randomUUID().toString(); SparkAppDriverConf sparkAppD...
public boolean delete(PageId pageId, boolean isTemporary) { if (mState.get() != READ_WRITE) { Metrics.DELETE_NOT_READY_ERRORS.inc(); Metrics.DELETE_ERRORS.inc(); return false; } ReadWriteLock pageLock = getPageLock(pageId); try (LockResource r = new LockResource(pageLock.writeLock())) ...
@Test public void deleteNotExist() throws Exception { assertFalse(mCacheManager.delete(PAGE_ID1)); }
public MetricsBuilder prometheus(PrometheusConfig prometheus) { this.prometheus = prometheus; return getThis(); }
@Test void prometheus() { PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); exporter.setEnabled(true); exporter.setEnableHttpServiceDiscovery(true); exporter.setHttpServiceDiscoveryUrl("localhost:8080"); PrometheusConfig.Pushgateway pushGateway = new Prom...
protected boolean isPassed() { return !agentHealthHolder.hasLostContact(); }
@Test void shouldReturnFalseIfAgentHasLostContact() { AgentHealthHolder mock = mock(AgentHealthHolder.class); when(mock.hasLostContact()).thenReturn(true); IsConnectedToServerV1 handler = new IsConnectedToServerV1(mock); assertThat(handler.isPassed()).isFalse(); }
static Point map(MeasurementInfo info, Instant timestamp, Gauge<?> gauge) { Point.Builder builder = builder(info, timestamp); Object value = gauge.getValue(); if (value instanceof Number) { builder.addField("value", (Number) value); } else { builder.addField("valu...
@Test void testMapMeter() { Meter meter = new TestMeter(); verifyPoint(MetricMapper.map(INFO, TIMESTAMP, meter), "count=100", "rate=5.0"); }
public void unlockAndDestroy() { if (this.destroyed) { return; } this.destroyed = true; unlock(); }
@Test public void testUnlockAndDestroy() throws Exception { AtomicInteger lockSuccess = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(10); this.id.lock(); for (int i = 0; i < 10; i++) { new Thread() { @Override public void...
@Override public TopologyCluster getCluster(Topology topology, ClusterId clusterId) { checkNotNull(clusterId, CLUSTER_ID_NULL); return defaultTopology(topology).getCluster(clusterId); }
@Test public void testGetCluster() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topo...
static boolean isModern(Class<? extends LoadStatistics> clazz) { // cannot use Util.isOverridden as these are protected methods. boolean hasGetNodes = false; boolean hasMatches = false; while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) { i...
@Test public void isModernWorks() { assertThat(LoadStatistics.isModern(Modern.class), is(true)); assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false)); }
public String getJobName() { if (isBuilding()) { try { return buildLocator.split("/")[4]; } catch (ArrayIndexOutOfBoundsException e) { return null; } } return null; }
@Test public void shouldReturnTheJobName() { AgentBuildingInfo agentBuildingInfo = new AgentBuildingInfo("buildInfo", "foo/1/bar/3/job"); assertThat(agentBuildingInfo.getJobName(), is("job")); }
@Override public void write(ApiMessageAndVersion record) { if (closed) throw new ImageWriterClosedException(); records.add(record); }
@Test public void testWrite() { RecordListWriter writer = new RecordListWriter(); writer.write(testRecord(0)); writer.write(testRecord(1)); writer.close(true); assertEquals(Arrays.asList(testRecord(0), testRecord(1)), writer.records()); }
@Override public SchemaResult getKeySchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true); }
@Test public void shouldReturnErrorFromGetKeyIfUnauthorized() throws Exception { // Given: when(srClient.getSchemaBySubjectAndId(any(), anyInt())) .thenThrow(unauthorizedException()); // When: final SchemaResult result = supplier.getKeySchema(Optional.of(TOPIC_NAME), Optional.of(42), ...
public void convert(FSConfigToCSConfigConverterParams params) throws Exception { validateParams(params); this.clusterResource = getClusterResource(params); this.convertPlacementRules = params.isConvertPlacementRules(); this.outputDirectory = params.getOutputDirectory(); this.rulesToFile = para...
@Test public void testFairSchedulerXmlIsNotDefinedNeitherDirectlyNorInYarnSiteXml() throws Exception { FSConfigToCSConfigConverterParams params = createParamsBuilder(YARN_SITE_XML_NO_REF_TO_FS_XML) .withClusterResource(CLUSTER_RESOURCE_STRING) .build(); expectedException.expect(...
public T result() { return result; }
@Test public void testResult() { ResultOrError<Integer> resultOrError = new ResultOrError<>(123); assertFalse(resultOrError.isError()); assertTrue(resultOrError.isResult()); assertEquals(123, resultOrError.result()); assertNull(resultOrError.error()); }
static String cleanUpPath(String path) { return PATH_DIRTY_SLASHES.matcher(path).replaceAll("/").trim(); }
@Test void testEndpointLoggerPathCleaning() { String dirtyPath = " /this//is///a/dirty//path/ "; String anotherDirtyPath = "a/l//p/h/ /a/b ///// e/t"; assertThat(DropwizardResourceConfig.cleanUpPath(dirtyPath)).isEqualTo("/this/is/a/dirty/path/"); assertThat(DropwizardResource...
@Override public Connection connect(String url, Properties info) throws SQLException { // calciteConnection is initialized with an empty Beam schema, // we need to populate it with pipeline options, load table providers, etc return JdbcConnection.initialize((CalciteConnection) super.connect(url, info)); ...
@Test public void testInternalConnect_resetAll() throws Exception { CalciteConnection connection = JdbcDriver.connect(BOUNDED_TABLE, PipelineOptionsFactory.create()); Statement statement = connection.createStatement(); assertEquals(0, statement.executeUpdate("SET runner = bogus")); assertEqual...
@SuppressWarnings("unchecked") public static void validateResponse(HttpURLConnection conn, int expectedStatus) throws IOException { if (conn.getResponseCode() != expectedStatus) { Exception toThrow; InputStream es = null; try { es = conn.getErrorStream(); Map json = JsonSer...
@Test public void testValidateResponseOK() throws IOException { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_CREATED); HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED); }
public PartitionMetadata read() { synchronized (lock) { try { try (BufferedReader reader = Files.newBufferedReader(path(), StandardCharsets.UTF_8)) { PartitionMetadataReadBuffer partitionBuffer = new PartitionMetadataReadBuffer(file.getAbsolutePath(), reader); ...
@Test public void testRead() { LogDirFailureChannel channel = Mockito.mock(LogDirFailureChannel.class); PartitionMetadataFile partitionMetadataFile = new PartitionMetadataFile(file, channel); Uuid topicId = Uuid.randomUuid(); partitionMetadataFile.record(topicId); partitionM...
@Override public boolean checkExists(String path) { try { if (client.checkExists().forPath(path) != null) { return true; } } catch (Exception ignored) { } return false; }
@Test void testCreateContent4Persistent() { String path = "/curatorTest4CrContent/content.data"; String content = "createContentTest"; curatorClient.delete(path); assertThat(curatorClient.checkExists(path), is(false)); assertNull(curatorClient.getContent(path)); cura...
@Override public TimeSlot apply(TimeSlot timeSlot, SegmentInMinutes segmentInMinutes) { int segmentInMinutesDuration = segmentInMinutes.value(); Instant segmentStart = normalizeStart(timeSlot.from(), segmentInMinutesDuration); Instant segmentEnd = normalizeEnd(timeSlot.to(), segmentInMinute...
@Test void normalizedToTheHour() { //given Instant start = Instant.parse("2023-09-09T00:10:00Z"); Instant end = Instant.parse("2023-09-09T00:59:00Z"); TimeSlot timeSlot = new TimeSlot(start, end); SegmentInMinutes oneHour = SegmentInMinutes.of(60, FIFTEEN_MINUTES_SEGMENT_DURA...
public static RemoteCall<TransactionReceipt> sendFunds( Web3j web3j, Credentials credentials, String toAddress, BigDecimal value, Convert.Unit unit) throws InterruptedException, IOException, TransactionException { TransactionManager transa...
@Test public void testSendFunds() throws Exception { assertEquals( sendFunds(SampleKeys.CREDENTIALS, ADDRESS, BigDecimal.TEN, Convert.Unit.ETHER), (transactionReceipt)); }
public List<String> getAllowsToSignUpEnabledIdentityProviders() { if (managedInstanceService.isInstanceExternallyManaged()) { return emptyList(); } return identityProviderRepository.getAllEnabledAndSorted() .stream() .filter(IdentityProvider::isEnabled) .filter(IdentityProvider::allo...
@Test public void getAllowsToSignUpEnabledIdentityProviders_whenDefined_shouldReturnOnlyEnabled() { mockIdentityProviders(List.of( new TestIdentityProvider().setKey("saml").setName("Okta").setEnabled(true).setAllowsUsersToSignUp(true), new TestIdentityProvider().setKey("github").setName("GitHub").setE...
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed!"); return; } final List<ViewWidgetLimitMigration> widgetLimitMigrations = StreamSupport.stream(this.views.find().spliterator(),...
@Test @MongoDBFixtures("V20230113095300_MigrateGlobalPivotLimitsToGroupingsInViewsTest_null_limits.json") void migratingPivotsWithNullLimits() { this.migration.upgrade(); assertThat(migrationCompleted().migratedViews()).isEqualTo(1); final Document document = this.collection.find().fir...
@Override public MutableTreeRootHolder setRoots(Component root, Component reportRoot) { checkState(this.root == null, "root can not be set twice in holder"); this.root = requireNonNull(root, "root can not be null"); this.extendedTreeRoot = requireNonNull(reportRoot, "extended tree root can not be null"); ...
@Test public void setRoots_throws_NPE_if_root_is_null() { assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) .isInstanceOf(NullPointerException.class) .hasMessage("root can not be null"); }
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public HistoryInfo get() { return getHistoryInfo(); }
@Test public void testHS() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("history") .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, respo...
public RandomForest prune(DataFrame test) { Model[] forest = Arrays.stream(models).parallel() .map(model -> new Model(model.tree.prune(test, formula, classes), model.metrics)) .toArray(Model[]::new); // The tree weight and OOB metrics are still the old one // as ...
@Test public void testPrune() { System.out.println("prune"); // Overfitting with very large maxNodes and small nodeSize RandomForest model = RandomForest.fit(USPS.formula, USPS.train, 200, 16, SplitRule.GINI, 20, 2000, 1, 1.0, null, Arrays.stream(seeds)); double[] importance = mode...
@Override public void updatePost(PostSaveReqVO updateReqVO) { // 校验正确性 validatePostForCreateOrUpdate(updateReqVO.getId(), updateReqVO.getName(), updateReqVO.getCode()); // 更新岗位 PostDO updateObj = BeanUtils.toBean(updateReqVO, PostDO.class); postMapper.updateById(updateObj); ...
@Test public void testValidatePost_codeDuplicateForUpdate() { // mock 数据 PostDO postDO = randomPostDO(); postMapper.insert(postDO); // mock 数据:稍后模拟重复它的 code PostDO codePostDO = randomPostDO(); postMapper.insert(codePostDO); // 准备参数 PostSaveReqVO reqVO ...
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) { checkBackupLevel(backupUser, BackupLevel.MEDIA); return Mono // Figure out how many objects we're allowed to copy, updating the quota usage for the amount we are allowed .fromFuture(enf...
@Test public void copyPartialSuccess() { final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupLevel.MEDIA); final List<CopyParameters> toCopy = List.of( new CopyParameters(3, "success", 100, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)), new CopyPara...
public static Builder newBuilder() { return new Builder(); }
@Test public void fail_if_malformed_URL() { assertThatThrownBy(() -> newBuilder().url("wrong URL").build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Malformed URL: 'wrong URL'"); }
public void delete(boolean drainQueue) { addTask(TbQueueConsumerManagerTask.delete(drainQueue)); }
@Test public void testDelete_singleConsumer() { queue.setConsumerPerPartition(false); consumerManager.init(queue); Set<TopicPartitionInfo> partitions = createTpis(1, 2); consumerManager.update(partitions); TestConsumer consumer = getConsumer(); verifySubscribedAndLaun...
@Override public Server build(Environment environment) { printBanner(environment.getName()); final ThreadPool threadPool = createThreadPool(environment.metrics()); final Server server = buildServer(environment.lifecycle(), threadPool); final Handler applicationHandler = createAppServ...
@Test void configuresDumpAfterStart() { http.setDumpAfterStart(true); assertThat(http.build(environment).isDumpAfterStart()).isTrue(); }
public final void contains(@Nullable Object element) { if (!Iterables.contains(checkNotNull(actual), element)) { List<@Nullable Object> elementList = newArrayList(element); if (hasMatchingToStringPair(actual, elementList)) { failWithoutActual( fact("expected to contain", element), ...
@Test public void iterableContainsWithNull() { assertThat(asList(1, null, 3)).contains(null); }
public static String toChecksumAddress(String address) { String lowercaseAddress = Numeric.cleanHexPrefix(address).toLowerCase(); String addressHash = Numeric.cleanHexPrefix(Hash.sha3String(lowercaseAddress)); StringBuilder result = new StringBuilder(lowercaseAddress.length() + 2); res...
@Test public void testToChecksumAddress() { // Test cases as per https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md#test-cases assertEquals( Keys.toChecksumAddress("0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359"), ("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359"))...
public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length) { checkNotNull(a, "a"); checkNotNull(b, "b"); // All indexes and lengths must be non-negative checkPositiveOrZero(aStartIndex, "aStartIndex"); checkPositiveOrZero(bStartIndex, "bStart...
@Test public void notEqualsBufferUnderflow() { final byte[] b1 = new byte[8]; final byte[] b2 = new byte[16]; Random rand = new Random(); rand.nextBytes(b1); rand.nextBytes(b2); final int iB1 = b1.length / 2; final int iB2 = iB1 + b1.length; final int ...
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { if (!TbJsonPathNodeConfiguration.DEFAULT_JSON_PATH.equals(this.jsonPathValue)) { try { Object jsonPathData = jsonPath.read(msg.getData(), this.configurationJso...
@Test void givenNoResultsForPath_whenOnMsg_thenTellFailure() throws Exception { String data = "{\"Attribute_1\":22.5,\"Attribute_5\":10.3}"; JsonNode dataNode = JacksonUtil.toJsonNode(data); TbMsg msg = getTbMsg(deviceId, dataNode.toString()); node.onMsg(ctx, msg); ArgumentC...
@Override public LifecycleConfiguration getConfiguration(final Path file) throws BackgroundException { final Path bucket = containerService.getContainer(file); if(file.getType().contains(Path.Type.upload)) { return LifecycleConfiguration.empty(); } try { final...
@Test public void testGetConfiguration() throws Exception { final LifecycleConfiguration configuration = new S3LifecycleConfiguration(session).getConfiguration( new Path("test-lifecycle-us-east-1-cyberduck", EnumSet.of(Path.Type.directory)) ); assertEquals(30, configuration.getEx...
public List<? extends Coder<?>> getElementCoders() { return elementCoders; }
@Test public void testGetElementCoders() { UnionCoder unionCoder = UnionCoder.of(ImmutableList.of(StringUtf8Coder.of(), DoubleCoder.of())); assertThat(unionCoder.getElementCoders().get(0), Matchers.equalTo(StringUtf8Coder.of())); assertThat(unionCoder.getElementCoders().get(1), Matchers.equalTo(DoubleCode...
public static Map<String, Object> decryptMap(Map<String, Object> map) { decryptNode(map); return map; }
@Test public void testDecryptMap() { Map<String, Object> secretMap = Config.getInstance().getJsonMapConfig("secret"); DecryptUtil.decryptMap(secretMap); Assert.assertEquals("password", secretMap.get("serverKeystorePass")); }
public void submit(Zombie zombie) { Task<?> reapTask = zombie.reap().onFailure(e -> { if (ZKUtil.isRecoverable(e)) { submit(zombie); } else { LOG.error("failed to delete zombie node: {}", zombie); } }); _engine.run(reapTask); }
@Test public void testReaperRetry() throws InterruptedException { final int MAX_RETRY = 3; final CountDownLatch failure = new CountDownLatch(MAX_RETRY); final CountDownLatch success = new CountDownLatch(1); Reaper.Zombie zombie = new Reaper.Zombie() { private int count = 0; @Overri...
@Override @Transactional public Product createProduct(String title, String details) { return this.productRepository.save(new Product(null, title, details)); }
@Test void createProduct_ReturnsCreatedProduct() { // given var title = "Новый товар"; var details = "Описание нового товара"; doReturn(new Product(1, "Новый товар", "Описание нового товара")) .when(this.productRepository).save(new Product(null, "Новый товар", "Описа...
@Override public List<TransferItem> normalize(final List<TransferItem> roots) { final List<TransferItem> normalized = new ArrayList<>(); for(TransferItem upload : roots) { boolean duplicate = false; for(Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext(); ) { ...
@Test public void testNormalizeLargeSet() { UploadRootPathsNormalizer n = new UploadRootPathsNormalizer(); final List<TransferItem> list = new ArrayList<>(); for(int i = 0; i < 1000; i++) { final String name = String.format("f-%d", i); list.add(new TransferItem(new Pa...
@Override public Authenticator create(KeycloakSession session) { logger.info("Trying to create {} via factory.", this.getClass().getSimpleName()); return SINGLETON; }
@Test public void testCreate() { //GIVEN CorporateEdsLoginAuthenticatorFactory factory = new CorporateEdsLoginAuthenticatorFactory(); // Mock the KeycloakSession KeycloakSession session = Mockito.mock(KeycloakSession.class); //WHEN var authenticator = factory.create...
@Override public int compareTo(VirtualPointer other) { return Long.compare(logicalOffset, other.logicalOffset); }
@Test public void testCompare() { final VirtualPointer lower = new VirtualPointer(100L); final VirtualPointer higher = new VirtualPointer(200L); assertEquals(1, higher.compareTo(lower), higher.logicalOffset + " must be greater than " + lower.logicalOffset); assertEquals(-1, lower.co...
@Override public List<SelectMappedBufferResult> getBulkCommitLogData(final long offset, final int size) { if (this.shutdown) { LOGGER.warn("message store has shutdown, so getBulkCommitLogData is forbidden"); return null; } return this.commitLog.getBulkData(offset, si...
@Test public void testGetBulkCommitLogData() { DefaultMessageStore defaultMessageStore = (DefaultMessageStore) messageStore; messageBody = new byte[2 * 1024 * 1024]; for (int i = 0; i < 10; i++) { MessageExtBrokerInner msg1 = buildMessage(); messageStore.putMessage(...
@Override public String getHttpMethod() { return HttpMethods.GET; }
@Test public void testGetHttpMethod() { Assert.assertEquals("GET", testBlobPuller.getHttpMethod()); }
@Override public Long clusterCountKeysInSlot(int slot) { MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(slot); RFuture<Long> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLUSTER_COUNTKEYSINSLOT, slot); return syncFuture(f); }
@Test public void testClusterCountKeysInSlot() { Long t = connection.clusterCountKeysInSlot(1); assertThat(t).isZero(); }
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType); return BINARY_PRO...
@Test void assertGetBinaryProtocolValueWithMySQLTypeYear() { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.YEAR), instanceOf(MySQLInt2BinaryProtocolValue.class)); }
public Object normalizeValue( ValueMetaInterface valueMeta, Object value ) throws KettleValueException { if ( valueMeta.isDate() ) { // Pass date field converted to UTC, see PDI-10836 Calendar cal = Calendar.getInstance( valueMeta.getDateFormatTimeZone() ); cal.setTime( valueMeta.getDate( value ) ...
@Test public void createDateObjectTest() throws KettleValueException, ParseException { SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class ); DateFormat dateForm...
public static String getHttpMethod(Exchange exchange, Endpoint endpoint) { // 1. Use method provided in header. Object method = exchange.getIn().getHeader(Exchange.HTTP_METHOD); if (method instanceof String) { return (String) method; } else if (method instanceof Enum) { ...
@Test public void testGetMethodQueryStringHeader() { Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getHeader(Exchange.HTTP_QUERY)).thenReturn("MyQuery"); ...
@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 testListEmptyDirectory() throws Exception { final Path directory = new BrickDirectoryFeature(session).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)), new TransferStatus()); final AttributedList<Path> list = new BrickListServi...
@Nonnull @Override public ProgressState call() { progTracker.reset(); stateMachineStep(); return progTracker.toProgressState(); }
@Test public void when_notAbleToOffer_then_offeredLater() { // When init(singletonList(entry("k", "v"))); mockSsWriter.ableToOffer = false; assertEquals(MADE_PROGRESS, sst.call()); assertEquals(0, input.remainingItems().size()); assertEquals(NO_PROGRESS, sst.call()); ...
@Override public T remove(int index) { return data.remove(index); }
@Test public void remove() { l.remove("nosuchthing"); assertEquals(3, l.size()); l.remove("B"); assertEquals(2, l.size()); assertEquals("D", l.get(0)); assertEquals("F", l.get(1)); }
@Override public String getExpression() { return null == owner ? "*" : owner.getValue() + ".*"; }
@Test void assertGetExpression() { assertThat(new ShorthandProjection(new IdentifierValue("owner"), Collections.emptyList()).getExpression(), is("owner.*")); }
public static String formatHex(byte[] bytes) { return hexFormat.formatHex(bytes); }
@Test @Parameters(method = "bytesToHexStringVectors") public void formatHexValid(byte[] bytes, String expectedHexString) { String actual = ByteUtils.formatHex(bytes); assertEquals("incorrect hex formatted string", expectedHexString, actual); }
@VisibleForTesting void addPluginsFoldersToShipFiles(Collection<Path> effectiveShipFiles) { final Optional<File> pluginsDir = PluginConfig.getPluginsDir(); pluginsDir.ifPresent(dir -> effectiveShipFiles.add(getPathFromLocalFile(dir))); }
@Test void testEnvironmentEmptyPluginsShipping() { try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) { File pluginsFolder = Paths.get( temporaryFolder.toFile().getAbsolutePath(), "s0m...
public SchemaMapping fromParquet(MessageType parquetSchema) { List<Type> fields = parquetSchema.getFields(); List<TypeMapping> mappings = fromParquet(fields); List<Field> arrowFields = fields(mappings); return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings); }
@Test public void testParquetInt96ToArrowTimestamp() { final SchemaConverter converterInt96ToTimestamp = new SchemaConverter(true); MessageType parquet = Types.buildMessage().addField(Types.optional(INT96).named("a")).named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Time...
static void clearCache() { CONSTRUCTOR_CACHE.clear(); }
@Test public void testCache() throws Exception { assertEquals(0, cacheSize()); doTestCache(); assertEquals(toConstruct.length, cacheSize()); ReflectionUtils.clearCache(); assertEquals(0, cacheSize()); }
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void reported_down_retired_node_within_transition_time_transitions_to_maintenance() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp(); final ClusterStateGenerator.Params params = fixture.generatorParams() .currentTimeInMillis(10_000) ...
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteInPredicate() { // Given: final InPredicate parsed = parseExpression("1 IN (1, 2, 3)"); when(processor.apply(parsed.getValue(), context)).thenReturn(expr1); when(processor.apply(parsed.getValueList(), context)).thenReturn(inList); // When: final Expression rewri...
public int nextInt() { return twister.nextInt(); }
@Test public void testRandomInt_int() { System.out.println("nextInt"); smile.math.Random instance = new Random(System.currentTimeMillis()); for (int i = 0; i < 1000000; i++) { int n = instance.nextInt(1000000) + 1; int result = instance.nextInt(n); assertT...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldNotThrowOnKeyColumnThatIsNotCalledRowKey() { // Given: final CreateStream statement = new CreateStream( SOME_NAME, TableElements.of(tableElement("someKey", new Type(SqlTypes.STRING), KEY_CONSTRAINT)), false, true, withProperties, false ...
public void consume(Inbox inbox) { ensureNotDone(); if (limit <= 0) { done.compareAndSet(null, new ResultLimitReachedException()); ensureNotDone(); } while (offset > 0 && inbox.poll() != null) { offset--; } for (JetSqlRow row; (row = ...
@Test public void when_queueCapacityExceeded_then_inboxNotConsumed() { initProducer(false); int numExcessItems = 2; for (int i = 0; i < QueryResultProducerImpl.QUEUE_CAPACITY + numExcessItems; i++) { inbox.queue().add(jetRow()); } producer.consume(inbox); ...
@Override public void register(long ref, String uuid, boolean file) { requireNonNull(uuid, "uuid can not be null"); Long existingRef = refsByUuid.get(uuid); if (existingRef != null) { checkArgument(ref == existingRef, "Uuid '%s' already registered under ref '%s' in repository", uuid, existingRef); ...
@Test public void register_throws_NPE_if_uuid_is_null() { assertThatThrownBy(() -> underTest.register(SOME_REF, null, true)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can not be null"); }
@Override public void verify(X509Certificate certificate, Date date) { logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal()); // Create trustAnchors final Set<TrustAnchor> trustAnchors = getTrusted().stream().map( ...
@Test public void shouldVerifyExpiredCertificateIfTestedAgainstCorrectDate() { createCertificateService( new String[] { "root.crt" }, new String[] { "intermediate.crt"}, new String[0], false ).verify(readCert("expired.crt"), new Date(1521638101000L)); }
@Override protected void processOptions(LinkedList<String> args) { CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, OPTION_QUOTA, OPTION_HUMAN, OPTION_HEADER, OPTION_QUOTA_AND_USAGE, OPTION_EXCLUDE_SNAPSHOT, OPTION_ECPOLICY, OPTION_SNAPSHOT_COUNT); cf.addOptionWithValue(OPTIO...
@Test public void processPathWithSnapshotHeader() throws Exception { Path path = new Path("mockfs:/test"); when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat); PrintStream out = mock(PrintStream.class); Count count = new Count(); count.out = out; LinkedList<String> options = new LinkedLi...
public Optional<Projection> createProjection(final ProjectionSegment projectionSegment) { if (projectionSegment instanceof ShorthandProjectionSegment) { return Optional.of(createProjection((ShorthandProjectionSegment) projectionSegment)); } if (projectionSegment instanceof ColumnProj...
@Test void assertCreateProjectionWhenProjectionSegmentInstanceOfExpressionProjectionSegment() { ExpressionProjectionSegment expressionProjectionSegment = new ExpressionProjectionSegment(0, 10, "text"); Optional<Projection> actual = new ProjectionEngine(databaseType).createProjection(expressionProjec...
public Properties translate(Properties source) { Properties hikariProperties = new Properties(); // Iterate over source Properties and translate from HZ to Hikari source.forEach((key, value) -> { String keyString = (String) key; if (PROPERTY_MAP.containsKey(keyString)) {...
@Test public void testPoolNameProperty() { Properties hzProperties = new Properties(); Properties hikariProperties = hikariTranslator.translate(hzProperties); HikariConfig hikariConfig = new HikariConfig(hikariProperties); String poolName = hikariConfig.getPoolName(); asser...
@Override @SuppressWarnings("nls") public void setConf(Configuration conf) { isInitialized = false; this.conf = conf; this.areTxnStatsSupported = MetastoreConf.getBoolVar(conf, ConfVars.HIVE_TXN_STATS_ENABLED); configureSSL(conf); PersistenceManagerProvider.updatePmfProperties(conf); assert...
@Ignore // See comment in ObjectStore.getDataSourceProps @Test public void testNonConfDatanucleusValueSet() { String key = "datanucleus.no.such.key"; String value = "test_value"; String key1 = "blabla.no.such.key"; String value1 = "another_value"; Assume.assumeTrue(System.getProperty(key) == nul...
public static String cleanKey(final String key) { return INVALID_KEY_CHARS.matcher(key).replaceAll(String.valueOf(KEY_REPLACEMENT_CHAR)); }
@Test public void testCleanKey() throws Exception { // Valid keys assertEquals("foo123", Message.cleanKey("foo123")); assertEquals("foo-bar123", Message.cleanKey("foo-bar123")); assertEquals("foo_bar123", Message.cleanKey("foo_bar123")); assertEquals("foo.bar123", Message.cle...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_contains_failure() { expectFailureWhenTestingThat(array(1.1f, INTOLERABLE_2POINT2, 3.3f)) .usingTolerance(DEFAULT_TOLERANCE) .contains(2.0f); assertFailureKeys("value of", "expected to contain", "testing whether", "but was"); assertFailureValue("expected to...
static int interpretOrdinal(int ordinal, int numTiers) { if (ordinal >= 0) { return Math.min(ordinal, numTiers - 1); } return Math.max(numTiers + ordinal, 0); }
@Test public void interpretTier() throws Exception { Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(0, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(1, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(2, 1)); Assert.assertEquals(0, DefaultSto...
@SuppressWarnings("unchecked") public static Class<? extends UuidGenerator> parseUuidGenerator(String cucumberUuidGenerator) { Class<?> uuidGeneratorClass; try { uuidGeneratorClass = Class.forName(cucumberUuidGenerator); } catch (ClassNotFoundException e) { throw new ...
@Test void parseUuidGenerator_not_a_generator() { // When IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> UuidGeneratorParser.parseUuidGenerator(String.class.getName())); // Then assertThat(exception.getMessage(), Matchers.contains...
@Override public void start() { MasterServletFilter masterServletFilter = MasterServletFilter.getInstance(); if (masterServletFilter != null) { // Probably a database upgrade. MasterSlaveFilter was instantiated by the servlet container // while spring was not completely up. // See https://ji...
@Test public void should_not_fail_if_master_filter_is_not_up() { MasterServletFilter.setInstance(null); new RegisterServletFilters(new ServletFilter[2], new HttpFilter[2]).start(); }
public synchronized long calculateObjectSize(Object obj) { // Breadth-first traversal instead of naive depth-first with recursive // implementation, so we don't blow the stack traversing long linked lists. boolean init = true; try { for (;;) { visit(obj, init); init = false; ...
@Test public void testConstantMap() { Map<Long, CompositeObject> test = new ConcurrentHashMap<>(); for (long i = 0; i < 4; i++) { test.put(i, new CompositeObject()); } long size = mObjectSizeCalculator.calculateObjectSize(test); Set<Class<?>> testSet = new HashSet<>(); testSet.add(Compos...
public int getBytes(int index, byte[] dst, int off, int len) { int count = Math.min(len, size - index); if (buf.hasArray()) { System.arraycopy(buf.array(), buf.arrayOffset() + index, dst, off, count); } else { ByteBuffer dup = buf.duplicate(); dup...
@Test public void testGetBytesOffset() { final Msg msg = initMsg(); final byte[] dst = new byte[6]; msg.getBytes(3, dst, 1, 2); assertThat(dst, is(new byte[] { 0, 3, 4, 0, 0, 0 })); }