focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void delete(final String path, final int version, final AsyncCallback.VoidCallback cb, final Object ctx) { final RetryCallback callback = new RetryCallback() { @Override protected void retry() { _log.info("Retry delete operation: path = " + path + " version = " + version); ...
@Test public void testDelete() throws NoSuchMethodException { final RetryZooKeeper rzkPartialMock = createMockObject( RetryZooKeeper.class.getMethod("zkDelete", String.class, int.class, A...
@JsonIgnore public Map<String, StepRuntimeState> decodeStepOverview(Map<String, StepTransition> runtimeDag) { AtomicLong ordinal = new AtomicLong(0); Map<Long, String> ordinalStepMap = runtimeDag.keySet().stream() .collect(Collectors.toMap(s -> ordinal.incrementAndGet(), Function.identity(...
@Test public void testDecodeStepOverview() throws Exception { WorkflowRuntimeOverview overview = loadObject( "fixtures/instances/sample-workflow-runtime-overview.json", WorkflowRuntimeOverview.class); assertFalse(overview.existsNotCreatedStep()); WorkflowInstance instance ...
static RuntimeException handleException(Throwable e) { if (e instanceof OutOfMemoryError error) { OutOfMemoryErrorDispatcher.onOutOfMemory(error); throw error; } if (e instanceof Error error) { throw error; } if (e instanceof HazelcastSerializa...
@Test(expected = Error.class) public void testHandleException_OOME() { SerializationUtil.handleException(new OutOfMemoryError()); }
public Resource getResource(Resource clusterResource) { if (percentages != null && clusterResource != null) { long memory = (long) (clusterResource.getMemorySize() * percentages[0]); int vcore = (int) (clusterResource.getVirtualCores() * percentages[1]); Resource res = Resource.newInstance(memory,...
@Test public void testGetResourceWithPercentage() { ConfigurableResource configurableResource = new ConfigurableResource(new double[] {0.5, 0.5}); assertEquals( configurableResource.getResource(clusterResource).getMemorySize(), 1024); assertEquals( configurableResource.getR...
@Override public BlueRun getLatestRun() { Run run = job.getLastBuild(); if(run instanceof FreeStyleBuild){ BlueRun blueRun = new FreeStyleRunImpl((FreeStyleBuild) run, this, organization); return new FreeStyleRunSummary(blueRun, run, this, organization); } ret...
@Test public void findModernRun() throws Exception { FreeStyleProject freestyle = Mockito.spy(j.createProject(FreeStyleProject.class, "freestyle")); FreeStyleBuild build1 = Mockito.mock(FreeStyleBuild.class); FreeStyleBuild build2 = Mockito.mock(FreeStyleBuild.class); Mockito.when(...
public static SqlPrimitiveType of(final String typeName) { switch (typeName.toUpperCase()) { case INT: return SqlPrimitiveType.of(SqlBaseType.INTEGER); case VARCHAR: return SqlPrimitiveType.of(SqlBaseType.STRING); default: try { final SqlBaseType sqlType = SqlBase...
@Test public void shouldThrowOnMapType() { // When: final Exception e = assertThrows( SchemaException.class, () -> SqlPrimitiveType.of(SqlBaseType.MAP) ); // Then: assertThat(e.getMessage(), containsString("Invalid primitive type: MAP")); }
@Override public DbEntitiesCatalog get() { final Stopwatch stopwatch = Stopwatch.createStarted(); final DbEntitiesCatalog catalog = scan(packagesToScan, packagesToExclude, chainingClassLoader); stopwatch.stop(); LOG.info("{} entities have been scanned and added to DB Entity Catalog, ...
@Test void testScansEntitiesWithDefaultReadPermissionFieldProperly() { DbEntitiesScanner scanner = new DbEntitiesScanner(new String[]{"org.graylog2.cluster"}, new String[]{}); final DbEntitiesCatalog dbEntitiesCatalog = scanner.get(); final DbEntityCatalogEntry entryByCollectionName = dbEnt...
@Override public String encrypt(final Object plainValue, final AlgorithmSQLContext algorithmSQLContext) { return digestAlgorithm.digest(plainValue); }
@Test void assertEncrypt() { assertThat(encryptAlgorithm.encrypt("test", mock(AlgorithmSQLContext.class)), is("098f6bcd4621d373cade4e832627b4f6")); }
public static RecordBuilder<Schema> record(String name) { return builder().record(name); }
@Test void record() { Schema schema = SchemaBuilder.record("myrecord").namespace("org.example").aliases("oldrecord").fields().name("f0") .aliases("f0alias").type().stringType().noDefault().name("f1").doc("This is f1").type().longType().noDefault() .name("f2").type().nullable().booleanType().boolea...
@Override public void transform(Message message, DataType fromType, DataType toType) { final Optional<ValueRange> valueRange = getValueRangeBody(message); String range = message.getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A:A").toString(); String majorDimension = message ...
@Test public void testTransformToValueRangeAutoFillColumnValues() throws Exception { Exchange inbound = new DefaultExchange(camelContext); inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A1:C2"); List<String> model = Arrays.asList("{" + ...
private static boolean canSatisfyConstraints(ApplicationId appId, PlacementConstraint constraint, SchedulerNode node, AllocationTagsManager atm, Optional<DiagnosticsCollector> dcOpt) throws InvalidAllocationTagsQueryException { if (constraint == null) { LOG.debug("Constraint is found e...
@Test public void testRackAntiAffinityAssignment() throws InvalidAllocationTagsQueryException { AllocationTagsManager tm = new AllocationTagsManager(rmContext); PlacementConstraintManagerService pcm = new MemoryPlacementConstraintManager(); // Register App1 with anti-affinity constraint map ...
@VisibleForTesting boolean isOAuth2Auth(@Nullable Credential credential) { return credential != null && credential.isOAuth2RefreshToken(); }
@Test public void isOAuth2Auth_oauth2() { Credential credential = Credential.from("<token>", "oauth2_token"); Assert.assertTrue(registryAuthenticator.isOAuth2Auth(credential)); }
public void prioritize(T element) { final Iterator<T> iterator = deque.iterator(); // Already prioritized? Then, do not reorder elements. for (int i = 0; i < numPriorityElements && iterator.hasNext(); i++) { if (iterator.next() == element) { return; } ...
@Test void testPrioritize() { final PrioritizedDeque<Integer> deque = new PrioritizedDeque<>(); deque.add(0); deque.add(1); deque.add(2); deque.add(3); deque.prioritize(3); assertThat(deque.asUnmodifiableCollection()).containsExactly(3, 0, 1, 2); }
@Override public Dataset<Row> apply( final JavaSparkContext jsc, final SparkSession sparkSession, final Dataset<Row> rowDataset, final TypedProperties props) { final String sqlFile = getStringWithAltKeys(props, SqlTransformerConfig.TRANSFORMER_SQL_FILE); final FileSystem fs = HadoopF...
@Test public void testSqlFileBasedTransformerInvalidSQL() throws IOException { UtilitiesTestBase.Helpers.copyToDFS( "streamer-config/sql-file-transformer-invalid.sql", UtilitiesTestBase.storage, UtilitiesTestBase.basePath + "/sql-file-transformer-invalid.sql"); // Test if the SQL file...
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testIsNullOperand() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); SearchArgument arg = builder.startAnd().isNull("salary", PredicateLeaf.Type.LONG).end().build(); UnboundPredicate expected = Expressions.isNull("salary"); UnboundPredicate actual = (Un...
@Override public String toString() { return getClass().getSimpleName() + "." + root.getLocalName() + "(id=" + id + ")"; }
@Test public void testAllowAndDisallowSnapshot() throws Exception { final Path dir = new Path("/dir"); final Path file0 = new Path(dir, "file0"); final Path file1 = new Path(dir, "file1"); DFSTestUtil.createFile(hdfs, file0, BLOCKSIZE, REPLICATION, seed); DFSTestUtil.createFile(hdfs, file1, BLOCKS...
public static boolean isWebService(Optional<String> serviceName) { return serviceName.isPresent() && IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey( Ascii.toLowerCase(serviceName.get())); }
@Test public void isWebService_whenHasAtLeastOneHttpMethod_returnsTrue() { assertThat( NetworkServiceUtils.isWebService( NetworkService.newBuilder() .setServiceName("irrelevantService") .addSupportedHttpMethods("IrrelevantMethodName") ...
@Override public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) { return getSqlRecordIteratorBatch(value, descending, null); }
@Test public void getRecordsUsingExactValueInequalityAscending() { var expectedOrder = List.of(1, 4, 7, 2, 5, 8); var actual = store.getSqlRecordIteratorBatch(Comparison.GREATER, 0, false); assertResult(expectedOrder, actual); }
@Override public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) { log.debug( "sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}", catalogueTree, sortTypeEnum); return recursionSortCatalogues...
@Test public void sortEmptyTest() { List<Catalogue> catalogueTree = Lists.newArrayList(); SortTypeEnum sortTypeEnum = SortTypeEnum.ASC; List<Catalogue> resultList = catalogueTreeSortCreateTimeStrategyTest.sort(catalogueTree, sortTypeEnum); assertEquals(Lists.newArrayList(), resultLi...
public static <Req extends RpcRequest> Matcher<Req> serviceEquals(String service) { if (service == null) throw new NullPointerException("service == null"); if (service.isEmpty()) throw new NullPointerException("service is empty"); return new RpcServiceEquals<Req>(service); }
@Test void serviceEquals_unmatched_null() { assertThat(serviceEquals("grpc.health.v1.Health").matches(request)).isFalse(); }
@Override public void register(@NonNull ThreadPoolPlugin plugin) { mainLock.runWithWriteLock(() -> { String id = plugin.getId(); Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered"); registeredPlugins.put(id, plugin); forQuic...
@Test public void testGetAllPluginRuntimes() { manager.register(new TestExecuteAwarePlugin()); manager.register(new TestRejectedAwarePlugin()); Assert.assertEquals(2, manager.getAllPluginRuntimes().size()); }
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 testGetBytesLength() { final Msg msg = initMsg(); final byte[] dst = new byte[5]; msg.getBytes(2, dst, 0, 2); assertThat(dst, is(new byte[] { 2, 3, 0, 0, 0 })); }
public static InetAddress getLocalhost() { final LinkedHashSet<InetAddress> localAddressList = localAddressList(address -> { // 非loopback地址,指127.*.*.*的地址 return false == address.isLoopbackAddress() // 需为IPV4地址 && address instanceof Inet4Address; }); if (CollUtil.isNotEmpty(localAddressList)) { I...
@Test public void getLocalHostTest() { assertNotNull(NetUtil.getLocalhost()); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test public void testMoveOverrideFile() throws Exception { final DeepboxIdProvider fileid = new DeepboxIdProvider(session); final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path trash = new Path("/...
@Override public long estimate() { final double raw = (1 / computeE()) * alpha() * m * m; return applyRangeCorrection(raw); }
@RequireAssertEnabled @Test(expected = AssertionError.class) public void testAlpha_withGivenZeroAsInvalidMemoryFootprint() { DenseHyperLogLogEncoder encoder = new DenseHyperLogLogEncoder(0); encoder.estimate(); }
public static void main(String[] args) { App app = new App(App.REST_API_URL, HttpClient.newHttpClient()); app.createDynamicProxy(); app.callMethods(); }
@Test void shouldRunAppWithoutExceptions() { assertDoesNotThrow(() -> App.main(null)); }
@Override @Nullable public Object convert(@Nullable String value) { if (isNullOrEmpty(value)) { return null; } LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone); final DateTimeFormatter form...
@Test public void testBasicConvert() throws Exception { final DateConverter converter = new DateConverter(config("YYYY MMM dd HH:mm:ss", null, null)); final DateTime result = (DateTime) converter.convert("2013 Aug 15 23:15:16"); assertThat(result) .isNotNull() ...
public RegistryBuilder appendParameters(Map<String, String> appendParameters) { this.parameters = appendParameters(parameters, appendParameters); return getThis(); }
@Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); RegistryBuilder builder = new RegistryBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.buil...
@SuppressWarnings("unchecked") public Output run(RunContext runContext) throws Exception { Logger logger = runContext.logger(); try (HttpClient client = this.client(runContext, this.method)) { HttpRequest<String> request = this.request(runContext); HttpResponse<String> respo...
@Test void run() throws Exception { try ( ApplicationContext applicationContext = ApplicationContext.run(); EmbeddedServer server = applicationContext.getBean(EmbeddedServer.class).start(); ) { Request task = Request.builder() .id(RequestTest.clas...
public VersionMatchResult matches(DeploymentInfo info) { // Skip if no manifest configuration if(info.getManifest() == null || info.getManifest().size() == 0) { return VersionMatchResult.SKIPPED; } for (ManifestInfo manifest: info.getManifest()) { Versio...
@Test public void testSkipped() throws IOException { Set<MavenInfo> maven = new HashSet<MavenInfo>(); ManifestInfo manifest = new ManifestInfo(new java.util.jar.Manifest(this.getClass().getResourceAsStream("/org/hotswap/agent/versions/matcher/TEST.MF"))); DeploymentInfo info = new Deployme...
@Override public Iterable<MappingEntry> getMappingEntries(Type type, DeviceId deviceId) { return store.getMappingEntries(type, deviceId); }
@Test public void getMappingEntries() { assertTrue("Store should be empty", Sets.newHashSet( service.getMappingEntries(MAP_DATABASE, LISP_DID)).isEmpty()); addMapping(MAP_DATABASE, 1); addMapping(MAP_DATABASE, 2); assertEquals("2 mappings should exist", 2, mappingCou...
public void registerClient(SonarLintClient sonarLintClient) { clients.add(sonarLintClient); sonarLintClient.scheduleHeartbeat(); sonarLintClient.addListener(new SonarLintClientEventsListener(sonarLintClient)); LOG.debug("Registering new SonarLint client"); }
@Test public void registerClient_whenCalledFirstTime_addsAsyncListenerToClient() { SonarLintClient client = mock(SonarLintClient.class); underTest.registerClient(client); verify(client).addListener(any()); }
public void updateConnection(Connection connection) { if (connection != null) { connectionRepository.saveAndFlush(connection); cacheService.evictRelatedCacheValues("metadata-response", connection.getEntityId()); cacheService.evictSingleCacheValue("metadata", connection.getEn...
@Test void updateConnection() { connectionServiceMock.updateConnection(new Connection()); verify(connectionRepositoryMock, times(1)).saveAndFlush(any(Connection.class)); }
@Override public final BootstrapConfig config() { return config; }
@Test public void optionsAndAttributesMustBeAvailableOnChannelInit() throws InterruptedException { final AttributeKey<String> key = AttributeKey.valueOf(UUID.randomUUID().toString()); new Bootstrap() .group(groupA) .channel(LocalChannel.class) .option(...
public void notify(DashboardNotification e) { notificationMappers.stream() .filter(notificationMapper -> notificationMapper.supports(e)) .map(notificationMapper -> notificationMapper.map(e)) .forEach(this::saveDashboardNotificationAsMetadata); }
@Test void notifyForCpuAllocationIrregularityShouldSaveJobRunrMetadataToStorageProvider() { dashboardNotificationManager.notify(new CpuAllocationIrregularityNotification(11)); verify(storageProviderMock).saveMetadata(jobRunrMetadataToSaveArgumentCaptor.capture()); assertThat(jobRunrMetadat...
@Udf public boolean check(@UdfParameter(description = "The input JSON string") final String input) { if (input == null) { return false; } try { return !UdfJsonMapper.parseJson(input).isMissingNode(); } catch (KsqlFunctionException e) { return false; } }
@Test public void shouldInterpretString() { assertTrue(udf.check("\"abc\"")); }
public String format(List<String> args) { // https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands // XTerm accepts either BEL or ST for terminating OSC // sequences, and when returning information, uses the same // terminator used in a query. ret...
@Test public void formatUsingSameTerminator() { var seq1 = create("2;Test 1" + BEL_CHAR); assertEquals(ESC_CHAR + "]foo" + BEL_CHAR, seq1.format(List.of("foo"))); var seq2 = create("2;Test 1" + TWO_BYTES_TERMINATOR); assertEquals(ESC_CHAR + "]bar;baz" + TWO_BYTES_TERMINATOR, seq2.for...
@Override public int inferParallelism(Context dynamicParallelismContext) { FileEnumerator fileEnumerator; List<HiveTablePartition> partitions; if (dynamicFilterPartitionKeys != null) { fileEnumerator = new HiveSourceDynamicFileEnumerator.Provider( ...
@Test void testDynamicParallelismInferenceWithLimit() throws Exception { ObjectPath tablePath = new ObjectPath("default", "hiveTbl2"); createTable(tablePath, hiveCatalog, true); HiveSource<RowData> hiveSource = createHiveSourceWithPartition(tablePath, new Configuration(), 1L...
@Override public InputStream open(String path) throws IOException { try (InputStream in = delegate.open(path)) { final String config = new String(in.readAllBytes(), StandardCharsets.UTF_8); final String substituted = substitutor.replace(config); return new ByteArrayInput...
@Test void shouldNotBeVulnerableToCVE_2022_42889() throws IOException { StringLookup dummyLookup = (x) -> null; SubstitutingSourceProvider provider = new SubstitutingSourceProvider(new DummySourceProvider(), new StringSubstitutor(dummyLookup)); assertThat(provider.open("foo: ${script:javasc...
@Override public String toString() { return "path:'" + getPath() + "'|param:'" + getParamName() + "'|mimetype:'" + getMimeType() + "'"; }
@Test public void testToString() throws Exception { HTTPFileArg file = new HTTPFileArg("path1", "param1", "mimetype1"); assertEquals("path:'path1'|param:'param1'|mimetype:'mimetype1'", file.toString()); }
@SuppressWarnings({"rawtypes", "unchecked"}) public static <T> int compare(T c1, T c2, Comparator<T> comparator) { if (null == comparator) { return compare((Comparable) c1, (Comparable) c2); } return comparator.compare(c1, c2); }
@Test public void compareTest(){ int compare = CompareUtil.compare(null, "a", true); assertTrue(compare > 0); compare = CompareUtil.compare(null, "a", false); assertTrue(compare < 0); }
public static List<InetSocketAddress> getIpListByRegistry(String registryIp) { List<String[]> ips = new ArrayList<String[]>(); String defaultPort = null; String[] srcIps = registryIp.split(","); for (String add : srcIps) { int a = add.indexOf("://"); if (a > -1) ...
@Test public void getIpListByRegistry() throws Exception { }
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testStableName() { DoFnInvoker<Void, Void> invoker = DoFnInvokers.invokerFor(new StableNameTestDoFn()); assertThat( invoker.getClass().getName(), equalTo( String.format( "%s$%s", StableNameTestDoFn.class.getName(), DoFnInvoker.class.getSimpleName()...
@Override public MutableNetwork<Node, Edge> apply(MapTask mapTask) { List<ParallelInstruction> parallelInstructions = Apiary.listOrEmpty(mapTask.getInstructions()); MutableNetwork<Node, Edge> network = NetworkBuilder.directed() .allowsSelfLoops(false) .allowsParallelEdges(true)...
@Test public void testParallelEdgeFlatten() { // /---\ // Read --> Read.out --> Flatten // \---/ InstructionOutput readOutput = createInstructionOutput("Read.out"); ParallelInstruction read = createParallelInstruction("Read", readOutput); read.setRead(new Read...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldInsertWrappedSingleField() { // Given: givenSourceStreamWithSchema(SINGLE_VALUE_COLUMN_SCHEMA, SerdeFeatures.of(), SerdeFeatures.of()); final ConfiguredStatement<InsertValues> statement = givenInsertValues( valueColumnNames(SINGLE_VALUE_COLUMN_SCHEMA), ImmutableLis...
@Override public Optional<String> getValue(Object arg, String type) { if (arg instanceof List) { List<?> list = (List<?>) arg; int index = Integer.parseInt(getKey(type)); if (index < 0 || index >= list.size()) { return Optional.empty(); } ...
@Test public void testValue() { TypeStrategy strategy = new ListTypeStrategy(); List<String> list = new ArrayList<>(); list.add("foo"); list.add(null); // normal Assert.assertEquals("foo", strategy.getValue(list, ".get(0)").orElse(null)); // test null ...
public Span nextSpan(TraceContextOrSamplingFlags extracted) { if (extracted == null) throw new NullPointerException("extracted == null"); TraceContext context = extracted.context(); if (context != null) return newChild(context); TraceIdContext traceIdContext = extracted.traceIdContext(); if (traceI...
@Test void localRootId_nextSpan_ids_notYetSampled() { TraceIdContext context1 = TraceIdContext.newBuilder().traceId(1).build(); TraceIdContext context2 = TraceIdContext.newBuilder().traceId(2).build(); localRootId(context1, context2, ctx -> tracer.nextSpan(ctx)); }
@Override public int run(String[] argv) { if (argv.length < 1) { printUsage(""); return -1; } int exitCode = -1; int i = 0; String cmd = argv[i++]; // // verify that we have enough command line parameters // if ("-safemode".equals(cmd)) { if (argv.length != 2) ...
@Test public void testAllowDisallowSnapshot() throws Exception { final Path dirPath = new Path("/ssdir1"); final Path trashRoot = new Path(dirPath, ".Trash"); final DistributedFileSystem dfs = cluster.getFileSystem(); final DFSAdmin dfsAdmin = new DFSAdmin(conf); dfs.mkdirs(dirPath); assertEq...
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { final int frameSizeValueLength = findFrameSizeValueLength(buffer); // We have not found the frame length value byte size yet. if (frameSizeValueLength <= 0) { return; ...
@Test public void testDecode() throws Exception { final ByteBuf buf1 = Unpooled.copiedBuffer("123 <45>1 2014-10-21T10:21:09+00:00 c4dc57ba1ebb syslog-ng 7120 - [meta sequenceId=\"1\"] syslog-ng starting up; version='3.5.3'\n", StandardCharsets.US_ASCII); final ByteBuf buf2 = Unpooled.copiedBuffer("1...
@Override public void updateArticleCategory(ArticleCategoryUpdateReqVO updateReqVO) { // 校验存在 validateArticleCategoryExists(updateReqVO.getId()); // 更新 ArticleCategoryDO updateObj = ArticleCategoryConvert.INSTANCE.convert(updateReqVO); articleCategoryMapper.updateById(updateO...
@Test public void testUpdateArticleCategory_success() { // mock 数据 ArticleCategoryDO dbArticleCategory = randomPojo(ArticleCategoryDO.class); articleCategoryMapper.insert(dbArticleCategory);// @Sql: 先插入出一条存在的数据 // 准备参数 ArticleCategoryUpdateReqVO reqVO = randomPojo(ArticleCate...
@Override public Output run(RunContext runContext) throws Exception { URI from = new URI(runContext.render(this.from)); final PebbleExpressionPredicate predicate = getExpressionPredication(runContext); final Path path = runContext.workingDir().createTempFile(".ion"); long processe...
@Test void shouldFilterWithNotMatchGivenNonBooleanValue() throws Exception { // Given RunContext runContext = runContextFactory.of(); FilterItems task = FilterItems .builder() .from(generateKeyValueFile(TEST_VALID_ITEMS, runContext).toString()) .filterCon...
public static String prependHexPrefix(String input) { if (!containsHexPrefix(input)) { return HEX_PREFIX + input; } else { return input; } }
@Test public void testPrependHexPrefix() { assertEquals(Numeric.prependHexPrefix(""), ("0x")); assertEquals(Numeric.prependHexPrefix("0x0123456789abcdef"), ("0x0123456789abcdef")); assertEquals(Numeric.prependHexPrefix("0x"), ("0x")); assertEquals(Numeric.prependHexPrefix("0123456789...
public static void writeIdlProtocol(Writer writer, Protocol protocol) throws IOException { final String protocolFullName = protocol.getName(); final int lastDotPos = protocolFullName.lastIndexOf("."); final String protocolNameSpace; if (lastDotPos < 0) { protocolNameSpace = protocol.getNamespace()...
@Test public void cannotWriteEmptyEnums() { assertThrows(AvroRuntimeException.class, () -> IdlUtils.writeIdlProtocol(new StringWriter(), Schema.createEnum("Single", null, "naming", emptyList()))); }
@Override public void onCycleComplete(com.netflix.hollow.api.producer.Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { boolean isCycleSuccess; long cycleEndTimeNano = System.nanoTime(); if (status.getType() == com.netflix.hollow.api.producer.Status.Status...
@Test public void testCycleCompleteWithFail() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void cycleMetricsReporting(CycleMetrics cycleMetrics) { Assert.assertNotNull(cycleMetrics); Assert.assert...
public Future<KafkaVersionChange> reconcile() { return getVersionFromController() .compose(i -> getPods()) .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testNewClusterWithNewProtocolVersion(VertxTestContext context) { VersionChangeCreator vcc = mockVersionChangeCreator( mockKafka(VERSIONS.defaultVersion().version(), "3.2", "2.8"), mockNewCluster(null, null, List.of()) ); Checkpoint async = c...
public static Optional<Throwable> findThrowableOfThrowableType( Throwable throwable, ThrowableType throwableType) { if (throwable == null || throwableType == null) { return Optional.empty(); } Throwable t = throwable; while (t != null) { final Throwab...
@Test void testFindThrowableOfThrowableType() { // no throwable type assertThat( ThrowableClassifier.findThrowableOfThrowableType( new Exception(), ThrowableType.RecoverableError)) .isNotPresent(); // no recoverable thr...
static PublicKey recoverPublicKey(KeyFactory kf, PrivateKey priv) throws NoSuchAlgorithmException, InvalidKeySpecException { if (priv instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey rsaPriv = (RSAPrivateCrtKey) priv; return kf.generatePublic(new RSAPublicKeySpec(rsaPriv.getModulus(), rsaPriv .getPublicE...
@Test public void recoverPublicKey_FakeKey_Failure() throws Exception { try { PubkeyUtils.recoverPublicKey(null, new MyPrivateKey()); fail("Should not accept unknown key types"); } catch (NoSuchAlgorithmException expected) { } }
@Override public HealthStatus getStatus() { if (cr.getStatus() == ComponentStatus.INITIALIZING) return HealthStatus.INITIALIZING; PartitionHandlingManager partitionHandlingManager = cr.getComponent(PartitionHandlingManager.class); if (!isComponentHealthy() || partitionHandlingManager.getAvailabili...
@Test public void testHealthyStatus() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); DistributionManager distributionManagerMock = mock(DistributionManager.class); doReturn(false).when(distributionManagerMock).isRehashInProgress(); doRetur...
@Override public LoggingConfig extract(ConfigValue<?> value) { if (value instanceof ConfigValue.NullValue) { return new LoggingConfig(Map.of("ROOT", "info")); } if (!(value instanceof ObjectValue objectValue)) { throw ConfigValueExtractionException.unexpectedValueType...
@Test void testParseConfig() { var config = MapConfigFactory.fromMap(Map.of( "logging", Map.of( "level", Map.of( "root", "info", "ru.tinkoff.package1", "debug", "ru.tinkoff.package2", "trace", "ru.tin...
static Optional<RegistryAuthenticator> fromAuthenticationMethod( String authenticationMethod, RegistryEndpointRequestProperties registryEndpointRequestProperties, @Nullable String userAgent, FailoverHttpClient httpClient) throws RegistryAuthenticationFailedException { // If the authent...
@Test public void testFromAuthenticationMethod_basic() throws RegistryAuthenticationFailedException { assertThat( RegistryAuthenticator.fromAuthenticationMethod( "Basic", registryEndpointRequestProperties, "user-agent", httpClient)) .isEmpty(); assertThat( Regi...
@PUT @Consumes("application/json") @Produces("application/json") @Path("compare") public Map<String, Object> compare(InputStream is) throws Exception { JsonNode node = null; try (BufferedReader reader = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8)...
@Test public void testBasicCompare() throws Exception { Map<String, String> request = new HashMap<>(); request.put(TikaEvalResource.ID, "1"); request.put(TikaEvalResource.TEXT_A, "the quick brown fox jumped qwertyuiop"); request.put(TikaEvalResource.TEXT_B, "the the the fast brown do...
public ClusterStatsResponse clusterStats() { return execute(() -> { Request request = new Request("GET", "/_cluster/stats"); Response response = restHighLevelClient.getLowLevelClient().performRequest(request); return ClusterStatsResponse.toClusterStatsResponse(gson.fromJson(EntityUtils.toString(re...
@Test public void should_rethrow_ex_on_cluster_stat_fail() throws Exception { when(restClient.performRequest(argThat(new RawRequestMatcher( "GET", "/_cluster/stats")))) .thenThrow(IOException.class); assertThatThrownBy(() -> underTest.clusterStats()) .isInstanceOf(ElasticsearchExcepti...
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) { if (statsEnabled) { stats.log(deviceStateServiceMsg); } stateService.onQueueMsg(deviceStateServiceMsg, callback); }
@Test public void givenProcessingSuccess_whenForwardingInactivityMsgToStateService_thenOnSuccessCallbackIsCalled() { // GIVEN var inactivityMsg = TransportProtos.DeviceInactivityProto.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantId...
@Override public void doStart() throws Exception { if (!pluginConfigService.config().getCurrent().spamhausEnabled()) { throw new AdapterDisabledException("Spamhaus service is disabled, not starting (E)DROP adapter. To enable it please go to System / Configurations."); } final Imm...
@Test public void tableStateShouldRetrieveListsSuccessfully() throws Exception { when(httpFileRetriever.fetchFileIfNotModified("https://www.spamhaus.org/drop/drop.txt")).thenReturn(Optional.of(dropSnapshot)); when(httpFileRetriever.fetchFileIfNotModified("https://www.spamhaus.org/drop/edrop.txt")).t...
@Override public Serializer getSerializer(Class cl) throws HessianProtocolException { if (GenericObject.class == cl) { return GenericObjectSerializer.getInstance(); } if (GenericArray.class == cl) { return GenericArraySerializer.getInstance(); } if ...
@Test public void getSerializer() throws Exception { GenericMultipleClassLoaderSofaSerializerFactory factory = new GenericMultipleClassLoaderSofaSerializerFactory(); Assert.assertEquals(factory.getSerializer(GenericObject.class).getClass(), GenericObjectSerializer.class); Assert.assertEquals...
public ImmutableList<Path> walk(PathConsumer pathConsumer) throws IOException { ImmutableList<Path> files = walk(); for (Path path : files) { pathConsumer.accept(path); } return files; }
@Test public void testWalk() throws IOException { new DirectoryWalker(testDir).walk(addToWalkedPaths); Set<Path> expectedPaths = new HashSet<>( Arrays.asList( testDir, testDir.resolve("a"), testDir.resolve("a").resolve("b"), ...
@Override public View onCreateInputView() { final View view = super.onCreateInputView(); // triggering a new controller creation mKeyPreviewSubject.onNext(SystemClock.uptimeMillis()); return view; }
@Test public void testNewKeyPreviewControllerOnInputViewReCreate() { simulateOnStartInputFlow(); final ArgumentCaptor<KeyPreviewsController> captor = ArgumentCaptor.forClass(KeyPreviewsController.class); Mockito.verify(mAnySoftKeyboardUnderTest.getSpiedKeyboardView()) .setKeyPreviewControl...
@Udf(description = "Adds a duration to a timestamp") public Timestamp timestampAdd( @UdfParameter(description = "A unit of time, for example DAY or HOUR") final TimeUnit unit, @UdfParameter(description = "An integer number of intervals to add") final Integer interval, @UdfParameter(description = "A ...
@Test public void addNegativeTimestamp() { // When: final Timestamp result = udf.timestampAdd(TimeUnit.MILLISECONDS, -300, new Timestamp(100)); // Then: final Timestamp expectedResult = new Timestamp(-200); assertThat(result, is(expectedResult)); }
public Map<String, Parameter> generateMergedWorkflowParams( WorkflowInstance instance, RunRequest request) { Workflow workflow = instance.getRuntimeWorkflow(); Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>(); Map<String, ParamDefinition> defaultWorkflowParams = defaultParamMa...
@Test public void testWorkflowParamRunParamsStartRestart() { Map<String, ParamDefinition> runParams = singletonMap("p1", ParamDefinition.buildParamDefinition("p1", "d1")); RunRequest request = RunRequest.builder() .initiator(new ManualInitiator()) .currentPolicy(RunPoli...
@VisibleForTesting BackupReplayFile openOrCreateReplayFile() { try { final Optional<BackupReplayFile> backupReplayFile = latestReplayFile(); if (backupReplayFile.isPresent()) { return backupReplayFile.get(); } return newReplayFile(); } catch (final IOException e) { throw ...
@Test public void shouldOpenReplayFileAndIgnoreFileWithInvalidTimestamp() throws IOException { // Given: backupLocation.newFile("backup_command_topic_111"); backupLocation.newFile("backup_command_topic_222x"); // When: final BackupReplayFile replayFile = commandTopicBackup.openOrCreateReplayFile(...
private static VerificationResult verifyChecksums(String expectedDigest, String actualDigest, boolean caseSensitive) { if (expectedDigest == null) { return VerificationResult.NOT_PROVIDED; } if (actualDigest == null) { return VerificationResult.NOT_COMPUTED; } ...
@Test public void sha1Match() throws Exception { UpdateCenter.verifyChecksums( new MockDownloadJob(EMPTY_SHA1, null, null), buildEntryWithExpectedChecksums(EMPTY_SHA1, null, null), new File("example")); }
@Override public boolean match(Message msg, StreamRule rule) { if (msg.getField(rule.getField()) == null) return rule.getInverted(); try { final Pattern pattern = patternCache.get(rule.getValue()); final CharSequence charSequence = new InterruptibleCharSequence(m...
@Test public void testNullFieldShouldNotMatch() throws Exception { final String fieldName = "nullfield"; final StreamRule rule = getSampleRule(); rule.setField(fieldName); rule.setValue("^foo"); final Message msg = getSampleMessage(); msg.addField(fieldName, null); ...
public BeaconParser setBeaconLayout(String beaconLayout) { LogManager.d(TAG, "API setBeaconLayout "+beaconLayout); mBeaconLayout = beaconLayout; Log.d(TAG, "Parsing beacon layout: "+beaconLayout); String[] terms = beaconLayout.split(","); mExtraFrame = false; // this is not an...
@Test public void testSetBeaconLayout() { byte[] bytes = hexStringToByteArray("02011a1bffbeac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509000000"); BeaconParser parser = new BeaconParser(); parser.setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"); assertEquals("par...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void test4446CyclicProp() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Ticket4446Resource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /test/test:\n" + " get:\n" + " ...
public static L3ModificationInstruction modL3Dst(IpAddress addr) { checkNotNull(addr, "Dst l3 IPv4 address cannot be null"); return new ModIPInstruction(L3SubType.IPV4_DST, addr); }
@Test public void testModL3DstMethod() { final Instruction instruction = Instructions.modL3Dst(ip41); final L3ModificationInstruction.ModIPInstruction modIPInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, L3Mo...
@Private @VisibleForTesting static void checkResourceRequestAgainstAvailableResource(Resource reqResource, Resource availableResource) throws InvalidResourceRequestException { for (int i = 0; i < ResourceUtils.getNumberOfCountableResourceTypes(); i++) { final ResourceInformation requestedRI = ...
@Test public void testCustomResourceRequestedUnitIsSameAsAvailableUnit() { Resource requestedResource = ResourceTypesTestHelper.newResource(1, 1, ImmutableMap.of("custom-resource-1", "11M")); Resource availableResource = ResourceTypesTestHelper.newResource(1, 1, ImmutableMap.of("custo...
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema == null && value == null) { return null; } JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value); ...
@Test public void longToJson() { JsonNode converted = parse(converter.fromConnectData(TOPIC, Schema.INT64_SCHEMA, 4398046511104L)); validateEnvelope(converted); assertEquals(parse("{ \"type\": \"int64\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)); ...
public float[] decodeFloat4Array(final byte[] parameterBytes, final boolean isBinary) { ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode")); String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8); Collection<String> par...
@Test void assertParseFloat4ArrayNormalTextMode() { float[] actual = DECODER.decodeFloat4Array(FLOAT_ARRAY_STR.getBytes(), false); assertThat(actual.length, is(2)); assertThat(Float.compare(actual[0], 11.1F), is(0)); assertThat(Float.compare(actual[1], 12.1F), is(0)); }
@Override public AwsProxyResponse handle(Throwable ex) { log.error("Called exception handler for:", ex); // adding a print stack trace in case we have no appender or we are running inside SAM local, where need the // output to go to the stderr. ex.printStackTrace(); if (ex i...
@Test void typedHandle_InvalidRequestEventException_responseString() throws JsonProcessingException { AwsProxyResponse resp = exceptionHandler.handle(new InvalidRequestEventException(INVALID_REQUEST_MESSAGE, null)); assertNotNull(resp); String body = objectMapper.writeValueAsStr...
@Override public boolean remove(final Object value) { return value instanceof Integer i && remove(i.intValue()); }
@Test public void removingAnElementFromAnEmptyListDoesNothing() { assertFalse(set.remove(0)); }
public static <T> T deserializeByType(Object src, Class<T> clazz) { if (src == null) { return (T) ClassUtils.getDefaultPrimitiveValue(clazz); } else if (src instanceof Boolean) { return (T) CompatibleTypeUtils.convert(src, clazz); } else if (src instanceof Number) { ...
@Test public void testDeserializeByType() { Assert.assertTrue(0 == BeanSerializer.deserializeByType(null, int.class)); Assert.assertTrue(0 == BeanSerializer.deserializeByType(null, long.class)); Assert.assertFalse(BeanSerializer.deserializeByType(null, boolean.class)); Assert.assert...
@Override public <T> List<T> stores(final String storeName, final QueryableStoreType<T> queryableStoreType) { final List<T> allStores = new ArrayList<>(); for (final StreamThreadStateStoreProvider storeProvider : storeProviders) { final List<T> stores = stor...
@Test public void shouldFindKeyValueStores() { final List<ReadOnlyKeyValueStore<String, String>> results = wrappingStoreProvider.stores("kv", QueryableStoreTypes.<String, String>keyValueStore()); assertEquals(2, results.size()); }
@SuppressWarnings("unchecked") public static <R> R getField(final Object object, final String fieldName) { try { return traverseClassHierarchy( object.getClass(), NoSuchFieldException.class, traversalClass -> { Field field = traversalClass.getDeclaredField(fieldName...
@Test public void getFieldReflectively_givesHelpfulExceptions() { ExampleDescendant example = new ExampleDescendant(); try { ReflectionHelpers.getField(example, "nonExistent"); fail("Expected exception not thrown"); } catch (RuntimeException e) { if (!e.getMessage().contains("nonExistent...
@Override public ParsedLine parse(final String line, final int cursor, final ParseContext context) { final ParsedLine parsed = delegate.parse(line, cursor, context); if (context != ParseContext.ACCEPT_LINE) { return parsed; } if (UnclosedQuoteChecker.isUnclosedQuote(line)) { throw new EO...
@Test public void shouldAcceptIfPredicateReturnsTrue() { // Given: givenPredicateWillReturnTrue(); givenDelegateWillReturn(UNTERMINATED_LINE); // When: final ParsedLine result = parser.parse("what ever", 0, ParseContext.ACCEPT_LINE); // Then: assertThat(result, is(parsedLine)); }
public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (CollectionUtils.isNotEmpty(forbid)) { List<String> newForbid = new ArrayList<>(); for (String serviceName : forbid) { if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isN...
@Test void testRevertForbid() { String service = "dubbo.test.api.HelloService"; List<String> forbid = new ArrayList<String>(); forbid.add(service); Set<URL> subscribed = new HashSet<URL>(); subscribed.add(URL.valueOf("dubbo://127.0.0.1:20880/" + service + "?group=perf&version...
@Override public long stringAppend(String path, Object value) { return get(stringAppendAsync(path, value)); }
@Test public void testStringAppend() { RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class)); TestType t = new TestType(); t.setName("name1"); al.set(t); long s1 = al.stringAppend("name", "23"); assertThat(s1).isEqualTo(7); ...
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final Optional<String> header = getBearerHeader(requestContext); if (header.isEmpty()) { // no JWT token, we'll fail immediately abortRequest(requestContext); } else { ...
@Test void verifyInvalidToken() throws IOException { final String generationKey = "gTVfiF6A0pB70A3UP1EahpoR6LId9DdNadIkYNygK5Z8lpeJIpw9vN0jZ6fdsfeuV9KIg9gVLkCHIPj6FHW5Q9AvpOoGZO3h"; final String verificationKey = "n51wcO3jn8w3JNyGgKc7k1fTCr1FWvGg7ODfQOyBT2fizBrCVsRJg2GsbYGLNejfi3QsKaqJgo3zAWMuAZhJzn...
@DeleteMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) public Object deleteUser(@RequestParam String username) { List<RoleInfo> roleInfoList = roleService.getRoles(username); if (roleInfoList != null) { for (RoleInfo roleI...
@Test void testDeleteUser2() { List<RoleInfo> roleInfoList = new ArrayList<>(1); RoleInfo testRole = new RoleInfo(); testRole.setUsername("nacos"); testRole.setRole("testRole"); roleInfoList.add(testRole); when(roleService.getRoles(anyString())).thenReturn(ro...
public static boolean isSupported(String charsetName) { try { if (isSupportedICU != null && (Boolean) isSupportedICU.invoke(null, charsetName)) { return true; } return Charset.isSupported(charsetName); } catch (IllegalCharsetNameException e) { ...
@Test public void testValidCharset() { assertTrue(CharsetUtils.isSupported("UTF-8")); assertFalse(CharsetUtils.isSupported("bogus")); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, String.valueOf(Path.DELIMITER)); }
@Test public void testListEncodedCharacterFile() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("us-east-1"); final Path placeholder = new GoogleStorageTouchFeature(session).touch( ...
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void shouldDescribeGlobalStoreTopology() { addGlobalStoreToTopologyAndExpectedDescription("globalStore", "source", "globalTopic", "processor", 0); assertThat(topology.describe(), equalTo(expectedDescription)); assertThat(topology.describe().hashCode(), equalTo(expectedDescriptio...
public FunSpec getFunSpec() { return methodNeedsInjection() ? new FunSpecGenerator( uniqueFunctionName, BeforeAll.class, defaultParameterSpecsForEachUnitTest(), generat...
@Test public void testThatNewGreetingMethodWasGenerated() { Optional<Method> deployFun = filteredMethods.stream().filter(m -> m.getName().equals("newGreeting")).findAny(); FunSpec deployFunSpec = new FunParser(deployFun.get(), greeterContractClass, "newGreeting").getF...
@SuppressWarnings("unused") public static void main(String[] args) { BarSeries a = buildAndAddData(); System.out.println("a: " + a.getBar(0).getClosePrice().getName()); BaseBarSeriesBuilder.setDefaultNum(DoubleNum::valueOf); a = buildAndAddData(); System.out.println("a: " + a...
@Test public void test() { BuildBarSeries.main(null); }
static SeekableInputStream wrap(FSDataInputStream stream) { return new HadoopSeekableInputStream(stream); }
@Test void closeShouldThrowIOExceptionWhenInterrupted() throws Exception { S3ABlockOutputStream s3ABlockOutputStream = new S3ABlockOutputStream(); FSDataOutputStream fsDataOutputStream = new FSDataOutputStream(s3ABlockOutputStream, null); PositionOutputStream wrap = HadoopStreams.wrap(fsDataOutputStream)...
@Override public void onProjectsDeleted(Set<DeletedProject> projects) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsDeleted(projects))); }
@Test public void onProjectsDeleted_throws_NPE_if_set_is_null() { assertThatThrownBy(() -> underTestWithListeners.onProjectsDeleted(null)) .isInstanceOf(NullPointerException.class) .hasMessage("projects can't be null"); }
public boolean validate(final Protocol protocol, final LoginOptions options) { return protocol.validate(this, options); }
@Test public void testLoginReasonable() { Credentials credentials = new Credentials("guest", "changeme"); assertTrue(credentials.validate(new TestProtocol(Scheme.ftp), new LoginOptions())); }
@Override public Set<String> getClasses() { return new LinkedHashSet<>(new HostPreferences(session.getHost()).getList("s3.storage.class.options")); }
@Test public void testGetClasses() { assertArrayEquals(Collections.singletonList(S3Object.STORAGE_CLASS_STANDARD).toArray(), new S3StorageClassFeature(new S3Session(new Host(new S3Protocol())), new S3AccessControlListFeature(session)).getClasses().toArray()); assertArrayEquals(Arrays...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 2) { onInvalidDataReceived(device, data); return; } // Read the Op Code final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); // Estima...
@Test public void onContinuousGlucosePatientHighAlertReceived() { final Data data = new Data(new byte[] { 9, 12, -16}); callback.onDataReceived(null, data); assertEquals("Level", 1.2f, patientHighAlertLevel, 0.01); assertFalse(secured); }
@Override public Set<NodeFileDescriptorStats> fileDescriptorStats() { final List<NodeResponse> result = nodes(); return result.stream() .map(node -> NodeFileDescriptorStats.create(node.name(), node.ip(), node.host(), node.fileDescriptorMax())) .collect(Collectors.toSe...
@Test void testFileDescriptorStats() { doReturn(List.of(NODE_WITH_CORRECT_INFO, NODE_WITH_MISSING_DISK_STATISTICS)).when(catApi).nodes(); final Set<NodeFileDescriptorStats> nodeFileDescriptorStats = clusterAdapter.fileDescriptorStats(); assertThat(nodeFileDescriptorStats) .h...
public RowExpression extract(PlanNode node) { return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null); }
@Test public void testAggregation() { PlanNode node = new AggregationNode( Optional.empty(), newId(), filter(baseTableScan, and( equals(AV, DV), equals(BV, EV), ...