focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public String toBaseMessageIdString(Object messageId) { if (messageId == null) { return null; } else if (messageId instanceof String) { String stringId = (String) messageId; // If the given string has a type encoding prefix, // we need to escape it as an ...
@Test public void testToBaseMessageIdStringWithStringBeginningWithEncodingPrefixForUUID() { String uuidStringMessageId = AMQPMessageIdHelper.AMQP_UUID_PREFIX + UUID.randomUUID(); String expected = AMQPMessageIdHelper.AMQP_STRING_PREFIX + uuidStringMessageId; String baseMessageIdString = mes...
@Override public boolean isSharable() { return decoder.isSharable(); }
@Test public void testIsSharable() { testIsSharable(true); }
public static FuryBuilder builder() { return new FuryBuilder(); }
@Test(dataProvider = "enableCodegen") public void testSerializeJDKObject(boolean enableCodegen) { Fury fury = Fury.builder() .withLanguage(Language.JAVA) .withJdkClassSerializableCheck(false) .requireClassRegistration(false) .withCodegen(enableCodegen) ...
@Override public void write(final PostgreSQLPacketPayload payload, final Object value) { throw new UnsupportedSQLOperationException("PostgreSQLInt8ArrayBinaryProtocolValue.write()"); }
@Test void assertWrite() { assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().write(new PostgreSQLPacketPayload(null, StandardCharsets.UTF_8), "val")); }
@Override public <T> Future<T> background(final BackgroundAction<T> action) { if(registry.contains(action)) { log.warn(String.format("Skip duplicate background action %s found in registry", action)); return ConcurrentUtils.constantFuture(null); } return DefaultBackgro...
@Test public void testBackground() throws Exception { final AbstractController controller = new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { runnable.run(); } }; final AbstractBackgrou...
@Override public ByteBuf copy() { return copy(readerIndex, readableBytes()); }
@Test public void copyBoundaryCheck4() { assertThrows(IndexOutOfBoundsException.class, new Executable() { @Override public void execute() { buffer.copy(buffer.capacity(), 1); } }); }
@Override public void flush() throws IOException { mLocalOutputStream.flush(); }
@Test @PrepareForTest(OBSOutputStream.class) public void testFlush() throws Exception { PowerMockito.whenNew(BufferedOutputStream.class) .withArguments(any(DigestOutputStream.class)).thenReturn(mLocalOutputStream); OBSOutputStream stream = new OBSOutputStream("testBucketName", "testKey", mObsClient,...
static void warmField(Class<?> context, Field field, ExecutorService compilationService) { Class<?> fieldRawType = field.getType(); if (fieldRawType.isPrimitive() || fieldRawType == String.class || fieldRawType == Object.class) { return; } if (TypeUtils.isBoxed(fieldRawType)) { ...
@Test public void testWarmField() throws Exception { Assert.assertEquals(int.class.getName(), "int"); Assert.assertEquals(Integer.class.getName(), "java.lang.Integer"); Descriptor.warmField( BeanA.class, BeanA.class.getDeclaredField("beanB"), CodeGenerator.getCompilationService()); Descriptor....
public static DeltaLakeTable convertDeltaToSRTable(String catalog, String dbName, String tblName, String path, Engine deltaEngine, long createTime) { SnapshotImpl snapshot; try (Timer ignored = Tracers.watchScope(EXTERNAL, "DeltaLake.getSnapshot"))...
@Test public void testConvertDeltaToSRTableWithException2() { expectedEx.expect(SemanticException.class); expectedEx.expectMessage("Failed to get latest snapshot for catalog.db.tbl"); Table table = new Table() { public Table forPath(Engine engine, String path) { r...
public static <T> T toObj(byte[] json, Class<T> cls) { try { return mapper.readValue(json, cls); } catch (Exception e) { throw new NacosDeserializationException(cls, e); } }
@Test void testToObject8() { assertThrows(Exception.class, () -> { JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), Object.class); }); }
public static void convertAttachment( DefaultHttp2Headers headers, Map<String, Object> attachments, boolean needConvertHeaderKey) { if (attachments == null) { return; } Map<String, String> needConvertKey = new HashMap<>(); for (Map.Entry<String, Object> entry : at...
@Test void testConvertAttachment() throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(10); DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.add("key", "value"); Map<String, Object> attachments = new HashMap<>(); atta...
@Override public List<String> listPartitionNames(String databaseName, String tableName, TableVersionRange version) { return deltaOps.getPartitionKeys(databaseName, tableName); }
@Test public void testListPartitionNames(@Mocked SnapshotImpl snapshot, @Mocked ScanBuilder scanBuilder, @Mocked Scan scan) { new MockUp<DeltaUtils>() { @Mock public DeltaLakeTable convertDeltaToSRTable(String catalog, String dbName, String tblN...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldThrowWhenInsertingValuesOnSourceStream() { // Given: givenDataSourceWithSchema("source_stream_1", SCHEMA, SerdeFeatures.of(), SerdeFeatures.of(), false, true); final KsqlConfig ksqlConfig = new KsqlConfig(ImmutableMap.of()); final ConfiguredStatement<InsertValues> state...
public static DatabaseType get(final String url) { Collection<DatabaseType> databaseTypes = ShardingSphereServiceLoader.getServiceInstances(DatabaseType.class).stream().filter(each -> matchURLs(url, each)).collect(Collectors.toList()); ShardingSpherePreconditions.checkNotEmpty(databaseTypes, () -> new U...
@Test void assertGetDatabaseTypeWithUnrecognizedURL() { assertThrows(UnsupportedStorageTypeException.class, () -> DatabaseTypeFactory.get("jdbc:not-existed:test")); }
public CompletableFuture<Map<TopicIdPartition, ShareAcknowledgeResponseData.PartitionData>> acknowledge( String memberId, String groupId, Map<TopicIdPartition, List<ShareAcknowledgementBatch>> acknowledgeTopics ) { log.trace("Acknowledge request for topicIdPartitions: {} with groupId...
@Test public void testAcknowledgeIncorrectMemberId() { String groupId = "grp"; String memberId = Uuid.randomUuid().toString(); TopicIdPartition tp = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0)); SharePartition sp = mock(SharePartition.class); when(sp...
public String lockName() { return kind + "::" + namespace + "::" + name; }
@Test public void testLockName() { SimplifiedReconciliation r1 = new SimplifiedReconciliation("kind", "my-namespace", "my-name", "watch"); String lockName = r1.lockName(); assertThat(lockName, is("kind::my-namespace::my-name")); }
public static <T> T readStaticFieldOrNull(String className, String fieldName) { try { Class<?> clazz = Class.forName(className); return readStaticField(clazz, fieldName); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | SecurityException e) { ...
@Test public void readStaticFieldOrNull_readFromPrivateField() { String field = ReflectionUtils.readStaticFieldOrNull(MyClass.class.getName(), "staticPrivateField"); assertEquals("staticPrivateFieldContent", field); }
public String getCustomError(HttpRequestWrapper req, HttpResponseWrapper res) { for (MatcherAndError m : matchersAndLogs) { if (m.getMatcher().matchResponse(req, res)) { return m.getCustomError().customError(req, res); } } return null; }
@Test public void testNotMatchesCodeAndUrlContains() throws IOException { HttpRequestWrapper request = createHttpRequest(BQ_TABLES_LIST_URL); HttpResponseWrapper response = createHttpResponse(404); CustomHttpErrors.Builder builder = new CustomHttpErrors.Builder(); builder.addErrorForCodeAndUrlContain...
@Override @Transactional(rollbackFor = Exception.class) @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_CREATE_SUB_TYPE, bizNo = "{{#role.id}}", success = SYSTEM_ROLE_CREATE_SUCCESS) public Long createRole(RoleSaveReqVO createReqVO, Integer type) { // 1. 校验角色 validateRo...
@Test public void testCreateRole() { // 准备参数 RoleSaveReqVO reqVO = randomPojo(RoleSaveReqVO.class) .setId(null); // 防止 id 被赋值 // 调用 Long roleId = roleService.createRole(reqVO, null); // 断言 RoleDO roleDO = roleMapper.selectById(roleId); assertP...
public static String capitalize(String string) { return string == null ? null : string.substring( 0, 1 ).toUpperCase( Locale.ROOT ) + string.substring( 1 ); }
@Test @DefaultLocale("tr") public void capitalizeTurkish() { String international = Strings.capitalize( "international" ); assertThat( international ).isEqualTo( "International" ); }
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if (this instanceof SimpleBuildStep) { // delegate to the overloaded version defined in SimpleBuildStep final SimpleBuildStep step = (Simp...
@Issue("JENKINS-18734") @Test @SuppressWarnings("deprecation") /* testing deprecated variant */ public void testPerformExpectAbstractMethodError() { FreeStyleBuild mock = Mockito.mock(FreeStyleBuild.class, Mockito.CALLS_REAL_METHODS); BuildStepCompatibilityLayer bscl = new BuildStepCompatib...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetchWithNoTopicId() { // Should work and default to using old request type. buildFetcher(); TopicIdPartition noId = new TopicIdPartition(Uuid.ZERO_UUID, new TopicPartition("noId", 0)); assignFromUser(noId.topicPartition()); subscriptions.seek(noId.topi...
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldErrorWhenConflictingUnreliableSubscriptionAdded() { driverProxy.addSubscription(CHANNEL_4000, STREAM_ID_1); driverConductor.doWork(); final long id2 = driverProxy.addSubscription(CHANNEL_4000 + "|reliable=false", STREAM_ID_1); driverConductor.doWork(); ...
public CardinalityEstimatorConfig setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount); return this; }
@Test(expected = IllegalArgumentException.class) public void testSetAsyncBackupCount_withNegativeValue() { config.setAsyncBackupCount(-1); }
public List<Integer> findLongestMatch(String key) { TST current; List<Integer> ordinals; do { current = prefixIndexVolatile; long nodeIndex = current.findLongestMatch(key); ordinals = current.getOrdinals(nodeIndex); } while (current != this.prefixIndex...
@Test public void testLongestPrefixMatch() throws Exception { // "The Matrix" // "Blood Diamond" // "Rush" // "Rocky" // "The Matrix Reloaded" // "The Matrix Resurrections" for (Movie movie : getSimpleList()) { objectMapper.add(movie); } ...
static QueryId buildId( final Statement statement, final EngineContext engineContext, final QueryIdGenerator idGenerator, final OutputNode outputNode, final boolean createOrReplaceEnabled, final Optional<String> withQueryId) { if (withQueryId.isPresent()) { final String que...
@Test public void shouldReuseExistingQueryId() { // Given: when(plan.getSinkName()).thenReturn(Optional.of(SINK)); when(plan.createInto()).thenReturn(true); when(queryRegistry.getQueriesWithSink(SINK)) .thenReturn(ImmutableSet.of(new QueryId("CTAS_FOO_10"))); // When: final QueryId qu...
@Override public boolean saveAndCheckUserLoginStatus(Long userId) throws Exception { Long add = redisTemplate.opsForSet().add(LOGIN_STATUS_PREFIX, userId.toString()); if (add == 0){ return false ; }else { return true ; } }
@Test public void checkUserLoginStatus() throws Exception { boolean status = userInfoCacheService.saveAndCheckUserLoginStatus(2000L); log.info("status={}", status); }
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldHandleOutOfOrderSchema() { // Given: final ConfiguredStatement<InsertValues> statement = givenInsertValues( ImmutableList.of(COL1, COL0, K0), ImmutableList.of( new LongLiteral(2L), new StringLiteral("str"), new StringLiteral("key") ...
public boolean isAdmin(Admin admin) { return !isSecurityEnabled() || noAdminsConfigured() || adminsConfig.isAdmin(admin, rolesConfig.memberRoles(admin)); }
@Test public void shouldKnowIfUserIsAdmin() throws Exception { SecurityConfig security = security(null, admins(user("chris"))); assertThat(security.isAdmin(new AdminUser(new CaseInsensitiveString("chris"))), is(true)); assertThat(security.isAdmin(new AdminUser(new CaseInsensitiveString("evil...
@Override public void loadAll(boolean replaceExistingValues) { map.loadAll(replaceExistingValues); }
@Test public void testLoadAll() { mapWithLoader.put(23, "value-23"); mapStore.setKeys(singleton(23)); adapterWithLoader.loadAll(true); adapterWithLoader.waitUntilLoaded(); assertEquals("newValue-23", mapWithLoader.get(23)); }
@Override public void check(Model model) { if (model == null) return; List<Model> secondPhaseModels = new ArrayList<>(); deepFindAllModelsOfType(AppenderModel.class, secondPhaseModels, model); deepFindAllModelsOfType(LoggerModel.class, secondPhaseModels, model); ...
@Test public void singleAppender() { ClassicTopModel topModel = new ClassicTopModel(); AppenderModel appenderModel0 = new AppenderModel(); appenderModel0.setLineNumber(1); topModel.addSubModel(appenderModel0); inwspeChecker.check(topModel); statusChecker.assertIsWarni...
@Description("encode value as a big endian varbinary according to IEEE 754 single-precision floating-point format") @ScalarFunction("to_ieee754_32") @SqlType(StandardTypes.VARBINARY) public static Slice toIEEE754Binary32(@SqlType(StandardTypes.REAL) long value) { Slice slice = Slices.allocate(Fl...
@Test public void testToIEEE754Binary32() { assertFunction("to_ieee754_32(CAST(0.0 AS REAL))", VARBINARY, sqlVarbinaryHex("00000000")); assertFunction("to_ieee754_32(CAST(1.0 AS REAL))", VARBINARY, sqlVarbinaryHex("3F800000")); assertFunction("to_ieee754_32(CAST(3.14 AS REAL))", VARBINAR...
@Nonnull @Override public CreatedAggregations<AggregationBuilder> doCreateAggregation(Direction direction, String name, Pivot pivot, Time timeSpec, OSGeneratedQueryContext queryContext, Query query) { AggregationBuilder root = null; AggregationBuilder leaf = null; final Interval interval...
@Test public void autoDateHistogramAggregationBuilderUsedForAutoIntervalAndAllMessages() { final AutoInterval interval = mock(AutoInterval.class); final RelativeRange allMessagesRange = RelativeRange.allTime(); doReturn(allMessagesRange).when(query).timerange(); when(time.interval())...
@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 shouldNotAllowNullMapperOnLeftJoinWithGlobalTable() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin(testGlobalTable, null, MockValueJoiner.TOSTRING_JOINER)); assertThat(exception.getMessage(), equa...
public static CharSequence parseElement(XmlPullParser parser) throws XmlPullParserException, IOException { return parseElement(parser, false); }
@Test public void parseElementMultipleNamespace() throws ParserConfigurationException, FactoryConfigurationError, XmlPullParserException, IOException, TransformerException, SAXException { // @formatter:off final String stanza = XMLBuilder.c...
@GET @TreeResponse public ExportedPipelineFunction[] doPipelineStepMetadata() { List<ExportedPipelineFunction> pd = new ArrayList<>(); // POST to this with parameter names // e.g. json:{"time": "1", "unit": "NANOSECONDS", "stapler-class": "org.jenkinsci.plugins.workflow.steps.TimeoutStep...
@Test public void verifyFunctionNames() throws Exception { PipelineMetadataService svc = new PipelineMetadataService(); List<ExportedDescribableModel> steps = new ArrayList<>(Arrays.asList(svc.doPipelineStepMetadata())); assertFalse(steps.isEmpty()); // Verify we have a Symbol-pro...
public static boolean isTableActiveVersionNode(final String path) { return Pattern.compile(getMetaDataNode() + TABLES_PATTERN + ACTIVE_VERSION_SUFFIX, Pattern.CASE_INSENSITIVE).matcher(path).find(); }
@Test void assertIsTableActiveVersionNode() { assertTrue(TableMetaDataNode.isTableActiveVersionNode("/metadata/foo_db/schemas/foo_schema/tables/foo_table/active_version")); }
static String removeWhiteSpaceFromJson(String json) { //reparse the JSON to ensure that all whitespace formatting is uniform String flattend = FLAT_GSON.toJson(JsonParser.parseString(json)); return flattend; }
@Test public void removeWhiteSpaceFromJson_noOp() { String input = "{\"a\":123,\"b\":456}"; String output = "{\"a\":123,\"b\":456}"; assertThat( removeWhiteSpaceFromJson(input), is(output) ); }
@Override public String convertToDatabaseColumn(MonetaryAmount amount) { return amount == null ? null : String.format("%s %s", amount.getCurrency().toString(), amount.getNumber().toString()); }
@Test void doesNotFormatLargeValues() { assertThat(converter.convertToDatabaseColumn(Money.of(123456, "EUR"))).isEqualTo("EUR 123456"); }
@Override public Data getValue() { return value; }
@Test public void testGetValue() { assertEquals(VALUE, record.getValue()); assertEquals(VALUE, recordSameAttributes.getValue()); assertNotEquals(VALUE, recordOtherKeyAndValue.getValue()); }
public void schedule(String eventDefinitionId) { final EventDefinitionDto eventDefinition = getEventDefinitionOrThrowIAE(eventDefinitionId); createJobDefinitionAndTriggerIfScheduledType(eventDefinition); }
@Test @MongoDBFixtures("event-processors-without-schedule.json") public void schedule() { assertThat(eventDefinitionService.get("54e3deadbeefdeadbeef0000")).isPresent(); assertThat(jobDefinitionService.streamAll().count()).isEqualTo(0); assertThat(jobTriggerService.all()).isEmpty(); ...
public String forDisplay(List<ConfigurationProperty> propertiesToDisplay) { ArrayList<String> list = new ArrayList<>(); for (ConfigurationProperty property : propertiesToDisplay) { if (!property.isSecure()) { list.add(format("%s=%s", property.getConfigurationKey().getName().t...
@Test void shouldGetConfigForDisplay() { ConfigurationProperty property1 = new ConfigurationProperty(new ConfigurationKey("key1"), new ConfigurationValue("value1"), null, null); ConfigurationProperty property2 = new ConfigurationProperty(new ConfigurationKey("key2"), new ConfigurationValue("value2")...
@VisibleForTesting State getState() { return state; }
@Test void testInitialState() throws Exception { final AdaptiveScheduler scheduler = new AdaptiveSchedulerBuilder( createJobGraph(), mainThreadExecutor, EXECUTOR_RESOURCE.getExecutor()) ...
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testBooleanType() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); SearchArgument arg = builder.startAnd().equals("boolean", PredicateLeaf.Type.BOOLEAN, true).end().build(); UnboundPredicate expected = Expressions.equal("boolean", true); UnboundPredicat...
public Stream<Hit> stream() { if (nPostingLists == 0) { return Stream.empty(); } return StreamSupport.stream(new PredicateSpliterator(), false); }
@Test void requireThatIntervalSortingWorksAsUnsigned() { PredicateSearch search = createPredicateSearch( new byte[]{1}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010001)), postingList(SubqueryBitmap.ALL_SUBQUERIES, ...
@Override protected TableRecords getUndoRows() { return sqlUndoLog.getAfterImage(); }
@Test public void getUndoRows() { Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getAfterImage()); }
@Override public GroupAssignment assign( GroupSpec groupSpec, SubscribedTopicDescriber subscribedTopicDescriber ) throws PartitionAssignorException { if (groupSpec.memberIds().isEmpty()) return new GroupAssignment(Collections.emptyMap()); if (groupSpec.subscriptionTy...
@Test public void testAssignWithTwoMembersAndTwoTopicsHomogeneous() { Map<Uuid, TopicMetadata> topicMetadata = new HashMap<>(); topicMetadata.put(TOPIC_1_UUID, new TopicMetadata( TOPIC_1_UUID, TOPIC_1_NAME, 3, Collections.emptyMap() )); ...
public void verifyPropertyParam(String param, String name) throws BadParam { verifyParam(param, name); Matcher m = PROPERTY_ID.matcher(param); if (!m.matches()) { throw new BadParam("Invalid property name " + name); } }
@Test public void testVerifyPropertyParam() { // HIVE-15410: Though there are not restrictions to Hive table property key and it could be any // combination of the letters, digits and even punctuations, we support conventional property // name in WebHCat (e.g. prepery name starting with a letter or digit ...
public ResT receive(long timeoutMs) throws IOException { if (mCompleted) { return null; } if (mCanceled) { throw new CancelledException(formatErrorMessage("Stream is already canceled.")); } long startMs = System.currentTimeMillis(); while (true) { long waitedForMs = System.cur...
@Test public void receiveError() throws Exception { mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); Exception e = assertThrows(UnauthenticatedException.class, () -> mStream.receive(TIMEOUT)); assertTrue(e.getMessage().contains(TEST_MESSAGE)); }
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) { final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps()); map.put( MetricCollectors.RESOURCE_LABEL_PREFIX + StreamsConfig.APPLICATION_ID_CONFIG, applicationId ); // Streams cli...
@Test public void shouldSetLogAndContinueExceptionHandlerByDefault() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.emptyMap()); final Object result = ksqlConfig.getKsqlStreamConfigProps().get(StreamsConfig.DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG); assertThat(result, equalTo(Log...
boolean hasProjectionMaskApi(JClass definedClass, ClassTemplateSpec templateSpec) { return _hasProjectionMaskCache.computeIfAbsent(definedClass, (jClass) -> { try { final Class<?> clazz = _classLoader.loadClass(jClass.fullName()); return Arrays.stream(clazz.getClasses()).anyMatch( ...
@Test public void testHasProjectionMaskApiGeneratedFromSource() throws Exception { ProjectionMaskApiChecker projectionMaskApiChecker = new ProjectionMaskApiChecker( _templateSpecGenerator, _sourceFiles, _mockClassLoader); Mockito.when(_nestedTypeSource.getAbsolutePath()).thenReturn(pegasusDir + FS ...
@Override public MetricsCollector create(final MetricConfiguration metricConfig) { switch (metricConfig.getType()) { case COUNTER: return new PrometheusMetricsCounterCollector(metricConfig); case GAUGE: return new PrometheusMetricsGaugeCollector(metric...
@Test void assertCreateHistogramCollector() { MetricConfiguration config = new MetricConfiguration("test_histogram", MetricCollectorType.HISTOGRAM, null, Collections.emptyList(), Collections.emptyMap()); assertThat(new PrometheusMetricsCollectorFactory().create(config), instanceOf(PrometheusMetricsH...
@Override public ObjectNode encode(MappingInstruction instruction, CodecContext context) { checkNotNull(instruction, "Mapping instruction cannot be null"); return new EncodeMappingInstructionCodecHelper(instruction, context).encode(); }
@Test public void unicastWeightInstrutionTest() { final UnicastMappingInstruction.WeightMappingInstruction instruction = (UnicastMappingInstruction.WeightMappingInstruction) MappingInstructions.unicastWeight(UNICAST_WEIGHT); final ObjectNode instructionJson = ...
@PostMapping("/server/leave") @Secured(resource = Commons.NACOS_CORE_CONTEXT + "/cluster", action = ActionTypes.WRITE, signType = SignType.CONSOLE) public RestResult<String> leave(@RequestBody Collection<String> params, @RequestParam(defaultValue = "true") Boolean notifyOtherMembers) throws Exceptio...
@Test void testLeave() throws Exception { RestResult<String> result = nacosClusterController.leave(Collections.singletonList("1.1.1.1"), true); assertFalse(result.ok()); assertEquals(405, result.getCode()); }
@Override public Mono<UserNotificationPreference> getByUser(String username) { var configName = buildUserPreferenceConfigMapName(username); return client.fetch(ConfigMap.class, configName) .map(config -> { if (config.getData() == null) { return new Use...
@Test void getByUserWhenNotFound() { when(client.fetch(ConfigMap.class, "user-preferences-guqing")) .thenReturn(Mono.empty()); userNotificationPreferenceService.getByUser("guqing") .as(StepVerifier::create) .consumeNextWith(preference -> assertThat...
public int calculateBufferSize(long totalBufferSizeInBytes, int totalBuffers) { checkArgument(totalBufferSizeInBytes >= 0, "Size of buffer should be non negative"); checkArgument(totalBuffers > 0, "Number of buffers should be positive"); // Since the result value is always limited by max buffer...
@Test void testSizeGreaterThanMaxSize() { BufferSizeEMA calculator = new BufferSizeEMA(200, 10, 3); // Decrease value to less than max. assertThat(calculator.calculateBufferSize(0, 1)).isEqualTo(100); // Impossible to exceed maximum. assertThat(calculator.calculateBufferSiz...
public void setType( int type ) { this.type = type; }
@Test public void setType() { DragAndDropContainer dnd = new DragAndDropContainer( DragAndDropContainer.TYPE_BASE_JOB_ENTRY, "Step Name" ); dnd.setType( DragAndDropContainer.TYPE_BASE_STEP_TYPE ); assertEquals( DragAndDropContainer.TYPE_BASE_STEP_TYPE, dnd.getType() ); }
public Number evaluate(final List<KiePMMLDefineFunction> defineFunctions, final List<KiePMMLDerivedField> derivedFields, final List<KiePMMLOutputField> outputFields, final Map<String, Object> inputData) { final List<KiePMMLNameValu...
@Test void evaluateFromFieldRef() { // <ComplexPartialScore> // <FieldRef field="PARAM_1"/> // </ComplexPartialScore> final KiePMMLFieldRef kiePMMLFieldRef = new KiePMMLFieldRef(PARAM_1, Collections.emptyList(), null); final KiePMMLComplexPartialScore complexPartialScore ...
public boolean isSuppressed(Device device) { if (suppressedDeviceType.contains(device.type())) { return true; } final Annotations annotations = device.annotations(); if (containsSuppressionAnnotation(annotations)) { return true; } return false; ...
@Test public void testSuppressedDeviceAnnotation() { Annotations annotation = DefaultAnnotations.builder() .set("no-lldp", "random") .build(); Device device = new DefaultDevice(PID, NON_SUPPRESSED_DID, ...
public static boolean isNullOrEmpty(final Collection<?> list) { return list == null || list.size() == 0; }
@Test public void testIsNullOrEmptyCollection() { assertTrue(Utils.isNullOrEmpty((Collection<Void>) null)); assertTrue(Utils.isNullOrEmpty(Collections.EMPTY_SET)); assertFalse(Utils.isNullOrEmpty(Collections.singletonList(null))); assertFalse(Utils.isNullOrEmpty(Arrays.asList(new Object()))); Coll...
@Description("returns index of first occurrence of a substring (or 0 if not found)") @ScalarFunction("strpos") @LiteralParameters({"x", "y"}) @SqlType(StandardTypes.BIGINT) public static long stringPosition(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice substring) { return...
@Test public void testStringPosition() { testStrPosAndPosition("high", "ig", 2L); testStrPosAndPosition("high", "igx", 0L); testStrPosAndPosition("Quadratically", "a", 3L); testStrPosAndPosition("foobar", "foobar", 1L); testStrPosAndPosition("foobar", "obar", 3L); ...
@Override public void add(final TimerTask timerTask) { if (Objects.isNull(timerTask)) { throw new NullPointerException("timer task null"); } this.readLock.lock(); try { start(); long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); ...
@Test public void testListForeach() { TimerTask timerTask = new TimerTask(100000) { @Override public void run(final TaskEntity taskEntity) { } }; timerTaskList.add(new TimerTaskList.TimerTaskEntry(timer, timerTask, -1L)); assertEquals(...
public static String formatChineseDate(Date date, boolean isUppercase, boolean withTime) { if (null == date) { return null; } if (false == isUppercase) { return (withTime ? DatePattern.CHINESE_DATE_TIME_FORMAT : DatePattern.CHINESE_DATE_FORMAT).format(date); } return CalendarUtil.formatChineseDate(Cal...
@Test public void formatChineseDateTest() { String formatChineseDate = DateUtil.formatChineseDate(DateUtil.parse("2018-02-24"), true, false); assertEquals("二〇一八年二月二十四日", formatChineseDate); formatChineseDate = DateUtil.formatChineseDate(DateUtil.parse("2018-02-14"), true, false); assertEquals("二〇一八年二月十四日", fo...
int getMaxLevel(int maxLevel) { return (maxLevel <= 0 || maxLevel > this.maxLevelAllowed) ? this.maxLevelAllowed : maxLevel; }
@Test public void givenMaxLevelPositive_whenGetMaxLevel_thenValueTheSame() { assertThat(repo.getMaxLevel(1), equalTo(1)); assertThat(repo.getMaxLevel(2), equalTo(2)); assertThat(repo.getMaxLevel(repo.getMaxLevelAllowed()), equalTo(repo.getMaxLevelAllowed())); assertThat(repo.getMaxLe...
@Override public BitMask resetAll(BitMask mask) { if (mask instanceof LongBitMask) { this.mask &= (-1L - ((LongBitMask) mask).asLong()); } else if (mask instanceof AllSetBitMask) { this.mask &= 0; } else if (mask instanceof AllSetButLastBitMask) { this.mas...
@Test public void testResetAll() { assertThat(new LongBitMask().resetAll(new LongBitMask()).toString()).isEqualTo("0"); assertThat(new LongBitMask().resetAll(AllSetBitMask.get()).toString()).isEqualTo("0"); assertThat(new LongBitMask().resetAll(AllSetButLastBitMask.get()).toString()).isEqualTo("0");...
public static Collection<String> getTrimmedStringCollection(String str, String delim) { List<String> values = new ArrayList<String>(); if (str == null) return values; StringTokenizer tokenizer = new StringTokenizer(str, delim); while (tokenizer.hasMoreTokens()) { String next = tokenize...
@Test public void testGetUniqueNonEmptyTrimmedStrings (){ final String TO_SPLIT = ",foo, bar,baz,,blah,blah,bar,"; Collection<String> col = StringUtils.getTrimmedStringCollection(TO_SPLIT); assertEquals(4, col.size()); assertTrue(col.containsAll(Arrays.asList(new String[]{"foo","bar","baz","blah"})))...
@Implementation protected HttpResponse execute( HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { if (FakeHttp.getFakeHttpLayer().isInterceptingHttpRequests()) { return FakeHttp.getFakeHttpLayer() .emulateRequest(httpHost, httpRequ...
@Test public void shouldReturnRequestsByRule() throws Exception { FakeHttp.addHttpResponseRule( HttpGet.METHOD_NAME, "http://some.uri", new TestHttpResponse(200, "a cheery response body")); HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null); ...
public static List<TypeRef<?>> getTypeArguments(TypeRef typeRef) { if (typeRef.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) typeRef.getType(); return Arrays.stream(parameterizedType.getActualTypeArguments()) .map(TypeRef::of) .co...
@Test public void getTypeArguments() { TypeRef<Tuple2<String, Map<String, Integer>>> typeRef = new TypeRef<Tuple2<String, Map<String, Integer>>>() {}; assertEquals(TypeUtils.getTypeArguments(typeRef).size(), 2); }
public static BigDecimal convertToDecimal(Schema schema, Object value, int scale) { if (value == null) { throw new DataException("Unable to convert a null value to a schema that requires a value"); } return convertToDecimal(Decimal.schema(scale), value); }
@Test public void shouldFailToConvertNullToDecimal() { assertThrows(DataException.class, () -> Values.convertToDecimal(null, null, 1)); }
int getMinimumTokens(String languageKey) { return settings.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100); }
@Test public void defaultMinimumTokens() { when(configuration.getInt(anyString())).thenReturn(Optional.empty()); assertThat(cpdSettings.getMinimumTokens("java")).isEqualTo(100); }
public static boolean createFile(final Path filePath) { try { final Path parent = filePath.getParent(); if (parent == null) { return false; } if (Files.notExists(parent)) { Files.createDirectories(parent); } ...
@Test void testCreateFileLinkDir() throws IOException { Path link = Paths.get(linkFolder.toFile().getPath(), "link"); Files.createSymbolicLink(link, realFolder); Path linkDirHistoryFile = Paths.get(link.toAbsolutePath().toString(), "history.file"); Path realLinkDirHistoryFile = Paths...
public static RawTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); TransactionType transactionType = getTransactionType(transaction); switch (transactionType) { case EIP1559: return decodeEIP155...
@Test public void testDecoding1559AccessList() { final RawTransaction rawTransaction = createEip1559RawTransactionAccessList(); final Transaction1559 transaction1559 = (Transaction1559) rawTransaction.getTransaction(); final byte[] encodedMessage = TransactionEncoder.encode(rawTransaction);...
public static Connection OpenConnection( String serveur, int port, String username, String password, boolean useKey, String keyFilename, String passPhrase, int timeOut, VariableSpace space, String proxyhost, int proxyport, String proxyusername, String proxypassword ) throws KettleException { Connection ...
@Test public void testOpenConnectionUseKey_2() throws Exception { when( fileObject.exists() ).thenReturn( true ); when( fileObject.getContent() ).thenReturn( fileContent ); when( fileContent.getSize() ).thenReturn( 1000L ); when( fileContent.getInputStream() ).thenReturn( new ByteArrayInputStream( new...
@Override public List<byte[]> clusterGetKeysInSlot(int slot, Integer count) { RFuture<List<byte[]>> f = executorService.readAsync((String)null, ByteArrayCodec.INSTANCE, CLUSTER_GETKEYSINSLOT, slot, count); return syncFuture(f); }
@Test public void testClusterGetKeysInSlot() { List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10); assertThat(keys).isEmpty(); }
@Override public void invoke() throws Exception { // -------------------------------------------------------------------- // Initialize // -------------------------------------------------------------------- LOG.debug(getLogString("Start registering input and output")); // i...
@Test void testFailingDataSinkTask() { int keyCnt = 100; int valCnt = 20; super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE); super.addInput(new UniformRecordGenerator(keyCnt, valCnt, false), 0); DataSinkTask<Record> testTask = new DataSinkTask<>(this.mockEnv)...
public T evolve(int generation) { return evolve(generation, Double.POSITIVE_INFINITY); }
@Test public void test() { System.out.println("Genetic Algorithm"); BitString[] seeds = new BitString[100]; // The mutation parameters are set higher than usual to prevent premature convergence. for (int i = 0; i < seeds.length; i++) { seeds[i] = new BitString(1...
@Override public GenericAvroRecord read(byte[] bytes, int offset, int length) { try { if (offset == 0 && this.offset > 0) { offset = this.offset; } Decoder decoder = DecoderFactory.get().binaryDecoder(bytes, offset, length - offset, null); org....
@Test public void testGenericAvroReaderByReaderSchema() { byte[] fooV2Bytes = fooV2Schema.encode(fooV2); GenericAvroReader genericAvroSchemaByReaderSchema = new GenericAvroReader(fooV2Schema.getAvroSchema(), fooSchemaNotNull.getAvroSchema(), new byte[10]); GenericRecord genericRecordByReade...
public URL getInterNodeListener( final Function<URL, Integer> portResolver ) { return getInterNodeListener(portResolver, LOGGER); }
@Test public void shouldResolveInterNodeListenerToFirstListenerSetToIpv6Loopback() { // Given: final URL expected = url("https://[::1]:12345"); final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder() .put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") ...
public static File unzip(String zipFilePath) throws UtilException { return unzip(zipFilePath, DEFAULT_CHARSET); }
@Test @Disabled public void issue3018Test() { ZipUtil.unzip( FileUtil.getInputStream("d:/test/default.zip") , FileUtil.file("d:/test/"), CharsetUtil.CHARSET_UTF_8); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testOrderedListMergePendingAdds() { SettableFuture<Map<Range<Instant>, RangeSet<Long>>> orderedListFuture = SettableFuture.create(); orderedListFuture.set(null); SettableFuture<Map<Range<Instant>, RangeSet<Instant>>> deletionsFuture = SettableFuture.create(); deletionsFuture....
public static Schema getOutputSchema( Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) { return getOutputSchemaTrackingNullable(inputSchema, fieldAccessDescriptor, false); }
@Test public void testNullableSchemaMap() { FieldAccessDescriptor fieldAccessDescriptor1 = FieldAccessDescriptor.withFieldNames("nestedMap.field1").resolve(NESTED_NULLABLE_SCHEMA); Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1); Schema expectedSchema...
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testNonSupportedPrimitiveType() { assertThat( getLiteral( void.class.getCanonicalName(), "0xFFFF_FFFF_FFFF" ) ).isNull(); }
@Override public boolean hasConflict(ConcurrentOperation thisOperation, ConcurrentOperation otherOperation) { // TODO : UUID's can clash even for insert/insert, handle that case. Set<String> partitionBucketIdSetForFirstInstant = thisOperation .getMutatedPartitionAndFileIds() .stream() ...
@Test public void testConcurrentWritesWithInterleavingSuccessfulCommit() throws Exception { createCommit(metaClient.createNewInstantTime()); HoodieActiveTimeline timeline = metaClient.getActiveTimeline(); // consider commits before this are all successful Option<HoodieInstant> lastSuccessfulInstant = ...
public StringSubject factValue(String key) { return doFactValue(key, null); }
@Test public void factValueIntFailNegative() { try { assertThat(fact("foo", "the foo")).factValue("foo", -1); fail(); } catch (IllegalArgumentException expected) { } }
@Nonnull public static List<Future<?>> getAllDone(Collection<Future<?>> futures) { List<Future<?>> doneFutures = new ArrayList<>(); for (Future<?> f : futures) { if (f.isDone()) { doneFutures.add(f); } } return doneFutures; }
@Test public void testGetAllDone_whenSomeFuturesAreCompleted() { Future<?> completedFuture = InternalCompletableFuture.newCompletedFuture(null); Collection<Future<?>> futures = asList(new UncancellableFuture<>(), completedFuture, new UncancellableFuture<>()); assertEquals(1,...
@Override protected int rsv(WebSocketFrame msg) { return msg.rsv() | WebSocketExtension.RSV1; }
@Test public void testFramementedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false)); EmbeddedChannel decoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE)); // initialize byte[] p...
@Override public MapSettings setProperty(String key, String value) { return (MapSettings) super.setProperty(key, value); }
@Test public void ignore_case_of_boolean_values() { Settings settings = new MapSettings(); settings.setProperty("foo", "true"); settings.setProperty("bar", "TRUE"); // labels in UI settings.setProperty("baz", "True"); assertThat(settings.getBoolean("foo")).isTrue(); assertThat(settings.ge...
public static TableSchema protoTableSchemaFromAvroSchema(Schema schema) { Preconditions.checkState(!schema.getFields().isEmpty()); TableSchema.Builder builder = TableSchema.newBuilder(); for (Schema.Field field : schema.getFields()) { builder.addFields(fieldDescriptorFromAvroField(field)); } ...
@Test public void testNestedFromSchema() { DescriptorProto descriptor = TableRowToStorageApiProto.descriptorSchemaFromTableSchema( AvroGenericRecordToStorageApiProto.protoTableSchemaFromAvroSchema(NESTED_SCHEMA), true, false); Map<String, Type> expectedBaseTypes = ...
public HollowHashIndexResult findMatches(Object... query) { if (hashStateVolatile == null) { throw new IllegalStateException(this + " wasn't initialized"); } int hashCode = 0; for(int i=0;i<query.length;i++) { if(query[i] == null) throw new Illega...
@Test public void testIndexingListOfIntTypeField() throws Exception { mapper.add(new TypeListOfTypeString(10, 20, 30, 40, 10, 12)); mapper.add(new TypeListOfTypeString(10, 20, 30)); mapper.add(new TypeListOfTypeString(50, 51, 52)); roundTripSnapshot(); HollowHashIndex index =...
@Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { // will throw UnsupportedOperationException; delegate anyway for testability return underlying().merge(key, value, remappingFunction); }
@Test public void testDelegationOfUnsupportedFunctionMerge() { final BiFunction<Object, Object, Object> mockBiFunction = mock(BiFunction.class); new PCollectionsHashMapWrapperDelegationChecker<>() .defineMockConfigurationForUnsupportedFunction(mock -> mock.merge(eq(this), eq(this), eq(mo...
public static void sqlExecute(final Object[] newRow, final PreparedStatement statement) throws SQLException { if (ObjectUtils.isEmpty(newRow[0])) { statement.setObject(1, UUIDUtils.getInstance().generateShortUuid()); for (int i = 1; i < newRow.length - 2; i++) { statement...
@Test public void sqlExecute() { final Object[] newRow = new Object[4]; newRow[0] = null; newRow[1] = new Object(); newRow[2] = new Object(); newRow[3] = new Object(); Assertions.assertDoesNotThrow(() -> BaseTrigger.sqlExecute(newRow, mock(PreparedStatement.class))); ...
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(userF...
@Test @Parameters({ "true, __key", "false, this" }) public void when_duplicateExternalName_then_throws(boolean key, String prefix) { InternalSerializationService ss = new DefaultSerializationServiceBuilder().build(); ClassDefinition classDefinition = n...
public static boolean matchesScope(String actualScope, Set<String> scopes) { if (scopes.isEmpty() || scopes.contains(actualScope)) { return true; } // If there is no perfect match, a stage name-level match is tried. // This is done by a substring search over the levels of the scope. // e.g. a...
@Test public void testMatchesScope() { assertTrue(matchesScopeWithSingleFilter("Top1/Outer1/Inner1/Bottom1", "Top1")); assertTrue( matchesScopeWithSingleFilter("Top1/Outer1/Inner1/Bottom1", "Top1/Outer1/Inner1/Bottom1")); assertTrue(matchesScopeWithSingleFilter("Top1/Outer1/Inner1/Bottom1", "Top1/...
@Override public OverlayData createOverlayData(ComponentName remoteApp) { if (!OS_SUPPORT_FOR_ACCENT) { return EMPTY; } try { final ActivityInfo activityInfo = mLocalContext .getPackageManager() .getActivityInfo(remoteApp, PackageManager.GET_META_DATA); ...
@Test @Config(sdk = Build.VERSION_CODES.KITKAT) public void testAlwaysInvalidWhenPriorToLollipop() { setupReturnedColors(R.style.HappyPathRawColors); Assert.assertFalse(mUnderTest.createOverlayData(mComponentName).isValid()); }
public int terminateQueuedInstances( String workflowId, int limit, WorkflowInstance.Status status, String reason) { TimelineEvent timelineEvent = TimelineLogEvent.warn(TERMINATION_MESSAGE_TEMPLATE, status.name(), reason); String timelineEventStr = toJson(timelineEvent); return withMetricLogErr...
@Test public void testTerminateQueuedInstances() throws Exception { WorkflowInstance wfi1 = loadObject(TEST_WORKFLOW_INSTANCE, WorkflowInstance.class); wfi1.setWorkflowUuid("wfi1-uuid"); wfi1.setWorkflowInstanceId(100L); WorkflowInstance wfi2 = loadObject(TEST_WORKFLOW_INSTANCE, WorkflowInstance.class...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthCompileSolidity() throws Exception { web3j.ethCompileSolidity( "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }") .send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_compileS...
public static String getCheckJobResultPath(final String jobId, final String checkJobId) { return String.join("/", getCheckJobIdsRootPath(jobId), checkJobId); }
@Test void assertGetCheckJobResultPath() { assertThat(PipelineMetaDataNode.getCheckJobResultPath(jobId, "j02fx123"), is(jobCheckRootPath + "/job_ids/j02fx123")); }
public void stop() { if (stopped.compareAndSet(false, true)) { LOG.debug("Stopping the PooledConnectionFactory, number of connections in cache: {}", connectionsPool != null ? connectionsPool.getNumActive() : 0); try { if (connectionsPool != null) { ...
@Test(timeout = 60000) public void testInstanceOf() throws Exception { PooledConnectionFactory pcf = new PooledConnectionFactory(); assertTrue(pcf instanceof QueueConnectionFactory); assertTrue(pcf instanceof TopicConnectionFactory); pcf.stop(); }
@Override public Set<K8sNode> nodes() { return nodeStore.nodes(); }
@Test public void testGetNodesByType() { assertEquals(ERR_SIZE, 2, target.nodes(MINION).size()); assertTrue(ERR_NOT_FOUND, target.nodes(MINION).contains(MINION_2)); assertTrue(ERR_NOT_FOUND, target.nodes(MINION).contains(MINION_3)); }
@Nullable public static String getValueFromStaticMapping(String mapping, String key) { Map<String, String> m = Splitter.on(";") .omitEmptyStrings() .trimResults() .withKeyValueSeparator("=") .split(mapping); return m.get(key); }
@Test public void getValueFromStaticMapping() throws Exception { String mapping = "k=v; a=a; alice=bob; id1=userA; foo=bar"; assertEquals("v", CommonUtils.getValueFromStaticMapping(mapping, "k")); assertEquals("a", CommonUtils.getValueFromStaticMapping(mapping, "a")); assertEquals("bob", Com...