focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public List<UiView> views() { return (isValid || ui2Valid) ? viewList : ImmutableList.of(); }
@Test public void twoViews() { viewList = ImmutableList.of(FOO_VIEW, BAR_VIEW); ext = new UiExtension.Builder(cl, viewList).build(); assertEquals("expected 2 views", 2, ext.views().size()); view = ext.views().get(0); assertEquals("wrong view category", OTHER, view.category(...
public static String formatMethodWithClass(Method input) { return String.format("%s#%s", input.getDeclaringClass().getName(), formatMethod(input)); }
@Test public void testClassMethodFormatter() throws Exception { assertEquals( getClass().getName() + "#testMethodFormatter()", ReflectHelpers.formatMethodWithClass(getClass().getMethod("testMethodFormatter"))); assertEquals( getClass().getName() + "#oneArg(int)", ReflectHelper...
public static String clientIdBase(WorkerConfig config) { String result = Optional.ofNullable(config.groupId()) .orElse("connect"); String userSpecifiedClientId = config.getString(CLIENT_ID_CONFIG); if (userSpecifiedClientId != null && !userSpecifiedClientId.trim().isEmpty()) { ...
@Test public void testClientIdBase() { String groupId = "connect-cluster"; String userSpecifiedClientId = "worker-57"; String expectedClientIdBase = groupId + "-" + userSpecifiedClientId + "-"; assertClientIdBase(groupId, userSpecifiedClientId, expectedClientIdBase); expect...
public static Map<String, Object> map(String metricName, Metric metric) { final Map<String, Object> metricMap = Maps.newHashMap(); metricMap.put("full_name", metricName); metricMap.put("name", metricName.substring(metricName.lastIndexOf(".") + 1)); if (metric instanceof Timer) { ...
@Test public void mapSupportsCounter() { final Counter counter = new Counter(); counter.inc(23L); final Map<String, Object> map = MetricUtils.map("metric", counter); assertThat(map) .containsEntry("type", "counter") .extracting("metric") ...
@Override public void serialize(ModelLocalUriId value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); gen.writeStringField("model", value.model()); gen.writeStringField("basePath", decodedPath(value.basePath())); gen.writeStringField("ful...
@Test void serializeDecodedPath() throws IOException { String path = "/example/some-id/instances/some-instance-id"; LocalUri parsed = LocalUri.parse(path); ModelLocalUriId modelLocalUriId = new ModelLocalUriId(parsed); Writer jsonWriter = new StringWriter(); JsonGenerator jso...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchUdpDstTest() { Criterion criterion = Criteria.matchUdpDst(tpPort); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
static String prettyPrintTaskInfo(TaskState taskState, ZoneOffset zoneOffset) { if (taskState instanceof TaskPending) { return "Will start at " + dateString(taskState.spec().startMs(), zoneOffset); } else if (taskState instanceof TaskRunning) { TaskRunning runState = (TaskRunning...
@Test public void testPrettyPrintTaskInfo() { assertEquals("Will start at 2019-01-08T07:05:59.85Z", CoordinatorClient.prettyPrintTaskInfo( new TaskPending(new NoOpTaskSpec(1546931159850L, 9000)), ZoneOffset.UTC)); assertEquals("Started 2009-07-07T01:45:59....
public <T extends ManifestTemplate> ManifestAndDigest<T> pullManifest( String imageQualifier, Class<T> manifestTemplateClass) throws IOException, RegistryException { ManifestPuller<T> manifestPuller = new ManifestPuller<>( registryEndpointRequestProperties, imageQualifier, manifestTemplate...
@Test public void testPullManifest() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String manifestResponse = "HTTP/1.1 200 OK\nContent-Length: 307\n\n{\n" + " \"schemaVersion\": 2,\n" + " \"mediaTyp...
@Override public KeyValueIterator<Windowed<K>, V> fetch(final K key) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType); for (final ReadOnlySessionStore<K, V> store : stores) { tr...
@Test public void shouldThrowNPEIfKeyIsNull() { assertThrows(NullPointerException.class, () -> underlyingSessionStore.fetch(null)); }
@Override public CompletableFuture<Long> getCounterAsync(String key) { ensureStateEnabled(); return defaultStateStore.getCounterAsync(key); }
@Test public void testGetCounterStateEnabled() throws Exception { context.defaultStateStore = mock(BKStateStoreImpl.class); context.getCounterAsync("test-key"); verify(context.defaultStateStore, times(1)).getCounterAsync(eq("test-key")); }
static BlockStmt getDiscretizeBinVariableDeclaration(final String variableName, final DiscretizeBin discretizeBin) { final MethodDeclaration methodDeclaration = DISCRETIZE_BIN_TEMPLATE.getMethodsByName(GETKIEPMMLDISCRETIZE_BIN).get(0).clone...
@Test void getDiscretizeBinVariableDeclaration() throws IOException { String variableName = "variableName"; double leftMargin = 45.32; Interval interval = new Interval(); interval.setLeftMargin(leftMargin); interval.setRightMargin(null); interval.setClosure(Interval....
public static String random(int size) { return random(size, new Random()); }
@Test public void testRandom() { StringUtils.random(40); assertEquals(StringUtils.random(4, 7), "#,q7"); }
@Override public ObjectNode encode(Driver driver, CodecContext context) { checkNotNull(driver, "Driver cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(NAME, driver.name()) .put(MANUFACTURER, driver.manufacturer()) .put(H...
@Test public void codecTest() { Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours = ImmutableMap.of(TestBehaviour.class, TestBehaviourImpl.class, TestBehaviourTwo.class, TestBehaviourTwoImpl.class); Map<Stri...
@VisibleForTesting public ProcessContinuation run( RestrictionTracker<OffsetRange, Long> tracker, OutputReceiver<PartitionRecord> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, InitialPipelineState initialPipelineState) throws Exception { LOG.debug("DNP: Watermark: "...
@Test public void testUpdateWatermarkOnEvenCountAfter10Seconds() throws Exception { // We update watermark every 2 iterations only if it's been more than 10s since the last update. OffsetRange offsetRange = new OffsetRange(2, Long.MAX_VALUE); when(tracker.currentRestriction()).thenReturn(offsetRange); ...
public List<String> getLiveBrokers() { List<String> brokerUrls = new ArrayList<>(); try { byte[] brokerResourceNodeData = _zkClient.readData(BROKER_EXTERNAL_VIEW_PATH, true); brokerResourceNodeData = unpackZnodeIfNecessary(brokerResourceNodeData); JsonNode jsonObject = OBJECT_READER.readTree(g...
@Test public void testGetBrokerListByInstanceConfigTls() { configureData(_instanceConfigTls, true); final List<String> brokers = _externalViewReaderUnderTest.getLiveBrokers(); assertEquals(brokers, Arrays.asList("first.pug-pinot-broker-headless:8090")); }
public static KeyId ofBytes(byte[] keyIdBytes) { Objects.requireNonNull(keyIdBytes); return new KeyId(Arrays.copyOf(keyIdBytes, keyIdBytes.length)); }
@Test void malformed_utf8_key_id_is_rejected_on_construction() { byte[] malformedIdBytes = new byte[]{ (byte)0xC0 }; // First part of a 2-byte continuation without trailing byte assertThrows(IllegalArgumentException.class, () -> KeyId.ofBytes(malformedIdBytes)); }
@Override public CompletableFuture<V> whenComplete(BiConsumer<? super V, ? super Throwable> action) { return future.handleAsync(new WhenCompleteAdapter(action), defaultExecutor()); }
@Test public void whenComplete_whenExceptional() { CompletableFuture<String> nextStage = delegatingFuture.whenComplete((v, t) -> assertInstanceOf(IllegalArgumentException.class, t)); invocationFuture.completeExceptionally(new IllegalArgumentException()); assertTrueEventually(() -> assertTru...
public static <E> ArrayList<E> newArrayListWithCapacity( int initialArraySize) { checkNonnegative(initialArraySize, "initialArraySize"); return new ArrayList<>(initialArraySize); }
@Test public void testArrayListWithSize() { List<String> list = Lists.newArrayListWithCapacity(3); list.add("record1"); list.add("record2"); list.add("record3"); Assert.assertEquals(3, list.size()); Assert.assertEquals("record1", list.get(0)); Assert.assertEquals("record2", list.get(1)); ...
public void verifyAndValidate(final String jwt) { try { Jws<Claims> claimsJws = Jwts.parser() .verifyWith(tokenConfigurationParameter.getPublicKey()) .build() .parseSignedClaims(jwt); // Log the claims for debugging purposes C...
@Test void givenMalformedToken_whenVerifyAndValidate_thenThrowJwtException() { // Given String malformedToken = "malformed.token.string"; // When & Then assertThatThrownBy(() -> tokenService.verifyAndValidate(malformedToken)) .isInstanceOf(ResponseStatusException.cl...
@Override public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) { // 默认使用积分为 0 result.setUsePoint(0); // 1.1 校验是否使用积分 if (!BooleanUtil.isTrue(param.getPointStatus())) { result.setUsePoint(0); return; } // 1.2 校...
@Test public void testCalculate_success() { // 准备参数 TradePriceCalculateReqBO param = new TradePriceCalculateReqBO() .setUserId(233L).setPointStatus(true) // 是否使用积分 .setItems(asList( new TradePriceCalculateReqBO.Item().setSkuId(10L).setCount(2)....
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final JsonNode event; try { event = objectMapper.readTree(payload); if (event == null || event.isMissingNode()) { throw new ...
@Test public void decodeMessagesHandleGenericBeatMessages() throws Exception { final Message message = codec.decode(messageFromJson("generic.json")); assertThat(message).isNotNull(); assertThat(message.getSource()).isEqualTo("unknown"); assertThat(message.getTimestamp()).isEqualTo(ne...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == ARRAY_GET_SUB_COMMAND_NAME) { returnCommand = getArray(reader); } else if (s...
@Test public void testSet() { String inputCommand = ArrayCommand.ARRAY_SET_SUB_COMMAND_NAME + "\n" + target2 + "\ni1\ni555\ne\n"; try { command.execute("a", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); assertEquals(Array.getInt(array2, 1), 555); ...
@Override public TenantPackageDO validTenantPackage(Long id) { TenantPackageDO tenantPackage = tenantPackageMapper.selectById(id); if (tenantPackage == null) { throw exception(TENANT_PACKAGE_NOT_EXISTS); } if (tenantPackage.getStatus().equals(CommonStatusEnum.DISABLE.getS...
@Test public void testValidTenantPackage_disable() { // mock 数据 TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据 // 调用, 并断言异常 ...
String getProtocol(URL url) { String protocol = url.getSide(); protocol = protocol == null ? url.getProtocol() : protocol; return protocol; }
@Test void testGetProtocol() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&side=provider"); String protocol = abstractMetadataReport.getProtocol(url); assertEquals("provider", ...
@Override public void persist(final String key, final String value) { try { if (isExisted(key)) { update(key, value); return; } String tempPrefix = ""; String parent = SEPARATOR; String[] paths = Arrays.stream(key.sp...
@Test void assertPersistWithUpdateForSimpleKeys() throws SQLException { final String key = "key"; final String value = "value"; when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByKeySQL())).thenReturn(mockPreparedStatement); when(mockJdbcConnection.prepareStatement(rep...
@SuppressWarnings("unchecked") public static synchronized <T extends Cache> T createCache(String name) { T cache = (T) caches.get(name); if (cache != null) { return cache; } cache = (T) cacheFactoryStrategy.createCache(name); log.info("Created cache [" + cacheFac...
@Test public void testCacheCreation() throws Exception { // Setup test fixture. // Execute system under test. final Cache result = CacheFactory.createCache("unittest-cache-creation"); // Verify results. assertNotNull(result); }
@Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { filter(ch, start, length, ignorableWhitespaceOutput); }
@Test public void testNormalWhitespace() throws SAXException { safe.ignorableWhitespace("abc".toCharArray(), 0, 3); assertEquals("abc", output.toString()); }
public static void refreshSuperUserGroupsConfiguration() { //load server side configuration; refreshSuperUserGroupsConfiguration(new Configuration()); }
@Test public void testIPRange() { Configuration conf = new Configuration(); conf.set( DefaultImpersonationProvider.getTestProvider(). getProxySuperuserGroupConfKey(REAL_USER_NAME), "*"); conf.set( DefaultImpersonationProvider.getTestProvider(). getProxySuper...
public Container getContainer() { return container; }
@Test public void getContainer() { assertEquals(container, context.getContainer()); }
@PutMapping @TpsControl(pointName = "NamingServiceUpdate", name = "HttpNamingServiceUpdate") @Secured(action = ActionTypes.WRITE) public String update(HttpServletRequest request) throws Exception { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE...
@Test void testUpdate() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); servletRequest.addParameter("protectThreshold", "0.01"); try { String res = serviceC...
public void decode(ByteBuf in, ByteBuf out) { while (in.isReadable()) { switch (state) { case READING_PREAMBLE: int uncompressedLength = readPreamble(in); if (uncompressedLength == PREAMBLE_NOT_FULL) { // We've not yet read all of the p...
@Test public void testDecodeCopyWithOffsetBeforeChunk() { final ByteBuf in = Unpooled.wrappedBuffer(new byte[] { 0x0a, // preamble length 0x04 << 2, // literal tag + length 0x6e, 0x65, 0x74, 0x74, 0x79, // "netty" 0x05 << 2 | 0x01, // copy with 1-byte offset +...
@Override public int getIdleTimeout() { return clientConfig.getPropertyAsInteger( IClientConfigKey.Keys.ConnIdleEvictTimeMilliSeconds, DEFAULT_IDLE_TIMEOUT); }
@Test void testGetIdleTimeout() { assertEquals(ConnectionPoolConfigImpl.DEFAULT_IDLE_TIMEOUT, connectionPoolConfig.getIdleTimeout()); }
@Override public MapTask apply(MapTask input) { for (ParallelInstruction instruction : Apiary.listOrEmpty(input.getInstructions())) { ParDoInstruction parDoInstruction = instruction.getParDo(); if (parDoInstruction != null) { int numOutputs = Apiary.intOrZero(parDoInstruction.getNumOutputs());...
@Test public void testMissingTagsForMultipleOutputsThrows() { FixMultiOutputInfosOnParDoInstructions function = new FixMultiOutputInfosOnParDoInstructions(IdGenerators.decrementingLongs()); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Invalid ParDoInstruction"); thrown....
public static <InputT, OutputT> PTransformRunnerFactory<?> forWindowedValueMapFnFactory( WindowedValueMapFnFactory<InputT, OutputT> fnFactory) { return new Factory<>(new ExplodedWindowedValueMapperFactory<>(fnFactory)); }
@Test public void testFullWindowedValueMappingWithCompressedWindow() throws Exception { PTransformRunnerFactoryTestContext context = PTransformRunnerFactoryTestContext.builder(EXPECTED_ID, EXPECTED_PTRANSFORM) .processBundleInstructionId("57") .pCollections(Collections.singletonMap...
@GetMapping("/plugin/delete") public Mono<String> delete(@RequestParam("name") final String name) { LOG.info("delete apache shenyu local plugin for {}", name); PluginData pluginData = PluginData.builder().name(name).build(); subscriber.unSubscribe(pluginData); return Mono.just(Consta...
@Test public void testDelete() throws Exception { final String testPluginName = "testDeletePluginName"; final PluginData pluginData = new PluginData(); pluginData.setName(testPluginName); subscriber.onSubscribe(pluginData); assertThat(baseDataCache.obtainPluginData(testPlugin...
public Optional<UserDto> authenticate(HttpRequest request) { return extractCredentialsFromHeader(request) .flatMap(credentials -> Optional.ofNullable(authenticate(credentials, request))); }
@Test public void does_not_authenticate_when_authorization_header_is_not_BASIC() { when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("OTHER " + CREDENTIALS_IN_BASE64); underTest.authenticate(request); verifyNoInteractions(credentialsAuthentication, authenticationEvent); }
public static UAssign create(UExpression variable, UExpression expression) { return new AutoValue_UAssign(variable, expression); }
@Test public void serialization() { SerializableTester.reserializeAndAssert( UAssign.create(UFreeIdent.create("foo"), ULiteral.intLit(5))); }
@Override public Object copy(Object value) { try { Object replacement = writeReplaceMethod.invoke(value); Object newReplacement = getDataSerializer().copy(replacement); return READ_RESOLVE_METHOD.invoke(newReplacement); } catch (Exception e) { throw new RuntimeException("Can't copy lam...
@Test(dataProvider = "furyCopyConfig") public void testLambdaCopy(Fury fury) { { BiFunction<Fury, Object, byte[]> function = (Serializable & BiFunction<Fury, Object, byte[]>) Fury::serialize; fury.copy(function); } { Function<Integer, Integer> function = (Serializable...
@Override public String generateInstanceId(Instance instance) { ensureWorkerIdInitialization(); return SNOW_FLOWER_ID_GENERATOR.nextId() + NAMING_INSTANCE_ID_SPLITTER + instance.getClusterName() + NAMING_INSTANCE_ID_SPLITTER + instance.getServiceName(); }
@Test void testGenerateInstanceId() { final SnowFlakeInstanceIdGenerator instanceIdGenerator = new SnowFlakeInstanceIdGenerator(); Instance instance = new Instance(); Map<String, String> metaData = new HashMap<>(1); metaData.put(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, SNOWFLAKE_...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReflectionServiceDescriptor that = (ReflectionServiceDescriptor) o; return Objects.equals(interfaceName, ...
@Test void testEquals() { ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor(DemoService.class); ReflectionServiceDescriptor service3 = new ReflectionServiceDescriptor(DemoService.class); Assertions.assertEquals(service2, service3); }
@ProcessElement public void processElement( @Element KV<ByteString, ChangeStreamRecord> changeStreamRecordKV, OutputReceiver<KV<ByteString, ChangeStreamMutation>> receiver) { ChangeStreamRecord inputRecord = changeStreamRecordKV.getValue(); if (inputRecord instanceof ChangeStreamMutation) { ...
@Test public void shouldOutputChangeStreamMutations() { ChangeStreamMutation mutation = mock(ChangeStreamMutation.class); doFn.processElement(KV.of(ByteString.copyFromUtf8("test"), mutation), outputReceiver); verify(outputReceiver, times(1)).output(KV.of(ByteString.copyFromUtf8("test"), mutation)); }
@Override public boolean overlap(final Window other) throws IllegalArgumentException { if (getClass() != other.getClass()) { throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type " + other.getClass() + "."); } final Ti...
@Test public void shouldOverlapIfOtherWindowIsWithinThisWindow() { /* * This: [-------) * Other: [---) */ assertTrue(window.overlap(new TimeWindow(start, 75))); assertTrue(window.overlap(new TimeWindow(start, end))); assertTrue(window.overlap...
public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); }
@Test public void testValidateValueMismatchInt16() { assertThrows(DataException.class, () -> ConnectSchema.validateValue(Schema.INT16_SCHEMA, 1)); }
@Override public ByteBuf getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); return this; }
@Test public void testGetBytesAfterRelease2() { final ByteBuf buffer = buffer(); try { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getBytes(0, buffer, 1); ...
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { if (classifier == null) { LOG.warn(getClass().getSimpleName() + " is not configured properly."); re...
@Test public void endToEndTest() throws Exception { Tika tika = getTika("tika-config-sentiment-opennlp.xml"); if (tika == null) { return; } String text = "What a wonderful thought it is that" + " some of the best days of our lives haven't happened yet.";...
Object getFromStep(String stepId, String paramName) { try { return executor .submit(() -> fromStep(stepId, paramName)) .get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new MaestroInternalError( e, "getFromStep throws an exception for stepId=...
@Test public void testInvalidGetFromStep() throws Exception { StepRuntimeSummary summary = loadObject(TEST_STEP_RUNTIME_SUMMARY, StepRuntimeSummary.class); when(allStepOutputData.get("step1")) .thenReturn(Collections.singletonMap("maestro_step_runtime_summary", summary)); AssertHelper.assertThrow...
public static void rollMockClock(Duration delta) { if (clock.equals(Clock.systemUTC())) throw new IllegalStateException("You need to use setMockClock() first."); setMockClock(clock.instant().plus(delta)); }
@Test(expected = IllegalStateException.class) public void rollMockClock_uninitialized() { TimeUtils.rollMockClock(Duration.ofMinutes(1)); }
public static DataSchema canonicalizeDataSchemaForDistinct(QueryContext queryContext, DataSchema dataSchema) { List<ExpressionContext> selectExpressions = queryContext.getSelectExpressions(); int numSelectExpressions = selectExpressions.size(); Preconditions.checkState(dataSchema.size() == numSelectExpressi...
@Test public void testCanonicalizeDataSchemaForDistinct() { QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT DISTINCT col1, col2 + col3 FROM testTable"); // Intentionally make data schema not matching the string representation of the expression DataSchema dataSchema =...
static List<Factory> discoverFactories(ClassLoader classLoader) { final Iterator<Factory> serviceLoaderIterator = ServiceLoader.load(Factory.class, classLoader).iterator(); final List<Factory> loadResults = new ArrayList<>(); while (true) { try { // e...
@Test void testDiscoverFactoryBadClass(@TempDir Path tempDir) throws IOException { // Let's prepare the classloader with a factory interface and 2 classes, one implements our // sub-interface of SerializationFormatFactory and the other implements only // SerializationFormatFactory. f...
@Override public String getHost() { return host; }
@Test public void testGetHost() { assertThat(polarisRegistration1.getHost()).isEqualTo(HOST); }
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { // Automatically detect the character encoding try (AutoDetectReader reader = new AutoDetectReader(CloseShieldInpu...
@Test public void testUTF8Text() throws Exception { String text = "I\u00F1t\u00EBrn\u00E2ti\u00F4n\u00E0liz\u00E6ti\u00F8n"; ContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); parser.parse(new ByteArrayInputStream(text.getBytes(UTF_8)), handler, m...
@Override public boolean test(Pickle pickle) { URI picklePath = pickle.getUri(); if (!lineFilters.containsKey(picklePath)) { return true; } for (Integer line : lineFilters.get(picklePath)) { if (Objects.equals(line, pickle.getLocation().getLine()) ...
@Test void does_not_match_step() { LinePredicate predicate = new LinePredicate(singletonMap( featurePath, singletonList(4))); assertFalse(predicate.test(firstPickle)); assertFalse(predicate.test(secondPickle)); assertFalse(predicate.test(thirdPickle)); ...
public static <T> GoConfigClassLoader<T> classParser(Element e, Class<T> aClass, ConfigCache configCache, GoCipher goCipher, final ConfigElementImplementationRegistry registry, ConfigReferenceElements configReferenceElements) { return new GoConfigClassLoader<>(e, aClass, configCache, goCipher, registry, configR...
@Test public void shouldErrorOutWhenConfigClassHasAttributeAwareConfigTagAnnotationButAttributeIsNotPresent() { final Element element = new Element("example"); final GoConfigClassLoader<ConfigWithAttributeAwareConfigTagAnnotation> loader = GoConfigClassLoader.classParser(element, ConfigWithAttribut...
static byte[] generateRandomPayload(Integer recordSize, List<byte[]> payloadByteList, byte[] payload, SplittableRandom random, boolean payloadMonotonic, long recordValue) { if (!payloadByteList.isEmpty()) { payload = payloadByteList.get(random.nextInt(payloadByteList.size())); } ...
@Test public void testGenerateRandomPayloadByRecordSize() { Integer recordSize = 100; byte[] payload = new byte[recordSize]; List<byte[]> payloadByteList = new ArrayList<>(); SplittableRandom random = new SplittableRandom(0); payload = ProducerPerformance.generateRandomPaylo...
@Nonnull @Override public Iterator<T> getIterator(int unused) { List<T> hosts = new ArrayList<>(_cumulativePointsMap.values()); if (!hosts.isEmpty()) { Collections.shuffle(hosts); //we try to put host with higher probability as the first by calling get. This avoids the situation where unhe...
@Test public void testLowProbabilityHost() throws Exception { Map<URI, Integer> pointsMap = new HashMap<>(); Map<URI, Integer> countsMap = new HashMap<>(); List<URI> goodHosts = addHostsToPointMap(9, 100, pointsMap); List<URI> slowStartHost = addHostsToPointMap(1, 1, pointsMap); Ring<URI> ring = ...
public Object evaluatePredictedValue(final ProcessingDTO processingDTO) { return commonEvaluate(getValueFromKiePMMLNameValuesByVariableName(targetField, processingDTO.getKiePMMLNameValues()) .orElse(null), dataType); }
@Test void evaluatePredictedValue() { final String variableName = "variableName"; KiePMMLOutputField kiePMMLOutputField = KiePMMLOutputField.builder("outputfield", Collections.emptyList()) .withResultFeature(RESULT_FEATURE.PREDICTED_VALUE) .withTargetField(variableNam...
@Override public void beforeMigration(PartitionMigrationEvent event) { if (isPrimaryReplicaMigrationEvent(event)) { ownerMigrationsStarted.incrementAndGet(); } migrationAwareService.beforeMigration(event); }
@Test public void beforeMigration() { // when: countingMigrationAwareService.beforeMigration was invoked (in setUp method) // then: if event involves primary replica, stamp should change. if (isPrimaryReplicaMigrationEvent(event)) { assertEquals(IN_FLIGHT_MIGRATION_STAMP, countin...
@Override public String toString() { return toStringHelper(getClass()) .add("currentHopLimit", Byte.toString(currentHopLimit)) .add("mFlag", Byte.toString(mFlag)) .add("oFlag", Byte.toString(oFlag)) .add("routerLifetime", Short.toString(routerL...
@Test public void testToStringRA() throws Exception { RouterAdvertisement ra = deserializer.deserialize(bytePacket, 0, bytePacket.length); String str = ra.toString(); assertTrue(StringUtils.contains(str, "currentHopLimit=" + (byte) 3)); assertTrue(StringUtils.contains(str, "mFlag=" ...
@SqlInvokedScalarFunction(value = "array_min_by", deterministic = true, calledOnNullInput = true) @Description("Get the minimum value of array, by using a specific transformation function") @TypeParameter("T") @TypeParameter("U") @SqlParameters({@SqlParameter(name = "input", type = "array(T)"), @SqlPara...
@Test public void testArrayMinBy() { assertFunction("ARRAY_MIN_BY(ARRAY [double'1.0', double'2.0'], i -> i)", DOUBLE, 1.0d); assertFunction("ARRAY_MIN_BY(ARRAY [double'-3.0', double'2.0'], i -> i*i)", DOUBLE, 2.0d); assertFunction("ARRAY_MIN_BY(ARRAY ['a', 'bb', 'c'], x -> LENGTH(x))", c...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testMultipleAbortMarkers() { buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(), new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED); ByteBuffer buffer = ByteBuffer.allocate(1024); int currentOffset = 0; ...
@VisibleForTesting static void configureDataSource( BasicDataSource ds, DatabaseMeta databaseMeta, String partitionId, int initialSize, int maximumSize ) throws KettleDatabaseException { // substitute variables and populate pool properties; add credentials Properties connectionPoolProperties = new Prope...
@Test public void testConfigureDataSourceWhenNoDatabaseInterface() throws KettleDatabaseException { when( dbMeta.getDatabaseInterface() ).thenReturn( null ); ConnectionPoolUtil.configureDataSource( dataSource, dbMeta, "partId", INITIAL_SIZE, MAX_SIZE ); verify( dataSource, never() ).setDriverClassLo...
void handleLine(final String line) { final String trimmedLine = Optional.ofNullable(line).orElse("").trim(); if (trimmedLine.isEmpty()) { return; } handleStatements(trimmedLine); }
@Test public void shouldThrowOnCCloudConnectorRequestWithoutApiKey() throws Exception { // Given: final KsqlRestClient mockRestClient = givenMockRestClient(); when(mockRestClient.getIsCCloudServer()).thenReturn(true); when(mockRestClient.getHasCCloudApiKey()).thenReturn(false); // When: final...
@Override public Collection<RejectedAwarePlugin> getRejectedAwarePluginList() { return Collections.emptyList(); }
@Test public void testGetRejectedAwarePluginList() { Assert.assertEquals(Collections.emptyList(), manager.getRejectedAwarePluginList()); }
@Override public boolean isAllowable(URL url, Invocation invocation) { int rate = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY, -1); long interval = url.getMethodParameter( RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_...
@Test void testConfigChange() { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE); url = url.addParamet...
public void uninstall(String pluginKey) { if (!pluginRepository.hasPlugin(pluginKey) || pluginRepository.getPlugin(pluginKey).getType() != EXTERNAL) { throw new IllegalArgumentException(format("Plugin [%s] is not installed", pluginKey)); } Set<String> uninstallKeys = new HashSet<>(); uninstallKey...
@Test public void uninstall() throws Exception { File installedJar = copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); serverPluginRepository.addPlugin(newPlugin("testbase", EXTERNAL, installedJar.getName())); underTest.start(); assertThat(installedJar).exists(); underTe...
@Override public Serde<GenericKey> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> schemaRegistryClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, f...
@Test public void shouldReturnTrackingSerdeNonWindowed() { // When: factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt, Optional.of(callback)); // Then: verify(innerFactory).wrapInTrackingSerde(loggingSerde, callback); }
public void logWithRunnable(Runnable runnable) { long currentTimeMillis = System.currentTimeMillis(); if (disabled) { runnable.run(); } else if (currentTimeMillis > lastLogTime + waitTime) { lastLogTime = currentTimeMillis; runnable.run(); } }
@Test public void testDisable() throws InterruptedException { System.setProperty(RpcOptions.DISABLE_LOG_TIME_WAIT_CONF,"true"); try{ TimeWaitLogger timeWaitLogger = new TimeWaitLogger(100); AtomicLong atomicLong = new AtomicLong(); new Thread(()->{ ...
public void process(Packet packet) { MemberHandshake handshake = serverContext.getSerializationService().toObject(packet); TcpServerConnection connection = (TcpServerConnection) packet.getConn(); if (!connection.setHandshake()) { if (logger.isFinestEnabled()) { logger...
@Test public void process() { tcpServerControl.process(memberHandshakeMessage()); assertExpectedAddressesRegistered(); assertMemberConnectionRegistered(); assertTrueEventually(() -> assertEquals( 0, connectionManager.get...
private String hash(String password, String salt) { return PREFIX + BCrypt.hashpw(password, salt) + SALT_PREFIX + salt; }
@Test public void testHash() throws Exception { final String clearTextPassword = "foobar"; final String hashedPassword = bCryptPasswordAlgorithm.hash(clearTextPassword); assertThat(hashedPassword) .isNotEmpty() .startsWith("{bcrypt}") .contain...
@VisibleForTesting static YarnConfiguration getYarnConfWithRmHaId(Configuration conf) throws IOException { YarnConfiguration yarnConf = new YarnConfiguration(conf); if (yarnConf.get(YarnConfiguration.RM_HA_ID) == null) { // If RM_HA_ID is not configured, use the first of RM_HA_IDS. // Any v...
@Test public void testGetYarnConfWithRmHaId() throws IOException { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_HA_ID, "rm0"); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, false); YarnConfiguration result = YarnClientUtils.getYarnConfWithRmHaId(conf); assertSameCo...
public static String uncompress(byte[] compressedURL) { StringBuffer url = new StringBuffer(); switch (compressedURL[0] & 0x0f) { case EDDYSTONE_URL_PROTOCOL_HTTP_WWW: url.append(URL_PROTOCOL_HTTP_WWW_DOT); break; case EDDYSTONE_URL_PROTOCOL_HTTPS_...
@Test public void testDecompressWithPath() { String testURL = "http://google.com/123"; byte[] testBytes = {0x02, 'g', 'o', 'o', 'g', 'l', 'e', 0x00, '1', '2', '3'}; assertEquals(testURL, UrlBeaconUrlCompressor.uncompress(testBytes)); }
@Override public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) { StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES"); String[] queryParams = null; switch (scope.type()) { case ROOT: // account-level listing baseQuery.append(" IN ACCOUNT"); ...
@SuppressWarnings("unchecked") @Test public void testListIcebergTablesInAccount() throws SQLException { when(mockResultSet.next()) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(mockResultSet.getString("database_name")...
@VisibleForTesting BlockingResultInfo getBlockingResultInfo(IntermediateDataSetID resultId) { return blockingResultInfos.get(resultId); }
@Test void testUpdateBlockingResultInfoWhileScheduling() throws Exception { JobGraph jobGraph = createJobGraph(); Iterator<JobVertex> jobVertexIterator = jobGraph.getVertices().iterator(); JobVertex source1 = jobVertexIterator.next(); JobVertex source2 = jobVertexIterator.next(); ...
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request) throws Exception { BeamFnApi.ProcessBundleResponse.Builder response = BeamFnApi.ProcessBundleResponse.newBuilder(); BundleProcessor bundleProcessor = bundleProcessorCache.get( request, ...
@Test public void testCreatingPTransformExceptionsArePropagated() throws Exception { BeamFnApi.ProcessBundleDescriptor processBundleDescriptor = BeamFnApi.ProcessBundleDescriptor.newBuilder() .putTransforms( "2L", RunnerApi.PTransform.newBuilder() ...
@Override public void validateDictDataList(String dictType, Collection<String> values) { if (CollUtil.isEmpty(values)) { return; } Map<String, DictDataDO> dictDataMap = CollectionUtils.convertMap( dictDataMapper.selectByDictTypeAndValues(dictType, values), DictDat...
@Test public void testValidateDictDataList_notEnable() { // mock 数据 DictDataDO dictDataDO = randomDictDataDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); dictDataMapper.insert(dictDataDO); // 准备参数 String dictType = dictDataDO.getDictType(); List<String> values =...
@Override public int readUnsignedShortLE() { return readShortLE() & 0xFFFF; }
@Test public void testReadUnsignedShortLEAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().readUnsignedShortLE(); } }); }
@SuppressWarnings("unchecked") @Override public void configure(final Map<String, ?> configs, final boolean isKey) { final String windowedInnerClassSerdeConfig = (String) configs.get(StreamsConfig.WINDOWED_INNER_CLASS_SERDE); Serde<T> windowInnerClassSerde = null; if (windowedInnerClassSe...
@Test public void shouldThrowErrorIfWindowedInnerClassSerialiserIsNotSet() { final TimeWindowedSerializer<?> serializer = new TimeWindowedSerializer<>(); assertThrows(IllegalArgumentException.class, () -> serializer.configure(props, false)); }
@Override public ByteBuf discardReadBytes() { if (readerIndex == 0) { ensureAccessible(); return this; } if (readerIndex != writerIndex) { setBytes(0, this, readerIndex, writerIndex - readerIndex); writerIndex -= readerIndex; adjus...
@Test public void testDiscardReadBytes() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 4) { buffer.writeInt(i); } ByteBuf copy = copiedBuffer(buffer); // Make sure there's no effect if called when readerIndex is 0. buffer.readerInde...
public static JsonAsserter with(String json) { return new JsonAsserterImpl(JsonPath.parse(json).json()); }
@Test public void has_path() throws Exception { assertThrows(AssertionError.class, () -> with(JSON).assertNotDefined("$.store.bicycle[?(@.color == 'red' )]")); }
@Override public void onPluginChanged(final List<PluginData> changed, final DataEventTypeEnum eventType) { if (CollectionUtils.isEmpty(changed)) { return; } this.updatePluginCache(); this.afterPluginChanged(changed, eventType); }
@Test public void testOnPluginChanged() { List<PluginData> empty = Lists.newArrayList(); DataEventTypeEnum eventType = mock(DataEventTypeEnum.class); listener.onPluginChanged(empty, eventType); assertFalse(listener.getCache().containsKey(ConfigGroupEnum.PLUGIN.name())); List<...
@Override public org.apache.kafka.streams.kstream.Transformer<KIn, VIn, Iterable<KeyValue<KOut, VOut>>> get() { return new org.apache.kafka.streams.kstream.Transformer<KIn, VIn, Iterable<KeyValue<KOut, VOut>>>() { private final org.apache.kafka.streams.kstream.Transformer<KIn, VIn, KeyValue<KOu...
@Test public void shouldCallTransformOfAdaptedTransformerAndReturnSingletonIterable() { when(transformerSupplier.get()).thenReturn(transformer); when(transformer.transform(key, value)).thenReturn(KeyValue.pair(0, 1)); final TransformerSupplierAdapter<String, String, Integer, Integer> adapte...
public static List<String> getStringList(String property, JsonNode node) { Preconditions.checkArgument(node.has(property), "Cannot parse missing list: %s", property); return ImmutableList.<String>builder() .addAll(new JsonStringArrayIterator(property, node)) .build(); }
@Test public void getStringList() throws JsonProcessingException { assertThatThrownBy(() -> JsonUtil.getStringList("items", JsonUtil.mapper().readTree("{}"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing list: items"); assertThatThrownBy( () -> J...
public Long retryAfter() { return retryAfter; }
@Test void createRetryableExceptionWithResponseAndResponseHeader() { // given Long retryAfter = 5000L; Request request = Request.create(Request.HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8); byte[] response = "response".getBytes(StandardCharsets.UTF_8); Map<String, Collect...
@Override public Map<String, Object> resolve(DynamicConfigEvent event) { final Map<String, Object> result = new HashMap<>(); final Optional<Map<String, Object>> convert = yamlConverter.convert(event.getContent(), Map.class); convert.ifPresent(stringObjectMap -> MapUtils.resolveNestMap(result...
@Test public void resolve() { final DynamicConfigEvent event = Mockito.mock(DynamicConfigEvent.class); Mockito.when(event.getContent()).thenReturn("test: 'hello world'"); final DefaultConfigResolver defaultConfigResolver = new DefaultConfigResolver(); final Map<String, Object> resolv...
public boolean isEnrolled(final UUID accountUuid, final String experimentName) { final Optional<DynamicExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager .getConfiguration().getExperimentEnrollmentConfiguration(experimentName); return maybeConfiguration.map(config -> {...
@Test void testIsEnrolled_UuidExperiment() { assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME)); assertFalse( experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME + "-unrelated-experiment")); when(uuidSelector.getUuids()).thenRet...
@Override public boolean userDefinedIndexMode(boolean enable) { if (meters.isEmpty() && meterIdGenerators.isEmpty()) { userDefinedIndexMode = enable; } else { log.warn("Unable to {} user defined index mode as store did" + "already some allocations", enable...
@Test public void testInvalidEnableUserDefinedIndex() { testStoreMeter(); assertFalse(meterStore.userDefinedIndexMode(true)); }
public static Schema inferWiderSchema(List<Schema> schemas) { if (schemas.isEmpty()) { return null; } else if (schemas.size() == 1) { return schemas.get(0); } else { Schema outputSchema = null; for (Schema schema : schemas) { output...
@Test public void testInferWiderSchema() { // Test normal merges Assertions.assertThat( SchemaUtils.inferWiderSchema( Schema.newBuilder() .physicalColumn("Column1", DataTypes.INT()) ...
@Udf(description = "Converts a string representation of a date in the given format" + " into the number of milliseconds since 1970-01-01 00:00:00 UTC/GMT." + " Single quotes in the timestamp format can be escaped with ''," + " for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time...
@Test public void shouldSupportPSTTimeZone() { // When: final Object result = udf.stringToTimestamp("2018-08-15 10:10:43", "yyyy-MM-dd HH:mm:ss", "America/Los_Angeles"); // Then: assertThat(result, is(1534353043000L)); }
protected List<T> getEntities( @Nonnull final EntityProvider<T, ?> entities, @Nullable final Pageable pageable, @Nullable final Class<T> clazz, @Nullable final Sort sort) { Objects.requireNonNull(entities); Stream<? extends T> entityStream = entities .stream() .filter(this.criteria::evaluate); ...
@Test void getEntities_NoCriteria_NoPageable_NoSortable_Null() { final PageableSortableCollectionQuerier<Customer> querier = new PageableSortableCollectionQuerier<>( new DummyWorkingCopier<>(), Criteria.createNoCriteria() ); Assertions.assertThrows(NullPointerException.class, () -> querier.getEntities(nul...
@Override public void run() { // top-level command, do nothing }
@Test public void test_submit_with_JetBootstrap() throws IOException { Path testJarWithJetBootstrap = Files.createTempFile("testjob-with-jet-bootstrap-", ".jar"); try (InputStream inputStream = HazelcastCommandLineTest.class.getResourceAsStream("testjob-with-jet-bootstrap.jar")) { assert...
public SSLParametersConfiguration getParameters() { if (parameters == null) { parameters = new SSLParametersConfiguration(); } return parameters; }
@Test public void testParameters() throws Exception { assertNotNull(configuration.getParameters()); }
public static int scan(final UnsafeBuffer termBuffer, final int termOffset, final int limitOffset) { int offset = termOffset; while (offset < limitOffset) { final int frameLength = frameLengthVolatile(termBuffer, offset); if (frameLength <= 0) { ...
@Test void shouldReadFirstMessage() { final int offset = 0; final int limit = termBuffer.capacity(); final int messageLength = 50; final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT); when(termBuffer.getIntVolatile(lengthOffset(offset))).thenRe...
public Set<MapperConfig> load(InputStream inputStream) throws IOException { final PrometheusMappingConfig config = ymlMapper.readValue(inputStream, PrometheusMappingConfig.class); return config.metricMappingConfigs() .stream() .flatMap(this::mapMetric) .c...
@Test void metricMatchType() throws Exception { final Map<String, ImmutableList<Serializable>> config = Collections.singletonMap("metric_mappings", ImmutableList.of( ImmutableMap.of( "type", "metric_match", ...
public static String getUnresolvedSchemaName(final Schema schema) { if (!isUnresolvedSchema(schema)) { throw new IllegalArgumentException("Not a unresolved schema: " + schema); } return schema.getProp(UR_SCHEMA_ATTR); }
@Test(expected = IllegalArgumentException.class) public void testGetUnresolvedSchemaNameError() { Schema s = SchemaBuilder.fixed("a").size(10); SchemaResolver.getUnresolvedSchemaName(s); }
@Override public synchronized boolean onActivity() { if (!firstEventReceived) { firstEventReceived = true; return true; } return false; }
@Test public void testOnActivity_SubsequentCalls() { assertTrue(strategy.onActivity(), "First call of onActivity() should return true."); assertFalse(strategy.onActivity(), "Subsequent calls of onActivity() should return false."); }
public static Timer deadlineTimer(final Time time, final long deadlineMs) { long diff = Math.max(0, deadlineMs - time.milliseconds()); return time.timer(diff); }
@Test public void testDeadlineTimer() { long deadlineMs = time.milliseconds() + DEFAULT_TIMEOUT_MS; Timer timer = TimedRequestState.deadlineTimer(time, deadlineMs); assertEquals(DEFAULT_TIMEOUT_MS, timer.remainingMs()); timer.sleep(DEFAULT_TIMEOUT_MS); assertEquals(0, timer.r...
public static Status unblock( final UnsafeBuffer logMetaDataBuffer, final UnsafeBuffer termBuffer, final int blockedOffset, final int tailOffset, final int termId) { Status status = NO_ACTION; int frameLength = frameLengthVolatile(termBuffer, blockedOffset); ...
@Test void shouldPatchToEndOfPartition() { final int messageLength = HEADER_LENGTH * 4; final int termOffset = TERM_BUFFER_CAPACITY - messageLength; final int tailOffset = TERM_BUFFER_CAPACITY; when(mockTermBuffer.getIntVolatile(termOffset)).thenReturn(0); assertEquals(...
protected String cleanExpression(String rawExpression) { if (rawExpression != null && rawExpression.trim().startsWith(MVEL_ESCAPE_SYMBOL)) { return rawExpression.replaceFirst(MVEL_ESCAPE_SYMBOL, ""); } Optional<JsonNode> optionalJSONNode = JsonUtils.convertFromStringToJSONNode(rawExp...
@Test public void cleanExpression() { assertThat(evaluator.cleanExpression(MVEL_ESCAPE_SYMBOL + "test")).isEqualTo("test"); assertThat(evaluator.cleanExpression(MVEL_ESCAPE_SYMBOL + " test")).isEqualTo(" test"); assertThat(evaluator.cleanExpression(MVEL_ESCAPE_SYMBOL + " " + MVEL_ESCAPE_SYMB...
@VisibleForTesting String normalizeArchitecture(String architecture) { // Create mapping based on https://docs.docker.com/engine/install/#supported-platforms if (architecture.equals("x86_64")) { return "amd64"; } else if (architecture.equals("aarch64")) { return "arm64"; } return archi...
@Test public void testNormalizeArchitecture_x86_64() { assertThat(stepsRunner.normalizeArchitecture("x86_64")).isEqualTo("amd64"); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String returnCommand = null; String subCommand = safeReadLine(reader, false); if (subCommand.equals(FIELD_GET_SUB_COMMAND_NAME)) { returnCommand = getField(reader); } else ...
@Test public void testPrimitive() { String inputCommand = "g\n" + target + "\nfield10\ne\n"; try { command.execute("f", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yi10\n", sWriter.toString()); } catch (Exception e) { e.printStackTrace(); fail(); } }