focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Builder withMaximumSizeBytes(long maxBloomFilterSizeBytes) { checkArgument(maxBloomFilterSizeBytes > 0, "Expected Bloom filter size limit to be positive."); long optimalNumberOfElements = optimalNumInsertions(maxBloomFilterSizeBytes, DEFAULT_FALSE_POSITIVE_PROBABILITY); checkArgument( ...
@Test public void testBuilderWithMaxSize() throws Exception { ScalableBloomFilter.Builder builder = ScalableBloomFilter.withMaximumSizeBytes(MAX_SIZE); int maxValue = insertAndVerifyContents(builder, (int) (MAX_SIZE * 1.1)); ScalableBloomFilter bloomFilter = builder.build(); // Verify that the deco...
public static Map<String, InstanceInfo> selectInstancesMappedById(Application application) { Map<String, InstanceInfo> result = new HashMap<>(); for (InstanceInfo instance : application.getInstances()) { result.put(instance.getId(), instance); } return result; }
@Test public void testSelectInstancesMappedByIdIfNotNullReturnMapOfInstances() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); HashMap<String, InstanceInfo> hashMap = new HashMap<>(); hashMap.put("foo", application.getByInstan...
@Nonnull public <K, V> KafkaProducer<K, V> getProducer(@Nullable String transactionalId) { if (getConfig().isShared()) { if (transactionalId != null) { throw new IllegalArgumentException("Cannot use transactions with shared " + "KafkaProducer for DataConne...
@Test public void shared_data_connection_should_return_same_producer() { kafkaDataConnection = createKafkaDataConnection(kafkaTestSupport); try (Producer<Object, Object> p1 = kafkaDataConnection.getProducer(null); Producer<Object, Object> p2 = kafkaDataConnection.getProducer(null)) { ...
public ArrayList<AnalysisResult<T>> getOutliers(Track<T> track) { // the stream is wonky due to the raw type, probably could be improved return track.points().stream() .map(point -> analyzePoint(point, track)) .filter(analysisResult -> analysisResult.isOutlier()) .c...
@Test public void testBuggedOutlier() { /* * This track contains an "outlier" that shouldn't really be an outlier. This test ensure * that future editions of VerticalOutlierDetector do not flag this track. */ Track<NopHit> testTrack = createTrackFromResource( V...
@Override protected ConfigData<MetaData> fromJson(final JsonObject data) { return GsonUtils.getGson().fromJson(data, new TypeToken<ConfigData<MetaData>>() { }.getType()); }
@Test public void testFromJson() { ConfigData<MetaData> metaDataConfigData = new ConfigData<>(); MetaData metaData = new MetaData(); metaDataConfigData.setData(Collections.singletonList(metaData)); JsonObject jsonObject = GsonUtils.getGson().fromJson(GsonUtils.getGson().toJson(metaDa...
@Override public Num calculate(BarSeries series, Position position) { if (position.isClosed()) { Num profit = excludeCosts ? position.getGrossProfit() : position.getProfit(); return profit.isPositive() ? profit : series.zero(); } return series.zero(); }
@Test public void calculateComparingIncludingVsExcludingCosts() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 100, 80, 85, 120); FixedTransactionCostModel transactionCost = new FixedTransactionCostModel(1); ZeroCostModel holdingCost = new ZeroCostModel(); TradingR...
@Override public CEFParserResult evaluate(FunctionArgs args, EvaluationContext context) { final String cef = valueParam.required(args, context); final boolean useFullNames = useFullNamesParam.optional(args, context).orElse(false); final CEFParser parser = CEFParserFactory.create(); ...
@Test public void evaluate_returns_result_for_valid_CEF_string_with_full_names() throws Exception { final CEFParserFunction function = new CEFParserFunction(new MetricRegistry()); final Map<String, Expression> arguments = ImmutableMap.of( CEFParserFunction.VALUE, new StringExpression...
@Override public HostToKeyMapper<Integer> getAllPartitionsMultipleHosts(URI serviceUri, int numHostPerPartition) throws ServiceUnavailableException { return getHostToKeyMapper(serviceUri, null, numHostPerPartition, null); }
@Test(dataProvider = "ringFactories") public void testAllPartitionMultipleHostsStickKey(RingFactory<URI> ringFactory) throws URISyntaxException, ServiceUnavailableException { int numHost = 2; URI serviceURI = new URI("d2://articles"); ConsistentHashKeyMapper mapper = getConsistentHashKeyMapper(ringFact...
public boolean removeAll(Collection<?> c) { throw e; }
@Test void require_that_removeAll_throws_exception() { assertThrows(NodeVector.ReadOnlyException.class, () -> new TestNodeVector("foo").removeAll(null)); }
public MessageListener messageListener(MessageListener messageListener, boolean addConsumerSpan) { if (messageListener instanceof TracingMessageListener) return messageListener; return new TracingMessageListener(messageListener, this, addConsumerSpan); }
@Test void messageListener_doesntDoubleWrap() { MessageListener wrapped = jmsTracing.messageListener(mock(MessageListener.class), false); assertThat(jmsTracing.messageListener(wrapped, false)) .isSameAs(wrapped); }
@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 onContinuousGlucoseRateOfDecreaseAlertReceived() { final Data data = new Data(new byte[] { 21, 1, 16}); callback.onDataReceived(null, data); assertEquals("Level", 10.0f, rateOfDecreaseAlertLevel, 0.00); assertFalse(secured); }
public static DeploymentDescriptor merge(List<DeploymentDescriptor> descriptorHierarchy, MergeMode mode) { if (descriptorHierarchy == null || descriptorHierarchy.isEmpty()) { throw new IllegalArgumentException("Descriptor hierarchy list cannot be empty"); } if (descriptorHierarchy.si...
@Test public void testDeploymentDesciptorMergeHierarchy() { DeploymentDescriptor primary = new DeploymentDescriptorImpl("org.jbpm.domain"); primary.getBuilder() .addMarshalingStrategy(new ObjectModel("org.jbpm.test.CustomStrategy", new Object[]{"param2"})); assertThat(prima...
public static long toUnsignedLong(short value) { return Short.toUnsignedLong(value); }
@Test public void testIntToUnsignedLong() { getIntegerTestData().forEach(val -> assertEquals(val.toString(), toUnsignedLongPreviousImplementation(val), BitmapUtils.toUnsignedLong(val))); }
public static String getTimestampFromFile(String filename) { return filename.split("\\.")[0]; }
@Test public void testGetTimestamp() { Assertions.assertTrue(HoodieConsistentHashingMetadata.getTimestampFromFile("0000.hashing_metadata").equals("0000")); Assertions.assertTrue(HoodieConsistentHashingMetadata.getTimestampFromFile("1234.hashing_metadata").equals("1234")); }
public static FuryBuilder builder() { return new FuryBuilder(); }
@Test public void testPkgAccessLevelParentClass() { Fury fury = Fury.builder().withRefTracking(true).requireClassRegistration(false).build(); HashBasedTable<Object, Object, Object> table = HashBasedTable.create(2, 4); table.put("r", "c", 100); serDeCheckSerializer(fury, table, "Codec"); }
public static List<String> splitPlainTextParagraphs( List<String> lines, int maxTokensPerParagraph) { return internalSplitTextParagraphs( lines, maxTokensPerParagraph, (text) -> internalSplitLines( text, maxTokensPerParagraph, false, s_plaintextSplitOp...
@Test public void canSplitTextParagraphsEvenly() { List<String> input = Arrays.asList( "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test.", "A small note. And another. And once again. Seriously, this is ...
public String getLocation() { String location = properties.getProperty(NACOS_LOGGING_CONFIG_PROPERTY); if (StringUtils.isBlank(location)) { if (isDefaultLocationEnabled()) { return defaultLocation; } return null; } return location; ...
@Test void testGetLocationWithDefault() { assertEquals("classpath:test.xml", loggingProperties.getLocation()); }
public boolean isUnknown() { return this.major == 0 && this.minor == 0 && this.patch == 0; }
@Test public void testIsUnknown() { assertTrue(MemberVersion.UNKNOWN.isUnknown()); assertFalse(MemberVersion.of(VERSION_3_8_SNAPSHOT_STRING).isUnknown()); assertFalse(MemberVersion.of(VERSION_3_8_1_RC1_STRING).isUnknown()); assertFalse(MemberVersion.of(VERSION_3_8_1_BETA_1_STRING).is...
static Optional<String> globalResponseError(Optional<ClientResponse> response) { if (!response.isPresent()) { return Optional.of("Timeout"); } if (response.get().authenticationException() != null) { return Optional.of("AuthenticationException"); } if (resp...
@Test public void testGlobalResponseErrorResponseLevelError() { assertEquals(Optional.of("Response-level error: INVALID_REQUEST"), AssignmentsManager.globalResponseError(Optional.of( new ClientResponse(null, null, "", 0, 0, false, false, null, null, new As...
@Override public boolean tryLock(String name) { return tryLock(name, DEFAULT_LOCK_DURATION_SECONDS); }
@Test @UseDataProvider("randomValidDuration") public void tryLock_with_duration_delegates_to_InternalPropertiesDao_and_commits(int randomValidDuration) { String lockName = "foo"; boolean expected = new Random().nextBoolean(); when(internalPropertiesDao.tryLock(dbSession, lockName, randomValidDuration)) ...
@InvokeOnHeader(Web3jConstants.ETH_SUBMIT_WORK) void ethSubmitWork(Message message) throws IOException { String nonce = message.getHeader(Web3jConstants.NONCE, configuration::getNonce, String.class); String headerPowHash = message.getHeader(Web3jConstants.HEADER_POW_HASH, configuration::getHeaderPow...
@Test public void ethSubmitWorkTest() throws Exception { EthSubmitWork response = Mockito.mock(EthSubmitWork.class); Mockito.when(mockWeb3j.ethSubmitWork(any(), any(), any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.solutionValid(...
@SneakyThrows public static String readUtf8String(String path) { String resultReadStr; ClassPathResource classPathResource = new ClassPathResource(path); try ( InputStream inputStream = classPathResource.getInputStream(); BufferedInputStream bis = new Buffered...
@Test public void assertReadUtf8String() { String testFilePath = "test/test_utf8.txt"; String contentByFileUtil = FileUtil.readUtf8String(testFilePath); Assert.assertFalse(contentByFileUtil.isEmpty()); }
@CanIgnoreReturnValue public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); ListMultimap<?, ?> extra = difference(actual, expectedMult...
@Test public void containsExactlyEmpty() { ImmutableListMultimap<Integer, String> actual = ImmutableListMultimap.of(); ImmutableSetMultimap<Integer, String> expected = ImmutableSetMultimap.of(); assertThat(actual).containsExactlyEntriesIn(expected); assertThat(actual).containsExactlyEntriesIn(expecte...
@VisibleForTesting protected void copyFromHost(MapHost host) throws IOException { // reset retryStartTime for a new host retryStartTime = 0; // Get completed maps on 'host' List<TaskAttemptID> maps = scheduler.getMapsForHost(host); // Sanity check to catch hosts with only 'OBSOLETE' maps, ...
@Test public void testCopyFromHostBogusHeader() throws Exception { Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm, r, metrics, except, key, connection); String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key); when(connection.getResponseCode())....
@Override public <T> Mono<T> run(final Mono<T> run, final Function<Throwable, Mono<T>> fallback, final Resilience4JConf resilience4JConf) { RateLimiter rateLimiter = Resilience4JRegistryFactory.rateLimiter(resilience4JConf.getId(), resilience4JConf.getRateLimiterConfig()); CircuitBreaker circuitBrea...
@Test public void errorTest() { Resilience4JConf conf = mock(Resilience4JConf.class); when(conf.getId()).thenReturn("SHENYU"); when(conf.getRateLimiterConfig()).thenReturn(RateLimiterConfig.ofDefaults()); when(conf.getTimeLimiterConfig()).thenReturn(TimeLimiterConfig.ofDefaults()); ...
public CompletableFuture<Void> storeKemOneTimePreKeys(final UUID identifier, final byte deviceId, final List<KEMSignedPreKey> preKeys) { return pqPreKeys.store(identifier, deviceId, preKeys); }
@Test void storeKemOneTimePreKeys() { assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join(), "Initial pre-key count for an account should be zero"); keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestKEMSignedPreKey(1))).join(); assertEquals(1, keysMa...
@Override public long transferTo(long position, long count, WritableByteChannel target) throws IOException { checkNotNull(target); Util.checkNotNegative(position, "position"); Util.checkNotNegative(count, "count"); checkOpen(); checkReadable(); long transferred = 0; // will definitely either ...
@Test public void testTransferToNegative() throws IOException { FileChannel channel = channel(regularFile(0), READ, WRITE); try { channel.transferTo(-1, 0, new ByteBufferChannel(10)); fail(); } catch (IllegalArgumentException expected) { } try { channel.transferTo(0, -1, new By...
public void close(long timeoutMs) { ThreadUtils.shutdownExecutorServiceQuietly(commitExecutorService, timeoutMs, TimeUnit.MILLISECONDS); }
@Test public void testCloseTimeout() throws Exception { long timeoutMs = 1000; // Normal termination, where termination times out. when(executor.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS)).thenReturn(false); try (LogCaptureAppender logCaptureAppender = LogCaptureAppender.cr...
public static boolean isInvalidStanzaSentPriorToResourceBinding(final Packet stanza, final ClientSession session) { // Openfire sets 'authenticated' only after resource binding. if (session.getStatus() == Session.Status.AUTHENTICATED) { return false; } // Beware, the 'to...
@Test public void testIsInvalid_addressedAtDomain_authenticated() throws Exception { // Setup test fixture. final Packet stanza = new Message(); stanza.setTo(XMPPServer.getInstance().getServerInfo().getXMPPDomain()); final LocalClientSession session = mock(LocalClientSession.clas...
@Override public Map<String, Object> load(String configKey) { if (targetFilePath != null) { try { Map<String, Object> raw = (Map<String, Object>) Utils.readYamlFile(targetFilePath); if (raw != null) { return (Map<String, Object>) raw.get(config...
@Test public void testInvalidConfig() { Config conf = new Config(); FileConfigLoader testLoader = new FileConfigLoader(conf); Map<String, Object> result = testLoader.load(DaemonConfig.MULTITENANT_SCHEDULER_USER_POOLS); assertNull(result, "Unexpectedly returned a map"); }
public static List<String> findVariablesForEncodedValuesString(CustomModel model, NameValidator nameValidator, ClassHelper classHelper) { Set<String> variables = new LinkedHashSet<>(); // avoid parsing exception for backward_xy or in_xy ... NameValidator nameValidatorIntern = s -> { ...
@Test public void findVariablesForEncodedValueString() { CustomModel customModel = new CustomModel(); customModel.addToPriority(If("backward_car_access != car_access", MULTIPLY, "0.5")); List<String> variables = findVariablesForEncodedValuesString(customModel, s -> new DefaultImportRegistry(...
@Activate public void activate() { providerService = providerRegistry.register(this); // listens all LISP router related events controller.addRouterListener(listener); // listens all LISP control message controller.addMessageListener(listener); log.info("Started")...
@Test public void activate() throws Exception { assertEquals("Provider should be registered", 1, providerRegistry.getProviders().size()); assertTrue("LISP device provider should be registered", providerRegistry.getProviders().contains(provider.id())); ...
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) { this.jsonPath = jsonPath; this.resultMatcher = resultMatcher; }
@Test public void shouldMatchJsonPathEvaluatedToIntegerValue() { assertThat(BOOKS_JSON, withJsonPath(compile("$.expensive"), equalTo(10))); assertThat(BOOKS_JSON, withJsonPath("$.expensive", equalTo(10))); }
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testBlacklistRejection() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( Arrays.asList("h1", "h2"), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList(ResourceRequest.newInstance(PRIORITY_NORMAL, ...
@VisibleForTesting public void validateSmsTemplateCodeDuplicate(Long id, String code) { SmsTemplateDO template = smsTemplateMapper.selectByCode(code); if (template == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if (id == null) { throw exception(...
@Test public void testValidateDictDataValueUnique_success() { // 调用,成功 smsTemplateService.validateSmsTemplateCodeDuplicate(randomLongId(), randomString()); }
List<StatisticsEntry> takeStatistics() { if (reporterEnabled) throw new IllegalStateException("Cannot take consistent snapshot while reporter is enabled"); var ret = new ArrayList<StatisticsEntry>(); consume((metric, value) -> ret.add(new StatisticsEntry(metric, value))); ret...
@Test void request_type_can_be_set_explicitly() { testRequest("http", 200, "GET", "/search", com.yahoo.jdisc.Request.RequestType.WRITE); var stats = collector.takeStatistics(); assertStatisticsEntry(stats, "http", "GET", MetricDefinitions.RESPONSES_2XX, "write", 200, 1L); }
@Override public long tick() throws InterruptedException { long now = mClock.millis(); mSleeper.sleep( () -> Duration.ofMillis(mIntervalSupplier.getNextInterval(mPreviousTickedMs, now))); mPreviousTickedMs = mClock.millis(); return mIntervalSupplier.getRunLimit(mPreviousTickedMs); }
@Test public void warnWhenExecutionTakesLongerThanInterval() throws Exception { SleepingTimer timer = new SleepingTimer(THREAD_NAME, mMockLogger, mFakeClock, new SteppingThreadSleeper(mMockSleeper, mFakeClock), () -> new FixedIntervalSupplier(INTERVAL_MS, mMockLogger)); timer....
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final List<Path> containers = new ArrayList<Path>(); for(Path file : files.keySet()) { if(containerService.isContainer(file)) { ...
@Test public void testDeletePlaceholder() throws Exception { final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new AzureDirectoryFeature(session, null).mkdir(new Path(container, new AlphanumericRandomStringService().random(), EnumSet.o...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testLambdaInAggregationContext() { analyze("SELECT apply(sum(x), i -> i * i) FROM (VALUES 1, 2, 3, 4, 5) t(x)"); analyze("SELECT apply(x, i -> i - 1), sum(y) FROM (VALUES (1, 10), (1, 20), (2, 50)) t(x,y) group by x"); analyze("SELECT x, apply(sum(y), i -> i * 10) FROM ...
@Override public byte[] get(byte[] key) { return read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key); }
@Test public void testGeo() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); String key = "test_geo_key"; Point point = new Point(116.401001...
public static Map<String, AdvertisedListener> validateAndAnalysisAdvertisedListener(ServiceConfiguration config) { if (StringUtils.isBlank(config.getAdvertisedListeners())) { return Collections.emptyMap(); } Optional<String> firstListenerName = Optional.empty(); Map<String, L...
@Test(expectedExceptions = IllegalArgumentException.class) public void testListenerDuplicate_2() { ServiceConfiguration config = new ServiceConfiguration(); config.setAdvertisedListeners(" internal:pulsar://127.0.0.1:6660," + " internal:pulsar://192.168.1.11:6660"); config.setInternalListene...
public static @NonNull String printThrowable(@CheckForNull Throwable t) { if (t == null) { return Messages.Functions_NoExceptionDetails(); } StringBuilder s = new StringBuilder(); doPrintStackTrace(s, t, null, "", new HashSet<>()); return s.toString(); }
@Issue("JDK-6507809") @Test public void printThrowable() { // Basics: a single exception. No change. assertPrintThrowable(new Stack("java.lang.NullPointerException: oops", "p.C.method1:17", "m.Main.main:1"), "java.lang.NullPointerException: oops\n" + "\tat p.C.method1(C.java:...
public void write(D datum, Encoder out) throws IOException { Objects.requireNonNull(out, "Encoder cannot be null"); try { write(root, datum, out); } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { throw e.summarize(root); } }
@Test void write() throws IOException { String json = "{\"type\": \"record\", \"name\": \"r\", \"fields\": [" + "{ \"name\": \"f1\", \"type\": \"long\" }" + "]}"; Schema s = new Schema.Parser().parse(json); GenericRecord r = new GenericData.Record(s); r.put("f1", 100L); ByteArrayOutputStre...
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDe...
@Test public void testZeroGuarOverCap() { int[][] qData = new int[][] { // / A B C D E F { 200, 100, 0, 100, 0, 100, 100 }, // abs { 200, 200, 200, 200, 200, 200, 200 }, // maxCap { 170, 170, 60, 20, 90, 0, 0 }, // used { 85, 50, 30, 10, 10, 20, 20...
public void buyProduct(Product product) { LOGGER.info( String.format( "%s want to buy %s($%.2f)...", name, product.getName(), product.getSalePrice().getAmount())); try { withdraw(product.getSalePrice()); } catch (IllegalArgumentException ex) { LOGGER.error(ex.getM...
@Test void shouldAddProductToPurchases() { product.setPrice(Money.of(USD, 200.0)); customer.buyProduct(product); assertEquals(customer.getPurchases(), new ArrayList<>()); assertEquals(customer.getMoney(), Money.of(USD,100)); product.setPrice(Money.of(USD, 100.0)); ...
public boolean isSynchronous() { return synchronous; }
@Test public void testAsyncProducer() { Endpoint endpoint = context.getEndpoint("sjms:queue:test.SjmsEndpointTest?synchronous=true"); assertNotNull(endpoint); assertTrue(endpoint instanceof SjmsEndpoint); SjmsEndpoint qe = (SjmsEndpoint) endpoint; assertTrue(qe.isSynchronous(...
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getData(); switch (metric.getType().getValueType()) { case ...
@Test public void toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setValue(1.987d), SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.BO...
@Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { return zkClient.getContent(getNodePath(subscriberMetadataIdentifier)); }
@Test void testDoGetSubscribedURLs() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consu...
@Override public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) { final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier()); // Callers must be authenticated t...
@Test void getUnversionedProfileUnidentifiedAccessKey() { final UUID targetUuid = UUID.randomUUID(); final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid); final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccess...
@Override public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { String filteredValue = nonXmlCharFilterer.filter(value); writer.writeAttribute(prefix, namespaceURI, localName, filteredValue); }
@Test public void testWriteAttribute3Args() throws XMLStreamException { filteringXmlStreamWriter.writeAttribute("namespaceURI", "localName", "value"); verify(xmlStreamWriterMock).writeAttribute("namespaceURI", "localName", "filteredValue"); }
public TableMetadata maybeAppendSnapshots( TableMetadata metadata, List<Snapshot> snapshotsToAppend, Map<String, SnapshotRef> snapshotRefs, boolean recordAction) { TableMetadata.Builder metadataBuilder = TableMetadata.buildFrom(metadata); List<String> appendedSnapshots = new ArrayList<>(...
@Test void testAppendSnapshotsWithOldSnapshots() throws IOException { TableMetadata metadata = TableMetadata.buildFrom(BASE_TABLE_METADATA) .setPreviousFileLocation("tmp_location") .setLocation(BASE_TABLE_METADATA.metadataFileLocation()) .build(); // all snapshots a...
public static List<String> finalDestination(List<String> elements) { if (isMagicPath(elements)) { List<String> destDir = magicPathParents(elements); List<String> children = magicPathChildren(elements); checkArgument(!children.isEmpty(), "No path found under the prefix " + MAGIC_PATH_PREF...
@Test(expected = IllegalArgumentException.class) public void testFinalDestinationBaseNoChild() { assertEquals(l(), finalDestination(l(MAGIC_PATH_PREFIX, BASE))); }
public static Node build(final List<JoinInfo> joins) { Node root = null; for (final JoinInfo join : joins) { if (root == null) { root = new Leaf(join.getLeftSource()); } if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) { throw new K...
@Test public void shouldIncludeOnlyColFromFirstInViableKeyIfOverlap() { // Given: when(j1.getLeftSource()).thenReturn(a); when(j1.getRightSource()).thenReturn(b); when(j2.getLeftSource()).thenReturn(a); when(j2.getRightSource()).thenReturn(c); when(j1.getLeftJoinExpression()).thenReturn(e1); ...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer, final Merger<? super K, V> sessionMerger) { return aggregate(initializer, sessionMerger, Materialized.with(null, null)); }
@Test public void shouldNotHaveNullSessionMerger3OnAggregate() { assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, null, Named.as("name"), Materialized.as("test"))); }
@Override public final boolean wasNull() throws SQLException { return mergedResult.wasNull(); }
@Test void assertWasNull() throws SQLException { when(mergedResult.wasNull()).thenReturn(true); assertTrue(decoratorMergedResult.wasNull()); }
public static <T> T requireNonNull(T obj, String msg) { if (obj == null) { throw new PowerJobException(msg); } if (obj instanceof String) { if (StringUtils.isEmpty((String) obj)) { throw new PowerJobException(msg); } } if (obj i...
@Test void testRequireNonNull() { assertThrowsExactly(PowerJobException.class, () -> CommonUtils.requireNonNull(null, "NULL_OBJ")); assertThrowsExactly(PowerJobException.class, () -> CommonUtils.requireNonNull("", "EMPTY_STR")); assertThrowsExactly(PowerJobException.class, () -> CommonUtils...
public static <T extends PulsarConfiguration> T create(String configFile, Class<? extends PulsarConfiguration> clazz) throws IOException, IllegalArgumentException { requireNonNull(configFile); try (InputStream inputStream = new FileInputStream(configFile)) { return create(inputSt...
@Test public void testBackwardCompatibility() throws IOException { File testConfigFile = new File("tmp." + System.currentTimeMillis() + ".properties"); if (testConfigFile.exists()) { testConfigFile.delete(); } try (PrintWriter printWriter = new PrintWriter(new OutputStrea...
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = ResourceConfigException.class) public void failsOnSimpleResourceWithInvalidMethod() { @RestLiSimpleResource(name = "simpleResourceWithUnsupportedMethod") class LocalClass extends SimpleResourceTemplate<EmptyRecord> { @RestMethod.GetAll public List<EmptyRecord> getAl...
@Override public Serializer<AvroWrapper<T>> getSerializer(Class<AvroWrapper<T>> c) { Configuration conf = getConf(); Schema schema; if (AvroKey.class.isAssignableFrom(c)) { schema = getKeyWriterSchema(conf); } else if (AvroValue.class.isAssignableFrom(c)) { schema = getValueWriterSchema(co...
@Test void getSerializerForValue() throws IOException { // Set the writer schema in the job configuration. Schema writerSchema = Schema.create(Schema.Type.STRING); Job job = Job.getInstance(); AvroJob.setMapOutputValueSchema(job, writerSchema); // Get a serializer from the configuration. Avro...
public static RowCoder of(Schema schema) { return new RowCoder(schema); }
@Test public void testEncodingPositionReorderFields() throws Exception { Schema schema1 = Schema.builder() .addNullableField("f_int32", FieldType.INT32) .addNullableField("f_string", FieldType.STRING) .build(); Schema schema2 = Schema.builder() ....
void removeQueuedBlock(DatanodeStorageInfo storageInfo, Block block) { if (storageInfo == null || block == null) { return; } Block blk = new Block(block); if (BlockIdManager.isStripedBlockID(block.getBlockId())) { blk = new Block(BlockIdManager.convertToStripedID(block .getBlockId(...
@Test public void testRemoveQueuedBlock() { DatanodeDescriptor fakeDN1 = DFSTestUtil.getDatanodeDescriptor( "localhost", 8898, "/default-rack"); DatanodeDescriptor fakeDN2 = DFSTestUtil.getDatanodeDescriptor( "localhost", 8899, "/default-rack"); DatanodeStorage storage1 = new DatanodeStora...
public static void stopProxy(Object proxy) { if (proxy == null) { throw new HadoopIllegalArgumentException( "Cannot close proxy since it is null"); } try { if (proxy instanceof Closeable) { ((Closeable) proxy).close(); return; } else { InvocationHandler ha...
@Test public void testStopMockObject() throws IOException { RPC.stopProxy(MockitoUtil.mockProtocol(TestProtocol.class)); }
static void verifyAddMissingValues(final List<KiePMMLMiningField> notTargetMiningFields, final PMMLRequestData requestData) { logger.debug("verifyMissingValues {} {}", notTargetMiningFields, requestData); Collection<ParameterInfo> requestParams = requestData.getReq...
@Test void verifyAddMissingValuesNotMissingNotReturnInvalidReplacement() { KiePMMLMiningField miningField0 = KiePMMLMiningField.builder("FIELD-0", null) .withDataType(DATA_TYPE.STRING) .withMissingValueTreatmentMethod(MISSING_VALUE_TREATMENT_METHOD.AS_IS) .wit...
public B addProtocol(ProtocolConfig protocol) { if (this.protocols == null) { this.protocols = new ArrayList<>(); } this.protocols.add(protocol); return getThis(); }
@Test void addProtocol() { ProtocolConfig protocol = new ProtocolConfig(); ServiceBuilder builder = new ServiceBuilder(); Assertions.assertNull(builder.build().getProtocols()); builder.addProtocol(protocol); Assertions.assertNotNull(builder.build().getProtocols()); As...
@Override public void start() { if (taskExecutorThread == null) { taskExecutorThread = new TaskExecutorThread(name); taskExecutorThread.start(); shutdownGate = new CountDownLatch(1); } }
@Test public void shouldProcessTasks() { when(taskExecutionMetadata.canProcessTask(any(), anyLong())).thenReturn(true); when(task.isProcessable(anyLong())).thenReturn(true); taskExecutor.start(); verify(task, timeout(VERIFICATION_TIMEOUT).atLeast(2)).process(anyLong()); ver...
@Override public List<TaskProperty> getPropertiesForDisplay() { ArrayList<TaskProperty> taskProperties = new ArrayList<>(); if (PluggableTaskConfigStore.store().hasPreferenceFor(pluginConfiguration.getId())) { TaskPreference preference = taskPreference(); List<? extends Prope...
@Test public void shouldPopulatePropertiesForDisplayRetainingOrderAndDisplayNameIfConfigured() throws Exception { Task taskDetails = mock(Task.class); TaskConfig taskConfig = new TaskConfig(); addProperty(taskConfig, "KEY2", "Key 2", 1); addProperty(taskConfig, "KEY1", "Key 1", 0); ...
@UdafFactory(description = "Compute sample standard deviation of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint, M2 double>") public static TableUdaf<Integer, Struct, Double> stdDevInt() { return getStdDevImplementation( 0, STRUCT_INT, (agg, newValue)...
@Test public void shouldAverageEmpty() { final TableUdaf<Integer, Struct, Double> udaf = stdDevInt(); final Struct agg = udaf.initialize(); final double standardDev = udaf.map(agg); assertThat(standardDev, equalTo(0.0)); }
@Override public void close() { stopAsync(); awaitTerminated(); }
@Test public void constructAndClose() throws IOException { WalletAppKit kit = new WalletAppKit(REGTEST, P2WPKH, BIP43, tmpFolder.newFolder(), filePrefix); kit.close(); }
public Date getGregorianDate() { return DateUtil.date(getGregorianCalendar()); }
@Test public void getGregorianDateTest(){ // https://gitee.com/dromara/hutool/issues/I4ZSGJ ChineseDate chineseDate = new ChineseDate(1998, 5, 1); assertEquals("1998-06-24 00:00:00", chineseDate.getGregorianDate().toString()); chineseDate = new ChineseDate(1998, 5, 1, false); assertEquals("1998-05-26 00:00:...
@Override public ListView<String> getServiceList(int pageNo, int pageSize, String groupName, AbstractSelector selector) throws NacosException { Map<String, String> params = new HashMap<>(16); params.put("pageNo", String.valueOf(pageNo)); params.put("pageSize", String.val...
@Test void testGetServiceList() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult<Object> a = new HttpRestResult<Object>(); a.setData("{\"count\":2,\"doms\":[\"aaa\",\"bbb\"]}"); a.setCode(200); when(nacosRe...
public static UserOperatorConfig buildFromMap(Map<String, String> map) { Map<String, String> envMap = new HashMap<>(map); envMap.keySet().retainAll(UserOperatorConfig.keyNames()); Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES); return new UserOperatorC...
@Test public void testFromMapCaNameEnvVarMissingThrows() { Map<String, String> envVars = new HashMap<>(UserOperatorConfigTest.ENV_VARS); envVars.remove(UserOperatorConfig.CA_CERT_SECRET_NAME.key()); assertThrows(InvalidConfigurationException.class, () -> UserOperatorConfig.buildFromMap(env...
public Capabilities getCapabilities(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_GET_CAPABILITIES, new DefaultPluginInteractionCallback<>() { @Override public Capabilities onSuccess(String responseBody, Map<String, String> responseHeaders, String resolved...
@Test public void shouldTalkToPlugin_To_GetCapabilities() throws Exception { String responseBody = """ { "supported_analytics": [ {"type": "dashboard", "id": "abc", "title": "Title 1"}, {"type": "pipeline", "id": "abc", "title": "Title 1"...
public static boolean isViewSelfVisible(View view) { if (view == null || view.getWindowVisibility() == View.GONE) { return false; } if (WindowHelper.isDecorView(view.getClass())) { return true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ...
@Test public void isViewSelfVisible() { CheckBox textView1 = new CheckBox(mApplication); textView1.setVisibility(View.VISIBLE); Assert.assertFalse(SAViewUtils.isViewSelfVisible(textView1)); }
@Override public void close() throws IOException { boolean triedToClose = false, success = false; try { flush(); ((FileOutputStream)out).getChannel().force(true); triedToClose = true; super.close(); success = true; } finally { if (success) { boolean renamed = t...
@Test public void testOverwriteFile() throws IOException { assertTrue("Creating empty dst file", DST_FILE.createNewFile()); OutputStream fos = new AtomicFileOutputStream(DST_FILE); assertTrue("Empty file still exists", DST_FILE.exists()); fos.write(TEST_STRING.getBytes()); fos.flush(); ...
public static void addFileSliceCommonMetrics(List<FileSlice> fileSlices, Map<String, Double> metrics, long defaultBaseFileSize) { int numLogFiles = 0; long totalLogFileSize = 0; long totalIORead = 0; long totalIOWrite = 0; long totalIO = 0; for (FileSlice slice : fileSlices) { numLogFiles...
@Test public void testFileSliceMetricUtilsWithoutLogFile() { Map<String, Double> metrics = new HashMap<>(); List<FileSlice> fileSlices = new ArrayList<>(); final long defaultBaseFileSize = 10 * 1024 * 1024; final double epsilon = 1e-5; fileSlices.add(buildFileSlice(15 * 1024 * 1024, new ArrayList<...
public void findIntersections(Rectangle query, Consumer<T> consumer) { IntArrayList todoNodes = new IntArrayList(levelOffsets.length * degree); IntArrayList todoLevels = new IntArrayList(levelOffsets.length * degree); int rootLevel = levelOffsets.length - 1; int rootIndex = levelOff...
@Test public void testDoubletonFlatbush() { // This is the smallest Rtree with height > 1 // Also test for some degeneracies Rectangle rect0 = new Rectangle(1, 1, 1, 1); Rectangle rect1 = new Rectangle(-1, -2, -1, -1); List<Rectangle> items = ImmutableList.of(rect0, rect1...
@Override public Properties info(RedisClusterNode node) { Map<String, String> info = execute(node, RedisCommands.INFO_ALL); Properties result = new Properties(); for (Entry<String, String> entry : info.entrySet()) { result.setProperty(entry.getKey(), entry.getValue()); } ...
@Test public void testInfo() { RedisClusterNode master = getFirstMaster(); Properties info = connection.info(master); assertThat(info.size()).isGreaterThan(10); }
public static Object getValueOrCachedValue(Record record, SerializationService serializationService) { Object cachedValue = record.getCachedValueUnsafe(); if (cachedValue == NOT_CACHED) { //record does not support caching at all return record.getValue(); } for (; ...
@Test public void getValueOrCachedValue_whenRecordIsCachedDataRecordWithStats_thenCache() { String objectPayload = "foo"; Data dataPayload = serializationService.toData(objectPayload); Record record = new CachedDataRecordWithStats(dataPayload); Object firstDeserializedValue = Records...
@Override public CompletableFuture<Void> closeAsync() { synchronized (lock) { if (isShutdown) { return terminationFuture; } else { isShutdown = true; final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(3); ...
@Test void testConfigurableDelimiterForReportersInGroup() throws Exception { String name = "C"; MetricConfig config1 = new MetricConfig(); config1.setProperty(MetricOptions.REPORTER_SCOPE_DELIMITER.key(), "_"); MetricConfig config2 = new MetricConfig(); config2.setProperty(M...
@Override public void checkBeforeUpdate(final DropMaskRuleStatement sqlStatement) { if (!sqlStatement.isIfExists()) { checkToBeDroppedMaskTableNames(sqlStatement); } }
@Test void assertCheckSQLStatementWithoutToBeDroppedRule() { MaskRule rule = mock(MaskRule.class); when(rule.getConfiguration()).thenReturn(new MaskRuleConfiguration(Collections.emptyList(), Collections.emptyMap())); executor.setRule(rule); assertThrows(MissingRequiredRuleException.c...
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (GraceContext.INSTANCE.getStartWarmUpTime() == 0) { GraceContext.INSTANCE.setStartWarmUpTime(System.currentTimeMillis()); } addGraceAddress(request); final Gr...
@Test public void preHandle() { GraceContext.INSTANCE.getGraceShutDownManager().setShutDown(true); interceptor.preHandle(request, response, new Object()); Assert.assertTrue(GraceContext.INSTANCE.getStartWarmUpTime() > 0); Assert.assertTrue(addresses.contains(testAddress)); As...
@Override public ConsumerConfig build() { ConsumerConfig consumer = new ConsumerConfig(); super.build(consumer); consumer.setDefault(isDefault); consumer.setClient(client); consumer.setThreadpool(threadpool); consumer.setCorethreads(corethreads); consumer.set...
@Test void build() { ConsumerBuilder builder = ConsumerBuilder.newBuilder(); builder.isDefault(true) .client("client") .threadPool("threadPool") .coreThreads(10) .threads(100) .queues(200) .shareConnectio...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<>(); if(replies.isEmpty()) { return children; } // At least one entry successfully parsed...
@Test public void testParseWhitespaceInResponseLine() throws Exception { Path path = new Path("/", EnumSet.of(Path.Type.directory)); String[] replies = new String[]{ " Type=file;Size=38955938;Modify=20230328150158.830; IMG_2625–JK.psd" }; final AttributedList<Path...
AclBinding targetAclBinding(AclBinding sourceAclBinding) { String targetTopic = formatRemoteTopic(sourceAclBinding.pattern().name()); final AccessControlEntry entry; if (sourceAclBinding.entry().permissionType() == AclPermissionType.ALLOW && sourceAclBinding.entry().operation() =...
@Test public void testAclTransformation() { MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"), new DefaultReplicationPolicy(), x -> true, getConfigPropertyFilter()); AclBinding allowAllAclBinding = new AclBinding( new Resource...
@SuppressWarnings("FutureReturnValueIgnored") public void start() { running.set(true); configFetcher.start(); memoryMonitor.start(); streamingWorkerHarness.start(); sampler.start(); workerStatusReporter.start(); activeWorkRefresher.start(); }
@Test public void testExceptionInvalidatesCache() throws Exception { // We'll need to force the system to limit bundles to one message at a time. // Sequence is as follows: // 01. GetWork[0] (token 0) // 02. Create counter reader // 03. Counter yields 0 // 04. GetData[0] (state as null) //...
static ClockImpl createClock() { String clockImplClassName = System.getProperty(ClockProperties.HAZELCAST_CLOCK_IMPL); if (clockImplClassName != null) { try { return ClassLoaderUtil.newInstance(null, clockImplClassName); } catch (Exception e) { thr...
@Test public void testCreateClock_withClockImpl() { setJumpingClock(30); Clock.ClockImpl clock = Clock.createClock(); assertInstanceOf(JumpingSystemClock.class, clock); }
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowFunctionStatusStatement) { return Optional.of(new ShowFunctionStatusExecutor((ShowFu...
@Test void assertCreateWithMySQLShowDatabasesStatement() { when(sqlStatementContext.getSqlStatement()).thenReturn(new MySQLShowDatabasesStatement()); Optional<DatabaseAdminExecutor> actual = new MySQLAdminExecutorCreator().create(sqlStatementContext, "", "", Collections.emptyList()); assertT...
public static String buildWebApplicationRootUrl(NetworkService networkService) { checkNotNull(networkService); if (!isWebService(networkService)) { return "http://" + NetworkEndpointUtils.toUriAuthority(networkService.getNetworkEndpoint()) + "/"; } String rootUrl = (i...
@Test public void buildWebApplicationRootUrl_whenHttpsServiceOnPort443_removesTrailingPortFromUrl() { assertThat( NetworkServiceUtils.buildWebApplicationRootUrl( NetworkService.newBuilder() .setNetworkEndpoint(forIpAndPort("127.0.0.1", 443)) .setServiceName("ssl...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testWeb3Sha3() throws Exception { web3j.web3Sha3("0x68656c6c6f20776f726c64").send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"web3_sha3\"," + "\"params\":[\"0x68656c6c6f20776f726c64\"],\"id\":1}"); }
public void stop() { try { checkNotNull(httpServer, "httpServer").stop(); checkNotNull(guiceFilter, "guiceFilter").destroy(); } catch (Exception e) { throw new WebAppException(e); } }
@Test void testCreate() { WebApp app = WebApps.$for(this).start(); app.stop(); }
void upload(String json) throws IOException { Request request = buildHttpRequest(serverUrl, json); execute(okHttpClient.newCall(request)); }
@Test void upload() throws IOException { ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class); settings.setProperty(SONAR_TELEMETRY_COMPRESSION.getKey(), false); underTest.start(); underTest.upload(JSON); verify(okHttpClient).newCall(requestCaptor.capture()); Reques...
@Override public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment, InstancePartitions instancePartitions, InstancePartitionsType instancePartitionsType) { String serverTag = _tenantConfig.getServer(); Set<String> instances = HelixHelper.getServerInstances...
@Test public void testSegmentAssignmentAndRebalance() { List<HelixProperty> instanceConfigList = new ArrayList<>(); for (String instance : INSTANCES) { ZNRecord znRecord = new ZNRecord(instance); znRecord.setListField(TAG_LIST.name(), ImmutableList.of(OFFLINE_SERVER_TAG, REALTIME_SERVER_TAG)); ...
@Override public LongMaximum clone() { LongMaximum clone = new LongMaximum(); clone.max = this.max; return clone; }
@Test void testClone() { LongMaximum max = new LongMaximum(); long value = 4242424242424242L; max.add(value); LongMaximum clone = max.clone(); assertThat(clone.getLocalValue().longValue()).isEqualTo(value); }
static int mainNoExit(String... args) { try { execute(args); return 0; } catch (HelpScreenException e) { return 0; } catch (ArgumentParserException e) { e.getParser().handleError(e); return 1; } catch (TerseException e) { ...
@Test public void testCommandConfig() throws IOException { // specifying a --command-config containing properties that would prevent login must fail File tmpfile = TestUtils.tempFile(AdminClientConfig.SECURITY_PROTOCOL_CONFIG + "=SSL_PLAINTEXT"); assertEquals(1, MetadataQuorumCommand.mainNoE...
public void writeMethodHandle(MethodHandleReference methodHandleReference) throws IOException { writer.write(MethodHandleType.toString(methodHandleReference.getMethodHandleType())); writer.write('@'); Reference memberReference = methodHandleReference.getMemberReference(); if (memberRefe...
@Test public void testWriteMethodHandle_methodAccess() throws IOException { DexFormattedWriter writer = new DexFormattedWriter(output); writer.writeMethodHandle(getMethodHandleReferenceForMethod()); Assert.assertEquals("invoke-instance@Ldefining/class;->methodName(Lparam1;Lparam2;)Lreturn/...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatCreateTableStatementWithExplicitKey() { // Given: final CreateTable createTable = new CreateTable( TEST, ELEMENTS_WITH_PRIMARY_KEY, false, false, SOME_WITH_PROPS, false); // When: final String sql = SqlFormatter.formatSql(c...
@Override public void alert(Anomaly anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType) { super.alert(anomaly, autoFixTriggered, selfHealingStartTime, anomalyType); if (_slackWebhook == null) { LOG.warn("Slack webhook is null, can't send Slack self hea...
@Test public void testSlackAlertWithDefaultOptions() { _notifier = new MockSlackSelfHealingNotifier(mockTime); _notifier._slackWebhook = "http://dummy.slack.webhook"; _notifier._slackChannel = "#dummy-channel"; _notifier.alert(failures, false, 1L, KafkaAnomalyType.BROKER_FAILURE); ...
public <T> void resolve(T resolvable) { ParamResolver resolver = this; if (ParamScope.class.isAssignableFrom(resolvable.getClass())) { ParamScope newScope = (ParamScope) resolvable; resolver = newScope.applyOver(resolver); } resolveStringLeaves(resolvable, resolve...
@Test public void shouldProvideContextWhenAnExceptionOccursBecauseOfHashAtEnd() { PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant"); pipelineConfig.setLabelTemplate("abc#"); new ParamResolver(new ParamSubstitutionHandlerFactory(params(param("fo...
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testresetPositionsMetadataRefresh() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST); // First fetch fails with stale metadata client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequ...
@GetMapping @PreAuthorize("hasAnyAuthority('ADMIN', 'USER')") public CustomResponse<CustomPagingResponse<ProductResponse>> getProducts( @RequestBody @Valid final ProductPagingRequest productPagingRequest) { final CustomPage<Product> productPage = productReadService.getProducts(productPaging...
@Test void givenProductPagingRequest_whenGetProductsFromUser_thenReturnCustomPageProduct() throws Exception { // Given ProductPagingRequest pagingRequest = ProductPagingRequest.builder() .pagination( CustomPaging.builder() .pag...