focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public PipesResult process(FetchEmitTuple t) throws IOException, InterruptedException { boolean restart = false; if (!ping()) { restart = true; } else if (pipesConfig.getMaxFilesProcessedPerProcess() > 0 && filesProcessed >= pipesConfig.getMaxFilesProcessedPerProcess(...
@Test public void testBasic() throws IOException, InterruptedException { PipesResult pipesResult = pipesClient.process( new FetchEmitTuple(testPdfFile, new FetchKey(fetcherName, testPdfFile), new EmitKey(), new Metadata(), new ParseContext(), FetchEmitTuple.ON_PARSE_E...
public static void remove() { final Map<String, RequestContext> contextMap = THREAD_LOCAL_CONTEXT_MAP.get(); if (contextMap != null) { contextMap.clear(); THREAD_LOCAL_CONTEXT_MAP.remove(); } }
@Test public void remove() throws NoSuchFieldException, IllegalAccessException { ChainContext.getThreadLocalContext("test"); ChainContext.remove(); final Field mapField = ChainContext.class.getDeclaredField("THREAD_LOCAL_CONTEXT_MAP"); mapField.setAccessible(true); final Obje...
public static Predicate<MetricDto> isOptimizedForBestValue() { return m -> m != null && m.isOptimizedBestValue() && m.getBestValue() != null; }
@Test void isOptimizedForBestValue_is_false_when_is_not_optimized() { metric = new MetricDto() .setBestValue(42.0d) .setOptimizedBestValue(false); boolean result = MetricDtoFunctions.isOptimizedForBestValue().test(metric); assertThat(result).isFalse(); }
int parseAndConvert(String[] args) throws Exception { Options opts = createOptions(); int retVal = 0; try { if (args.length == 0) { LOG.info("Missing command line arguments"); printHelp(opts); return 0; } CommandLine cliParser = new GnuParser().parse(opts, args); ...
@Test public void testConvertFSConfigurationWithConsoleParam() throws Exception { setupFSConfigConversionFiles(true); ArgumentCaptor<FSConfigToCSConfigConverterParams> conversionParams = ArgumentCaptor.forClass(FSConfigToCSConfigConverterParams.class); FSConfigToCSConfigArgumentHandler arg...
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void doNotRetryFromPredicateUsingFlowable() { RetryConfig config = RetryConfig.custom() .retryOnException(t -> t instanceof IOException) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of("testName", config); ...
@Udf(description = "Returns a masked version of the input string. All characters except for the" + " last n will be replaced according to the default masking rules.") @SuppressWarnings("MethodMayBeStatic") // Invoked via reflection public String mask( @UdfParameter("input STRING to be masked") final Str...
@Test public void shouldNotMaskLastNChars() { final String result = udf.mask("AbCd#$123xy Z", 5); assertThat(result, is("XxXx--nn3xy Z")); }
public static CheckpointStorage load( @Nullable CheckpointStorage fromApplication, StateBackend configuredStateBackend, Configuration jobConfig, Configuration clusterConfig, ClassLoader classLoader, @Nullable Logger logger) throws Illeg...
@Test void testLegacyStateBackendTakesPrecedence() throws Exception { StateBackend legacy = new LegacyStateBackend(); CheckpointStorage storage = new MockStorage(); CheckpointStorage configured = CheckpointStorageLoader.load( storage, legacy, new Conf...
static void addKieRuntimeServiceToFirstLevelCache(KieRuntimeService toAdd, EfestoClassKey firstLevelClassKey) { List<KieRuntimeService> stored = firstLevelCache.get(firstLevelClassKey); if (stored == null) { stored = new ArrayList<>(); firstLevelCache.put(firstLevelClassKey, stor...
@Test void addKieRuntimeServiceToFirstLevelCache() { List<KieRuntimeService> discoveredKieRuntimeServices = Collections.singletonList(kieRuntimeServiceA); final Map<EfestoClassKey, List<KieRuntimeService>> toPopulate = new HashMap<>(); RuntimeManagerUtils.populateFirstLevelCache(discoveredKi...
public static <K, V, S extends StateStore> Materialized<K, V, S> as(final DslStoreSuppliers storeSuppliers) { Objects.requireNonNull(storeSuppliers, "store type can't be null"); return new Materialized<>(storeSuppliers); }
@Test public void shouldThrowNullPointerIfKeyValueBytesStoreSupplierIsNull() { final NullPointerException e = assertThrows(NullPointerException.class, () -> Materialized.as((KeyValueBytesStoreSupplier) null)); assertEquals(e.getMessage(), "supplier can't be null"); }
protected boolean isWebJar(Dependency dependency, Dependency nextDependency) { if (dependency == null || dependency.getFileName() == null || nextDependency == null || nextDependency.getFileName() == null || dependency.getSoftwareIdentifiers().isEmpty() || nextDepe...
@Test public void testIsWebJar() throws MalformedPackageURLException { DependencyBundlingAnalyzer instance = new DependencyBundlingAnalyzer(); Dependency left = null; Dependency right = null; boolean expResult = false; boolean result = instance.isWebJar(left, right); ...
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@Test public void shouldNotAllowNullValueJoinerWithKeyOnLeftJoinWithGlobalTableWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin( testGlobalTable, MockMapper.selectValueMapp...
@Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try ...
@Test public void testExecute() { UpdateTopicPermSubCommand cmd = new UpdateTopicPermSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster", "-t unit-test", "-p 6"}; final CommandL...
@Override public String getPrefix() { return String.format("%s.%s", SpectraProtocol.class.getPackage().getName(), "Spectra"); }
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.spectra.Spectra", new SpectraProtocol().getPrefix()); }
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseWxworkTest() { final String uaString = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1326.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safa...
@Override public int hashCode() { return executionId.hashCode() + executionState.ordinal(); }
@Test public void testSerialization() { try { final ExecutionAttemptID executionId = createExecutionAttemptId(); final ExecutionState state = ExecutionState.DEPLOYING; final Throwable error = new IOException("fubar"); TaskExecutionState original1 = new TaskEx...
static void setPropertiesForRecipientList( RecipientList recipientList, CamelContext camelContext, DynamicRouterConfiguration cfg) { recipientList.setAggregationStrategy(createAggregationStrategy(camelContext, cfg)); recipientList.setParallelProcessing(cfg.isParallelProcessing()); re...
@Test void testSetPropertiesForRecipientList() { // Set up mocking when(mockConfig.isParallelProcessing()).thenReturn(true); when(mockConfig.isParallelAggregate()).thenReturn(true); when(mockConfig.isSynchronous()).thenReturn(true); when(mockConfig.isStreaming()).thenReturn(t...
public static int stringHash(Client client) { String s = buildUniqueString(client); if (s == null) { return 0; } return s.hashCode(); }
@Test void performanceTestOfStringHash() { long start = System.nanoTime(); for (int i = 0; i < N; i++) { DistroUtils.stringHash(client1); } System.out.printf("Distro Verify Revision Performance: %.2f ivk/ns\n", ((double) System.nanoTime() - start) / N); }
@Override public List<String> readMultiParam(String key) { String[] values = source.getParameterValues(key); return values == null ? emptyList() : ImmutableList.copyOf(values); }
@Test public void read_multi_param_from_source_with_one_value() { when(source.getParameterValues("param")).thenReturn(new String[]{"firstValue"}); List<String> result = underTest.readMultiParam("param"); assertThat(result).containsExactly("firstValue"); }
@Override public Page<ConfigInfoTagWrapper> findAllConfigInfoTagForDumpAll(final int pageNo, final int pageSize) { final int startRow = (pageNo - 1) * pageSize; ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CON...
@Test void testFindAllConfigInfoTagForDumpAll() { //mock count Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(308); List<ConfigInfoTagWrapper> mockTagList = new ArrayList<>(); mockTagList.add(new ConfigInfoTagWrapper()); mockTagL...
public HollowOrdinalIterator findKeysWithPrefix(String prefix) { TST current; HollowOrdinalIterator it; do { current = prefixIndexVolatile; it = current.findKeysWithPrefix(prefix); } while (current != this.prefixIndexVolatile); return it; }
@Test public void testMovieActorReference() throws Exception { List<Actor> actors = Arrays.asList(new Actor("Keanu Reeves"), new Actor("Laurence Fishburne"), new Actor("Carrie-Anne Moss")); MovieActorReference movieSetReference = new MovieActorReference(1, 1999, "The Matrix", actors); object...
@Override public KeyValueIterator<Windowed<K>, V> fetchAll(final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return new KeyValueIteratorFacade<>(inner.fetchAll(timeFrom, timeTo)); }
@Test public void shouldReturnPlainKeyValuePairsOnFetchAllLongParameters() { when(mockedKeyValueWindowTimestampIterator.next()) .thenReturn(KeyValue.pair( new Windowed<>("key1", new TimeWindow(21L, 22L)), ValueAndTimestamp.make("value1", 22L))) .thenRe...
public synchronized ResultSet fetchResults(FetchOrientation orientation, int maxFetchSize) { long token; switch (orientation) { case FETCH_NEXT: token = currentToken; break; case FETCH_PRIOR: token = currentToken - 1; ...
@Test void testFetchIllegalToken() { ResultFetcher fetcher = buildResultFetcher(Collections.singletonList(data.iterator()), data.size()); assertThatThrownBy(() -> fetcher.fetchResults(2, Integer.MAX_VALUE)) .satisfies(FlinkAssertions.anyCauseMatches("Expecting token t...
public static <InputT> GloballyDistinct<InputT> globally() { return GloballyDistinct.<InputT>builder().build(); }
@Test public void smallCardinality() { final int smallCard = 1000; final int p = 6; final double expectedErr = 1.104 / Math.sqrt(p); List<Integer> small = new ArrayList<>(); for (int i = 0; i < smallCard; i++) { small.add(i); } PCollection<Long> cardinality = tp.apply("smal...
public FEELFnResult<TemporalAmount> invoke(@ParameterName("from") Temporal from, @ParameterName("to") Temporal to) { if ( from == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } if ( to == null ) { return FEELF...
@Test void invokeLocalDateLocalDate() { FunctionTestUtil.assertResult( yamFunction.invoke( LocalDate.of(2017, 6, 12), LocalDate.of(2020, 7, 13)), ComparablePeriod.of(3, 1, 0)); }
@Override public void stop() { try { // Removing the worker UUIDs getClusteredWorkerUUIDs().remove(hazelcastMember.getUuid()); } catch (HazelcastInstanceNotActiveException | RetryableHazelcastException e) { LOGGER.debug("Hazelcast is not active anymore", e); } }
@Test public void stop_whenThrowHazelcastInactiveException_shouldSilenceError() { logTester.setLevel(Level.DEBUG); when(hzClientWrapper.getReplicatedMap(any())).thenThrow(new HazelcastInstanceNotActiveException("Hazelcast is not active")); CeDistributedInformationImpl ceDistributedInformation = new CeDis...
public void runExtractor(Message msg) { try(final Timer.Context ignored = completeTimer.time()) { final String field; try (final Timer.Context ignored2 = conditionTimer.time()) { // We can only work on Strings. if (!(msg.getField(sourceField) instanceof St...
@Test public void testConvertersThatReturnNullValue() throws Exception { final Converter converter = new TestConverter.Builder() .callback(new Function<Object, Object>() { @Nullable @Override public Object apply(Object input) { ...
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR if (splittee == null || splitChar == null) { return new String[0]; } final String EMPTY_ELEMENT = ""; int spot; final int splitLength = splitChar.length(); final Stri...
@Test public void testSplitStringStringFalseDoubledSplitChar() throws Exception { assertThat(JOrphanUtils.split("a;;b;;;;;;d;;e;;;;f", ";;", false), CoreMatchers.equalTo(new String[]{"a", "b", "", "", "d", "e", "", "f"})); }
public Json removePadding(String padding) { String text = getFirstSourceText(); XTokenQueue tokenQueue = new XTokenQueue(text); tokenQueue.consumeWhitespace(); tokenQueue.consume(padding); tokenQueue.consumeWhitespace(); String chompBalanced = tokenQueue.chompBalancedNotI...
@Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); }
@Override public O apply(final E e) { if (o != null) { return o; } return init(e); }
@Test public void testApply() { Function<String, String> function = Function.identity(); FreshBeanHolder<String, String> freshBeanHolder = new FreshBeanHolder<>(function); assertEquals("hello", freshBeanHolder.apply("hello")); }
public Config setProperty(@Nonnull String name, @Nonnull String value) { if (isNullOrEmptyAfterTrim(name)) { throw new IllegalArgumentException("argument 'name' can't be null or empty"); } isNotNull(value, "value"); properties.setProperty(name, value); return this; ...
@Test(expected = IllegalArgumentException.class) public void testSetConfigPropertyNameEmpty() { config.setProperty(" ", "test"); }
@Override protected JobConfigInfo handleRequest( HandlerRequest<EmptyRequestBody> request, AccessExecutionGraph executionGraph) { return createJobConfigInfo(executionGraph); }
@Test void handleRequest_executionConfigWithSecretValues_excludesSecretValuesFromResponse() throws HandlerRequestException { final JobConfigHandler jobConfigHandler = new JobConfigHandler( () -> null, TestingUtils.TIMEOUT, ...
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void testAntarcticaTZ() throws Exception { NaturalDateParser.Result today = naturalDateParserAntarctica.parse("today"); assertThat(today.getFrom()).as("From should not be null").isNotNull(); assertThat(today.getTo()).as("To should not be null").isNotNull(); assertThat(to...
public int getWorkerId() { return instance.getWorkerId(); }
@Test void assertGetWorkerId() { ComputeNodeInstance computeNodeInstance = mock(ComputeNodeInstance.class); when(computeNodeInstance.getWorkerId()).thenReturn(0); ComputeNodeInstanceContext context = new ComputeNodeInstanceContext(computeNodeInstance, mock(WorkerIdGenerator.class), modeConfi...
@Override public void run() { try { Date now = new Date(); LOG.info("SubClusterCleaner at {}", now); Map<SubClusterId, SubClusterInfo> infoMap = this.gpgContext.getStateStoreFacade().getSubClusters(false, true); // Iterate over each sub cluster and check last heartbeat fo...
@Test public void testSubClusterRegisterHeartBeatTime() throws YarnException { cleaner.run(); Assert.assertEquals(3, facade.getSubClusters(true, true).size()); }
public static YarnApplicationAttemptState convertRmAppAttemptStateToYarnApplicationAttemptState( RMAppAttemptState currentState, RMAppAttemptState previousState ) { return createApplicationAttemptState( currentState == RMAppAttemptState.FINAL_SAVING ? previousState : currentSta...
@Test public void testConvertRmAppAttemptStateToYarnApplicationAttemptState() { Assert.assertEquals( YarnApplicationAttemptState.FAILED, RMServerUtils.convertRmAppAttemptStateToYarnApplicationAttemptState( RMAppAttemptState.FINAL_SAVING, RMAppAttemptState.FAILED ) ...
@Override public Database getDb(String name) { try { return new Database(ConnectorTableId.CONNECTOR_ID_GENERATOR.getNextId().asInt(), name); } catch (StarRocksConnectorException e) { e.printStackTrace(); return null; } }
@Test public void testGetDb() { Database database = odpsMetadata.getDb("project"); Assert.assertNotNull(database); Assert.assertEquals(database.getFullName(), "project"); }
@Override public void start() { this.all = registry.meter(name(getName(), "all")); this.trace = registry.meter(name(getName(), "trace")); this.debug = registry.meter(name(getName(), "debug")); this.info = registry.meter(name(getName(), "info")); this.warn = registry.meter(nam...
@Test public void usesSharedRegistries() { String registryName = "registry"; SharedMetricRegistries.add(registryName, registry); final InstrumentedAppender shared = new InstrumentedAppender(registryName); shared.start(); when(event.getLevel()).thenReturn(Level.INFO); ...
public static Autoscaling empty() { return empty(""); }
@Test public void test_autoscaling_in_dev_with_required_resources_preprovisioned() { var requiredCapacity = Capacity.from(new ClusterResources(2, 1, new NodeResources(1, 1, 1, 1, NodeResources.DiskSpeed.any)), n...
public MastershipInfo mastershipInfo() { return mastershipInfo; }
@Test public void checkConstruction() { assertThat(event1.type(), is(MastershipEvent.Type.BACKUPS_CHANGED)); assertThat(event1.subject(), is(deviceId1)); assertThat(event1.mastershipInfo(), is(mastershipInfo1)); assertThat(event4.time(), is(time)); assertThat(event4.type(), ...
public SerializableFunction<Row, T> getFromRowFunction() { return fromRowFunction; }
@Test public void testNullMapRowToProto() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(MapPrimitive.getDescriptor()); SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction(); MapPrimitive proto = parseFrom(fromRow.apply(NULL_MAP_PRIMITIVE_ROW).t...
public static synchronized void w(final String tag, String text, Object... args) { if (msLogger.supportsW()) { String msg = getFormattedString(text, args); msLogger.w(tag, msg); addLog(LVL_W, tag, msg); } }
@Test public void testW() throws Exception { Logger.w("mTag", "Text with %d digits", 0); Mockito.verify(mMockLog).w("mTag", "Text with 0 digits"); Logger.w("mTag", "Text with no digits"); Mockito.verify(mMockLog).w("mTag", "Text with no digits"); }
@DeleteMapping("/token") @PermitAll @Operation(summary = "删除访问令牌") @Parameter(name = "token", required = true, description = "访问令牌", example = "biu") public CommonResult<Boolean> revokeToken(HttpServletRequest request, @RequestParam("token") String token) { ...
@Test public void testRevokeToken() { // 准备参数 HttpServletRequest request = mockRequest("demo_client_id", "demo_client_secret"); String token = randomString(); // mock 方法(client) OAuth2ClientDO client = randomPojo(OAuth2ClientDO.class).setClientId("demo_client_id"); wh...
@Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc, boolean addFieldName, boolean addCr ){ return fallback.getFieldDefinition( v, tk, pk, useAutoinc, addFieldName, addCr ); }
@Test public void testStringFieldDef() throws Exception { AthenaDatabaseMeta dbricks = new AthenaDatabaseMeta(); String fieldDef = dbricks.getFieldDefinition( new ValueMetaString( "name" ), null, null, false, false, false ); assertEquals( "VARCHAR()", fieldDef ); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void filterExpression() { String inputExpression = "[ {x:1, y:2}, {x:2, y:3} ][ x=1 ]"; BaseNode filterBase = parse( inputExpression ); assertThat( filterBase).isInstanceOf(FilterExpressionNode.class); assertThat( filterBase.getText()).isEqualTo(inputExpression); Filt...
public static boolean isBeanPropertyReadMethod(Method method) { return method != null && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getReturnType() != void.class && method.getDeclaringClass() != ...
@Test void testIsBeanPropertyReadMethod() throws Exception { Method method = EmptyClass.class.getMethod("getProperty"); assertTrue(ReflectUtils.isBeanPropertyReadMethod(method)); method = EmptyClass.class.getMethod("getProperties"); assertFalse(ReflectUtils.isBeanPropertyReadMethod(m...
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { ...
@Test public void testFetchNormal() { int recordCount = DEFAULT_MAX_POLL_RECORDS; buildDependencies(); assignAndSeek(topicAPartition0); CompletedFetch completedFetch = completedFetchBuilder .recordCount(recordCount) .build(); // Validate that...
@Override public boolean registry(ServiceInstance serviceInstance) { checkDiscoveryState(); if (getZkClient().isStateOk()) { return registrySync(serviceInstance); } return registryAsync(serviceInstance); }
@Test public void registry() throws Exception { final DefaultServiceInstance instance = new DefaultServiceInstance("localhost", "127.0.0.1", 8080, Collections.emptyMap(), serviceName); final boolean result = zkDiscoveryClient.registry(instance); Assert.assertTrue(result); ...
public static boolean checkRegexResourceField(AbstractRule rule) { if (!rule.isRegex()) { return true; } String resourceName = rule.getResource(); try { Pattern.compile(resourceName); return true; } catch (Exception e) { return fals...
@Test public void testValidRegexRule() { // Setup FlowRule flowRule = new FlowRule(); flowRule.setRegex(true); flowRule.setResource("{}"); // Run the test and verify Assert.assertFalse(RuleManager.checkRegexResourceField(flowRule)); flowRule.setResource(".*")...
public PutMessageResult putMessage(MessageExtBrokerInner messageExt) { BrokerController masterBroker = this.brokerController.peekMasterBroker(); if (masterBroker != null) { return masterBroker.getMessageStore().putMessage(messageExt); } else if (this.brokerController.getBrokerConfig(...
@Test public void putMessageTest() { messageExtBrokerInner.setTopic(TEST_TOPIC); messageExtBrokerInner.setQueueId(DEFAULT_QUEUE_ID); messageExtBrokerInner.setBody("Hello World".getBytes(StandardCharsets.UTF_8)); // masterBroker is null final PutMessageResult result1 = escapeB...
public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException { checkMaybeCompatible(source, target); if (source.isOptional() && !target.isOptional()) { if (target.defaultValue() != null) { if (record != null) { ...
@Test public void testNestedSchemaProjection() { Schema sourceFlatSchema = SchemaBuilder.struct() .field("field", Schema.INT32_SCHEMA) .build(); Schema targetFlatSchema = SchemaBuilder.struct() .field("field", Schema.INT32_SCHEMA) .fiel...
public SerializableFunction<T, Row> getToRowFunction() { return toRowFunction; }
@Test public void testOneOfProtoToRow() throws InvalidProtocolBufferException { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(OneOf.getDescriptor()); SerializableFunction<DynamicMessage, Row> toRow = schemaProvider.getToRowFunction(); // equality doesn't work between dynamic messages and...
@Override public PageResult<ProductSpuDO> getSpuPage(ProductSpuPageReqVO pageReqVO) { return productSpuMapper.selectPage(pageReqVO); }
@Test void getSpuPage_alarmStock() { // 准备参数 ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{ o.setCategoryId(generateId()); o.setBrandId(generateId()); o.setDeliveryTemplateId(generateId()); o.setSort(Random...
@DELETE @Consumes(MediaType.APPLICATION_JSON) @Path("{component}") public Response unsetConfigs(@PathParam("component") String component, InputStream request) throws IOException { ComponentConfigService service = get(ComponentConfigService.class); ObjectNode ...
@Test public void unsetConfigs() { WebTarget wt = target(); try { // TODO: this needs to be revised later. Do you really need to // contain any entry inside delete request? Why not just use put then? wt.path("configuration/foo").request().delete(); } catch...
static AllManifestsTable.ManifestListReadTask fromJson(JsonNode jsonNode) { Preconditions.checkArgument(jsonNode != null, "Invalid JSON node for manifest task: null"); Preconditions.checkArgument( jsonNode.isObject(), "Invalid JSON node for manifest task: non-object (%s)", jsonNode); Schema dataTab...
@Test public void invalidJsonNode() throws Exception { String jsonStr = "{\"str\":\"1\", \"arr\":[]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.reader().readTree(jsonStr); assertThatThrownBy(() -> AllManifestsTableTaskParser.fromJson(rootNode.get("str"))) .isInstan...
@Override public void configure(final Map<String, ?> config) { configure( config, new Options(), org.rocksdb.LRUCache::new, org.rocksdb.WriteBufferManager::new ); }
@Test public void shouldSetNumThreads() { // When: KsqlBoundedMemoryRocksDBConfigSetter.configure( CONFIG_PROPS, rocksOptions, cacheFactory, bufferManagerFactory ); // Then: verify(env).setBackgroundThreads(NUM_BACKGROUND_THREADS); }
@Override public void clear() { repo.clear(); }
@Test public void testClear() throws Exception { // ADD key to remove assertTrue(repo.add(key01)); assertEquals(1, cache.size()); // remove key assertTrue(repo.remove(key01)); assertEquals(0, cache.size()); // try to remove a key that isn't there ass...
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR if (splittee == null || splitChar == null) { return new String[0]; } final String EMPTY_ELEMENT = ""; int spot; final int splitLength = splitChar.length(); final Stri...
@Test public void testSplitSSSWithEmptyDelimiter() { final String in = "a,;bc,;,"; assertThat(JOrphanUtils.split(in, "", "x"), CoreMatchers.equalTo(new String[]{in})); }
@ShellMethod(key = "show logfile records", value = "Read records from log files") public String showLogFileRecords( @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "10") final Integer limit, @ShellOption(value = "--logFilePathPattern", help = "Fully qualified p...
@Test public void testShowLogFileRecords() throws IOException, URISyntaxException { Object result = shell.evaluate(() -> "show logfile records --logFilePathPattern " + partitionPath + "/*"); assertTrue(ShellEvaluationResultUtil.isSuccess(result)); // construct expect result, get 10 records. List<Inde...
@SuppressWarnings("unchecked") public static <R> R getStaticField(Field field) { try { field.setAccessible(true); return (R) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void getStaticFieldReflectively_withField_getsStaticField() throws Exception { Field field = ExampleDescendant.class.getDeclaredField("DESCENDANT"); int result = ReflectionHelpers.getStaticField(field); assertThat(result).isEqualTo(6); }
public void reschedule(Node<K, V> node) { if (node.getNextInVariableOrder() != null) { unlink(node); schedule(node); } }
@Test(dataProvider = "clock") public void reschedule(long clock) { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; var timer = new Timer(clock + TimeUnit.MINUTES.toNanos(15)); timerWheel.schedule(timer); var startBucket = timer.getNextInVaria...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (!(obj instanceof Dimension)) { return false; } Dimension other = (Dimension) obj; if (this.width != other.width) { return false; } else if (thi...
@Test public void equalsTest() { Dimension dimension1 = new Dimension(1, 2); Dimension dimension2 = new Dimension(1, 2); Dimension dimension3 = new Dimension(1, 1); Dimension dimension4 = new Dimension(2, 2); TestUtils.equalsTest(dimension1, dimension2); TestUtils.n...
private void removeDevice(final DeviceId deviceId) { discoverers.computeIfPresent(deviceId, (did, ld) -> { ld.stop(); return null; }); }
@Test public void testRemoveDevice() { assertThat(provider.discoverers.entrySet(), hasSize(2)); deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3)); assertThat(provider.discoverers.entrySet(), hasSize(3)); deviceListener.event(new DeviceEvent(DeviceEvent.Type.D...
public static void main(String[] args) { var service = ServiceLocator.getService(JNDI_SERVICE_A); service.execute(); service = ServiceLocator.getService(JNDI_SERVICE_B); service.execute(); service = ServiceLocator.getService(JNDI_SERVICE_A); service.execute(); service = ServiceLocator.getSer...
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@POST @Path(RMWSConsts.SCHEDULER_LOGS) @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public String dumpSchedulerLogs(@FormParam(RMWSConsts.TIME) String time, @Context HttpServletRequest hsr) throws IOException { ...
@Test public void testDumpingSchedulerLogs() throws Exception { ResourceManager mockRM = mock(ResourceManager.class); Configuration conf = new YarnConfiguration(); HttpServletRequest mockHsr = mockHttpServletRequestByUserName("non-admin"); ApplicationACLsManager aclsManager = new ApplicationACLsManag...
@Override public void add(long key, String value) { // fix https://github.com/crossoverJie/cim/issues/79 sortArrayMap.clear(); for (int i = 0; i < VIRTUAL_NODE_SIZE; i++) { Long hash = super.hash("vir" + key + i); sortArrayMap.add(hash,value); } sortAr...
@Test public void getFirstNodeValue5() { AbstractConsistentHash map = new SortArrayMapConsistentHash() ; List<String> strings = new ArrayList<String>(); strings.add("45.78.28.220:9000:8081") ; strings.add("45.78.28.220:9100:9081") ; strings.add("45.78.28.220:9100:10081") ; ...
public MeasureDto toMeasureDto(Measure measure, Metric metric, Component component) { MeasureDto out = new MeasureDto(); out.setMetricUuid(metric.getUuid()); out.setComponentUuid(component.getUuid()); out.setAnalysisUuid(analysisMetadataHolder.getUuid()); if (measure.hasQualityGateStatus()) { ...
@Test public void toMeasureDto_returns_Dto_with_alertStatus_and_alertText_if_Measure_has_QualityGateStatus() { String alertText = "some error"; MeasureDto measureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().setQualityGateStatus(new QualityGateStatus(Measure.Level.ERROR, alertText)).create(SOME_STR...
@SuppressWarnings("checkstyle:magicnumber") void writeLong(long value) { if (value == Long.MIN_VALUE) { write(STR_LONG_MIN_VALUE); return; } if (value < 0) { write('-'); value = -value; } int digitsWithoutComma = 0; tm...
@Test public void writeLong() { assertLongValue(0); assertLongValue(10); assertLongValue(100); assertLongValue(1000); assertLongValue(10000); assertLongValue(100000); assertLongValue(1000000); assertLongValue(10000000); assertLongValue(10000000...
@Modified public void modified(ComponentContext context) { if (context == null) { log.info("No component configuration"); return; } Dictionary<?, ?> properties = context.getProperties(); int newPollFrequency = getNewPollFrequency(properties, alarmPollFrequenc...
@Test public void modified() throws Exception { provider.modified(null); assertEquals("Incorrect polling frequency", 1, provider.alarmPollFrequencySeconds); provider.activate(null); provider.modified(context); assertEquals("Incorrect polling frequency", 1, provider.alarmPollF...
@Override public RandomAccessReadView createView(long startPosition, long streamLength) throws IOException { throw new IOException(getClass().getName() + ".createView isn't supported."); }
@Test void testView() throws IOException { byte[] inputValues = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ByteArrayInputStream bais = new ByteArrayInputStream(inputValues); try (NonSeekableRandomAccessReadInputStream randomAccessSource = new NonSeekableRandomAccessReadInputStream( ...
void readEntries(ReadHandle lh, long firstEntry, long lastEntry, boolean shouldCacheEntry, final AsyncCallbacks.ReadEntriesCallback callback, Object ctx) { final PendingReadKey key = new PendingReadKey(firstEntry, lastEntry); Map<PendingReadKey, PendingRead> pendingReadsForLedger =...
@Test public void simpleRead() throws Exception { long firstEntry = 100; long endEntry = 199; boolean shouldCacheEntry = false; PreparedReadFromStorage read1 = prepareReadFromStorage(lh, rangeEntryCache, firstEntry, endEntry, shouldCacheEntry); CapturingRea...
public Node node() { return node; }
@Test void testNode() { int index = 0; Node node = new Node(index); assertEquals(index, node.index()); }
static void run(String resolverPath, String rootPath, String targetDirectoryPath, String[] sources) throws IOException { final DataSchemaResolver schemaResolver = MultiFormatDataSchemaResolver.withBuiltinFormats(resolverPath); VelocityEngine velocityEngine = initVelocityEngine(); final File targetDi...
@Test() public void testBasic() throws Exception { final String pegasusDir = moduleDir + FS + RESOURCES_DIR + FS + "pegasus"; final String outPath = outdir.getPath(); FluentApiGenerator.run(pegasusDir, moduleDir, outPath, new String[] { moduleDir + FS + RESOURCES_DIR ...
public void project() { srcPotentialIndex = 0; trgPotentialIndex = 0; recurse(0, 0); BayesAbsorption.normalize(trgPotentials); }
@Test public void testProjection2() { // Projects from node1 into sep. A, B and C are in node1. A and B are in the sep. // this tests a non separator var, after the vars BayesVariable a = new BayesVariable<String>( "A", 0, new String[] {"A1", "A2"}, new double[][] {{0.1, 0.2}}); Bay...
@VisibleForTesting void validateRoleDuplicate(String name, String code, Long id) { // 0. 超级管理员,不允许创建 if (RoleCodeEnum.isSuperAdmin(code)) { throw exception(ROLE_ADMIN_CODE_ERROR, code); } // 1. 该 name 名字被其它角色所使用 RoleDO role = roleMapper.selectByName(name); ...
@Test public void testValidateRoleDuplicate_nameDuplicate() { // mock 数据 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setName("role_name")); roleMapper.insert(roleDO); // 准备参数 String name = "role_name"; // 调用,并断言异常 assertServiceException(() -> roleService....
@CanIgnoreReturnValue public final Ordered containsExactly() { return containsExactlyEntriesIn(ImmutableMap.of()); }
@Test public void containsExactlyWrongValue_sameToStringForValues() { expectFailureWhenTestingThat(ImmutableMap.of("jan", 1L, "feb", 2L)) .containsExactly("jan", 1, "feb", 2); assertFailureKeys( "keys with wrong values", "for key", "expected value", "but got value", ...
@Override public void start() throws Exception { if (!state.compareAndSet(State.LATENT, State.STARTED)) { throw new IllegalStateException(); } try { client.create().creatingParentContainersIfNeeded().forPath(queuePath); } catch (KeeperException.NodeExistsExce...
@Test public void testSafetyBasic() throws Exception { final int itemQty = 10; DistributedQueue<TestQueueItem> queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final B...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testRofOne() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_RING_OF_FORGING_ONE, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_RING_OF_FORGING, 1); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) { RedirectionRequest wsRequest = new RedirectionRequest(request); ServletResponse wsResponse = new ServletResponse(response); webServiceEngine.execute(wsRequest, wsResponse); }
@Test public void redirect_components_update_key() { when(request.getServletPath()).thenReturn("/api/components/update_key"); when(request.getMethod()).thenReturn("POST"); underTest.doFilter(new JavaxHttpRequest(request), new JavaxHttpResponse(response), chain); assertRedirection("/api/projects/upda...
@SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops"}) public void validate(Workflow workflow, User caller) { try { RunProperties runProperties = new RunProperties(); runProperties.setOwner(caller); Map<String, ParamDefinition> workflowParams = workflow.getParams(); Map<String, ParamD...
@Test public void testValidateFailStepMerge() { when(paramsManager.generateMergedWorkflowParams(any(), any())) .thenReturn(new LinkedHashMap<>()); when(paramsManager.generateMergedStepParams(any(), any(), any(), any())) .thenThrow(new MaestroValidationException("Error validating")); Assert...
public Mono<CosmosItemResponse<Object>> deleteItem( final String itemId, final PartitionKey partitionKey, final CosmosItemRequestOptions itemRequestOptions) { CosmosDbUtils.validateIfParameterIsNotEmpty(itemId, PARAM_ITEM_ID); CosmosDbUtils.validateIfParameterIsNotEmpty(partitionKey, PARAM_P...
@Test void deleteItem() { final CosmosDbContainerOperations operations = new CosmosDbContainerOperations(Mono.just(mock(CosmosAsyncContainer.class))); CosmosDbTestUtils.assertIllegalArgumentException(() -> operations.deleteItem(null, null, null)); CosmosDbTestUtils.assertIll...
public Meter meter(String name) { return getOrAdd(name, MetricBuilder.METERS); }
@Test public void accessingACustomMeterRegistersAndReusesIt() { final MetricRegistry.MetricSupplier<Meter> supplier = () -> meter; final Meter meter1 = registry.meter("thing", supplier); final Meter meter2 = registry.meter("thing", supplier); assertThat(meter1) .isSa...
public static ImmutableList<String> glob(final String glob) { Path path = getGlobPath(glob); int globIndex = getGlobIndex(path); if (globIndex < 0) { return of(glob); } return doGlob(path, searchPath(path, globIndex)); }
@Test public void should_glob_absolute_files_with_glob(@TempDir final Path folder) throws IOException { Path tempFile = folder.resolve("glob.json"); java.nio.file.Files.createFile(tempFile); File file = tempFile.toFile(); String glob = Files.join(folder.toFile().getAbsolutePath(), "...
public static int getOcuranceString( String string, String searchFor ) { if ( string == null || string.length() == 0 ) { return 0; } Pattern p = Pattern.compile( searchFor ); Matcher m = p.matcher( string ); int count = 0; while ( m.find() ) { ++count; } return count; }
@Test public void testGetOcuranceString() { assertEquals( 0, Const.getOcuranceString( "", "" ) ); assertEquals( 0, Const.getOcuranceString( "foo bar bazfoo", "cat" ) ); assertEquals( 2, Const.getOcuranceString( "foo bar bazfoo", "foo" ) ); }
@Override public Mono<UserDetails> findByUsername(String username) { return userService.getUser(username) .onErrorMap(UserNotFoundException.class, e -> new BadCredentialsException("Invalid Credentials")) .flatMap(user -> { var name = user.getMetadata()...
@Test void shouldFindHaloUserDetailsWith2faDisabledWhen2faEnabledButNoTotpConfigured() { var fakeUser = createFakeUser(); fakeUser.getSpec().setTwoFactorAuthEnabled(true); when(userService.getUser("faker")).thenReturn(Mono.just(fakeUser)); when(roleService.getRolesByUsername("faker")...
@Override public void process(Exchange exchange) throws Exception { final SchematronProcessor schematronProcessor = SchematronProcessorFactory.newSchematronEngine(endpoint.getRules()); final Object payload = exchange.getIn().getBody(); final String report; if (payload instanceof Sou...
@Test public void testProcessInValidXMLAsSource() throws Exception { Exchange exc = new DefaultExchange(context, ExchangePattern.InOut); exc.getIn().setBody( new SAXSource(getXMLReader(), new InputSource(ClassLoader.getSystemResourceAsStream("xml/article-2.xml")))); // proce...
@Override public synchronized void write(int b) throws IOException { mUfsOutStream.write(b); mBytesWritten++; }
@Test public void singleByteWrite() throws IOException, AlluxioException { byte byteToWrite = 5; AlluxioURI ufsPath = getUfsPath(); try (FileOutStream outStream = mFileSystem.createFile(ufsPath)) { outStream.write(byteToWrite); } try (InputStream inputStream = mFileSystem.openFile(ufsPath)) ...
@Override public List<SimpleColumn> toColumns( final ParsedSchema schema, final SerdeFeatures serdeFeatures, final boolean isKey) { SerdeUtils.throwOnUnsupportedFeatures(serdeFeatures, format.supportedFeatures()); Schema connectSchema = connectSrTranslator.toConnectSchema(schema); if (...
@Test public void shouldSupportBuildingColumnsFromPrimitiveKeySchema() { // Given: when(format.supportedFeatures()).thenReturn(Collections.singleton(SerdeFeature.UNWRAP_SINGLES)); // When: translator.toColumns(parsedSchema, SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES), true); // Then: verif...
public Optional<Measure> toMeasure(@Nullable LiveMeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getDataAsString(); switch (metric.getType().getValueType()) {...
@Test public void toMeasure_returns_no_value_if_dto_has_no_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
@Deprecated public void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { synchronized (stateLock) { if (state.hasNotStarted()) { oldHandler = true; processStreamThread(thread -> thread.setUncaughtExceptionHandler(uncaug...
@Test public void shouldThrowNullPointerExceptionSettingStreamsUncaughtExceptionHandlerIfNull() { prepareStreams(); prepareStreamThread(streamThreadOne, 1); prepareStreamThread(streamThreadTwo, 2); try (final KafkaStreams streams = new KafkaStreams(getBuilderWithSource().build(), pro...
public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ...
@Test public void testRMDownRestoreForJobStatusBeforeGetAMReport() throws IOException { Configuration conf = new YarnConfiguration(); conf.setInt(MRJobConfig.MR_CLIENT_MAX_RETRIES, 3); conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME); conf.setBoolean(MRJobConfig.JOB_AM_ACCESS_DIS...
@Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { try { try { if(!new DriveAttributesFinderFeature(session, fileid).find(file).isHidden()) { throw new ConflictException(file.getAbsolute()); }...
@Test public void testTouch() throws Exception { final DriveFileIdProvider fileid = new DriveFileIdProvider(session); final Path folder = new DriveDirectoryFeature(session, fileid).mkdir( new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), ...
@Override public void process(Exchange exchange) throws Exception { try { plc4XEndpoint.reconnectIfNeeded(); } catch (PlcConnectionException e) { if (log.isTraceEnabled()) { log.warn("Unable to reconnect, skipping request", e); } else { ...
@Test public void processAsync() { sut.process(testExchange, doneSync -> { }); when(testExchange.getPattern()).thenReturn(ExchangePattern.InOnly); sut.process(testExchange, doneSync -> { }); when(testExchange.getPattern()).thenReturn(ExchangePattern.InOut); su...
@Operation(summary = "list", description = "List hosts") @GetMapping public ResponseEntity<List<HostVO>> list(@PathVariable Long clusterId) { return ResponseEntity.success(hostService.list(clusterId)); }
@Test void listReturnsAllHosts() { Long clusterId = 1L; List<HostVO> hosts = Arrays.asList(new HostVO(), new HostVO()); when(hostService.list(clusterId)).thenReturn(hosts); ResponseEntity<List<HostVO>> response = hostController.list(clusterId); assertTrue(response.isSuccess...
@Override public GZIPCompressionOutputStream createOutputStream( OutputStream out ) throws IOException { return new GZIPCompressionOutputStream( out, this ); }
@Test public void testCreateOutputStream() throws IOException { GZIPCompressionProvider provider = (GZIPCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME ); ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream( out ); GZIPCompressi...
static <P> Matcher[] toArray(Iterable<? extends Matcher<P>> matchers) { if (matchers == null) throw new NullPointerException("matchers == null"); if (matchers instanceof Collection) { return (Matcher[]) ((Collection) matchers).toArray(new Matcher[0]); } List<Matcher<P>> result = new ArrayList<Matc...
@Test void toArray_iterable() { Matcher<Void> one = b -> true; Matcher<Void> two = b -> false; Matcher<Void> three = b -> true; assertThat(Matchers.toArray(() -> asList(one, two, three).iterator())) .containsExactly(one, two, three); }
public static UpdateRequirement fromJson(String json) { return JsonUtil.parse(json, UpdateRequirementParser::fromJson); }
@Test public void testAssertViewUUIDFromJson() { String requirementType = UpdateRequirementParser.ASSERT_VIEW_UUID; String uuid = "2cc52516-5e73-41f2-b139-545d41a4e151"; String json = String.format("{\"type\":\"assert-view-uuid\",\"uuid\":\"%s\"}", uuid); UpdateRequirement expected = new UpdateRequire...
@NonNull public static List<VideoStream> getSortedStreamVideosList( @NonNull final Context context, @Nullable final List<VideoStream> videoStreams, @Nullable final List<VideoStream> videoOnlyStreams, final boolean ascendingOrder, final boolean preferVideoO...
@Test public void getSortedStreamVideosListTest() { List<VideoStream> result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, true, VIDEO_STREAMS_TEST_LIST, VIDEO_ONLY_STREAMS_TEST_LIST, true, false); List<String> expected = List.of("144p", "240p", "360p", "480p", "720p", ...
@Override public String getPolicyName() { return LoadBalancerStrategy.RANDOM.getStrategy(); }
@Test public void testGetPolicyName() { assertEquals(randomLoadBalancerProvider.getPolicyName(), LoadBalancerStrategy.RANDOM.getStrategy()); }
public static IndexIterationPointer create( @Nullable Comparable<?> from, boolean fromInclusive, @Nullable Comparable<?> to, boolean toInclusive, boolean descending, @Nullable Data lastEntryKey ) { return new IndexIterationPointer( ...
@Test void createBadSingleton() { assertThatThrownBy(() -> create(5, true, 5, false, false, null)) .isInstanceOf(AssertionError.class).hasMessageContaining("Point lookup limits must be all inclusive"); assertThatThrownBy(() -> create(5, false, 5, true, false, null)) ....
public static DataMap parseDataMapKeys(Map<String, List<String>> queryParameters) throws PathSegmentSyntaxException { // The parameters are parsed into an intermediary structure comprised of // HashMap<String,Object> and HashMap<Integer,Object>, defined respectively // as MapMap and ListMap for convenienc...
@Test public void testParseDataMapKeys() throws Exception { String testQS = "ids[0].params.versionTag=tag1&ids[0].params.authToken=tok1&ids[0].memberID=1&ids[0].groupID=2&" + "ids[1].params.versionTag=tag2&ids[1].params.authToken=tok2&ids[1].memberID=2&ids[1].groupID=2&" + ...