focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static List<Path> getQualifiedRemoteProvidedLibDirs( org.apache.flink.configuration.Configuration configuration, YarnConfiguration yarnConfiguration) throws IOException { return getRemoteSharedLibPaths( configuration, pathStr -> { ...
@Test void testSharedLibWithNonQualifiedPath() throws Exception { final String sharedLibPath = "/flink/sharedLib"; final String nonQualifiedPath = "hdfs://" + sharedLibPath; final String defaultFs = "hdfs://localhost:9000"; final String qualifiedPath = defaultFs + sharedLibPath; ...
@Override public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) { ParamCheckResponse paramCheckResponse = new ParamCheckResponse(); if (paramInfos == null) { paramCheckResponse.setSuccess(true); return paramCheckResponse; } for (ParamInfo pa...
@Test void testCheckParamInfoForServiceName() { ParamInfo paramInfo = new ParamInfo(); ArrayList<ParamInfo> paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); // Max Length String serviceName = buildStringLength(513); paramInfo.setServiceName(serviceName); ...
public static ParseResult parse(String text) { Map<String, String> localProperties = new HashMap<>(); String intpText = ""; String scriptText = null; Matcher matcher = REPL_PATTERN.matcher(text); if (matcher.find()) { String headingSpace = matcher.group(1); intpText = matcher.group(2); ...
@Test void testParagraphTextLocalPropertyNoValueNoText() { ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse("%spark.pyspark(pool)"); assertEquals("spark.pyspark", parseResult.getIntpText()); assertEquals(1, parseResult.getLocalProperties().size()); assertEquals("pool", parseResu...
public static <K> KTableHolder<K> build( final KTableHolder<K> left, final KTableHolder<K> right, final TableTableJoin<K> join ) { final LogicalSchema leftSchema; final LogicalSchema rightSchema; if (join.getJoinType().equals(RIGHT)) { leftSchema = right.getSchema(); rightSc...
@Test public void shouldReturnCorrectLegacySchema() { // Given: join = new TableTableJoin<>( new ExecutionStepPropertiesV1(ctx), JoinType.INNER, ColumnName.of(LEGACY_KEY_COL), left, right ); // When: final KTableHolder<Struct> result = join.build(planBuilde...
public static String getFullGcsPath(String... pathParts) { checkArgument(pathParts.length != 0, "Must provide at least one path part"); checkArgument( stream(pathParts).noneMatch(Strings::isNullOrEmpty), "No path part can be null or empty"); return String.format("gs://%s", String.join("/", pathPart...
@Test public void testGetFullGcsPath() { assertThat(ArtifactUtils.getFullGcsPath("bucket", "dir1", "dir2", "file")) .isEqualTo("gs://bucket/dir1/dir2/file"); }
public List<KinesisRecord> apply(List<KinesisRecord> records, ShardCheckpoint checkpoint) { List<KinesisRecord> filteredRecords = newArrayList(); for (KinesisRecord record : records) { if (checkpoint.isBeforeOrAt(record)) { filteredRecords.add(record); } } return filteredRecords; }
@Test public void shouldFilterOutRecordsBeforeOrAtCheckpoint() { when(checkpoint.isBeforeOrAt(record1)).thenReturn(false); when(checkpoint.isBeforeOrAt(record2)).thenReturn(true); when(checkpoint.isBeforeOrAt(record3)).thenReturn(true); when(checkpoint.isBeforeOrAt(record4)).thenReturn(false); whe...
@Override public String getColumnName(int columnIndex) { return _columnNamesArray.get(columnIndex).asText(); }
@Test public void testGetColumnName() { // Run the test final String result = _resultTableResultSetUnderTest.getColumnName(0); // Verify the results assertEquals("column1", result); }
public static L3ModificationInstruction modArpSha(MacAddress addr) { checkNotNull(addr, "Src l3 ARP address cannot be null"); return new ModArpEthInstruction(L3SubType.ARP_SHA, addr); }
@Test public void testModArpShaMethod() { final Instruction instruction = Instructions.modArpSha(mac1); final L3ModificationInstruction.ModArpEthInstruction modArpEthInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, ...
public static <T> Map<String, T> translateDeprecatedConfigs(Map<String, T> configs, String[][] aliasGroups) { return translateDeprecatedConfigs(configs, Stream.of(aliasGroups) .collect(Collectors.toMap(x -> x[0], x -> Stream.of(x).skip(1).collect(Collectors.toList())))); }
@Test public void testMultipleDeprecations() { Map<String, String> config = new HashMap<>(); config.put("foo.bar.deprecated", "derp"); config.put("foo.bar.even.more.deprecated", "very old configuration"); Map<String, String> newConfig = ConfigUtils.translateDeprecatedConfigs(config, ...
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto) throws ProtoParsingException { return Parsers.fromProto(proto); }
@Test public void parserFromProto() throws Exception { WorkerIdentity identity = WorkerIdentity.Parsers.fromProto( alluxio.grpc.WorkerIdentity.newBuilder() .setVersion(0) .setIdentifier(ByteString.copyFrom(Longs.toByteArray(1L))) .build()); assertEquals(new WorkerId...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final PathAttributes attributes = ...
@Test(expected = NotfoundException.class) public void testNotFound() throws Exception { final Path container = new Path(StringUtils.lowerCase(new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory, Path.Type.volume)); final AzureAttributesFinderFeature f = new AzureAttribute...
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 testRSize31() throws Exception { String hexTransaction = "0xf883370183419ce09433c98f20dd73d7bb1d533c4aa3371f2b30c6ebde80a45093dc7d00000000000000000000000000000000000000000000000000000000000000351c9fb90996c836fb34b782ee3d6efa9e2c79a75b277c014e353b51b23b00524d2da07435ebebca6...
public static <K, V> PerKey<K, V> perKey() { return new AutoValue_ApproximateCountDistinct_PerKey.Builder<K, V>() .setPrecision(HllCount.DEFAULT_PRECISION) .build(); }
@Test @Category(NeedsRunner.class) public void testStandardTypesPerKeyForBytes() { List<KV<Integer, byte[]>> bytes = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int k : INTS1) { bytes.add(KV.of(i, ByteBuffer.allocate(4).putInt(k).array())); } } PCollection<KV<Integer...
@Override public void updateUserPassword(String username, String password) { try { jt.update("UPDATE users SET password = ? WHERE username=?", password, username); } catch (CannotGetJdbcConnectionException e) { LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e); ...
@Test void testUpdateUserPassword() { externalUserPersistService.updateUserPassword("username", "password"); String sql = "UPDATE users SET password = ? WHERE username=?"; Mockito.verify(jdbcTemplate).update(sql, "password", "username"); }
@Override protected SubChannelCopy pick(final List<SubChannelCopy> list) { if (CollectionUtils.isEmpty(list)) { return null; } if (list.size() == 1) { return list.get(0); } int index = getRandomIndexByWeight(list); return list.get(index); }
@Test public void testPick() { SubChannelCopy firstSubChannelCopy = mock(SubChannelCopy.class); SubChannelCopy secondSubChannelCopy = mock(SubChannelCopy.class); when(secondSubChannelCopy.getWeight()).thenReturn(10); List<SubChannelCopy> list = Arrays.asList(firstSubChannelCopy, seco...
public Principal getOriginalPrincipal() { return principal; }
@Test public void shouldReturnOriginalPrincipal() { assertThat(wrappedKsqlPrincipal.getOriginalPrincipal(), is(ksqlPrincipal)); assertThat(wrappedOtherPrincipal.getOriginalPrincipal(), is(otherPrincipal)); }
protected boolean isSimpleTypeNode(JsonNode jsonNode) { if (!jsonNode.isObject()) { return false; } ObjectNode objectNode = (ObjectNode) jsonNode; int numberOfFields = objectNode.size(); return numberOfFields == 1 && objectNode.has(VALUE); }
@Test public void isSimpleTypeNode_emptyNode() { assertThat(expressionEvaluator.isSimpleTypeNode(new ArrayNode(factory))).isFalse(); }
@Override public void trash(final Local file) throws LocalAccessDeniedException { synchronized(NSWorkspace.class) { if(log.isDebugEnabled()) { log.debug(String.format("Move %s to Trash", file)); } // Asynchronous operation. 0 if the operation is performed ...
@Test public void testTrash() throws Exception { Local l = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); new DefaultLocalTouchFeature().touch(l); assertTrue(l.exists()); new WorkspaceTrashFeature().trash(l); assertFalse(l.exists()); }
@Override public boolean match(Message msg, StreamRule rule) { final boolean inverted = rule.getInverted(); final Object field = msg.getField(rule.getField()); if (field != null) { final String value = field.toString(); return inverted ^ value.contains(rule.getValue(...
@Test public void testInvertedNullFieldShouldMatch() { final String fieldName = "nullfield"; rule.setField(fieldName); rule.setInverted(true); msg.addField(fieldName, null); final StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); ...
@SuppressWarnings("") @Nonnull public static Number parse(@Nonnull String input) { String text = input.trim().toUpperCase(); Number value; if (text.indexOf('.') > 0) { value = parseDecimal(text); } else { if (text.endsWith("L") && text.startsWith("0X")) { String substring = text.substring(2, text.in...
@Test void testParse() { assertEquals(0, NumberUtil.parse("0")); assertEquals(0L, NumberUtil.parse("0L")); assertEquals(0D, NumberUtil.parse("0.0")); assertEquals(0D, NumberUtil.parse("0.0d")); assertEquals(0D, NumberUtil.parse("0.0D")); assertEquals(0F, NumberUtil.parse("0.0f")); assertEquals(0F, Number...
public boolean isIn(Number toEvaluate) { switch (closure) { case OPEN_OPEN: return isInsideOpenOpen(toEvaluate); case OPEN_CLOSED: return isInsideOpenClosed(toEvaluate); case CLOSED_OPEN: return isInsideClosedOpen(toEvaluate); ...
@Test void isIn() { KiePMMLInterval kiePMMLInterval = new KiePMMLInterval(20, 40, CLOSURE.OPEN_OPEN); assertThat(kiePMMLInterval.isIn(30)).isTrue(); assertThat(kiePMMLInterval.isIn(10)).isFalse(); assertThat(kiePMMLInterval.isIn(20)).isFalse(); assertThat(kiePMMLInterval.isIn...
@Override public Map<String, String> evaluate(FunctionArgs args, EvaluationContext context) { final String value = valueParam.required(args, context); if (Strings.isNullOrEmpty(value)) { return Collections.emptyMap(); } final CharMatcher kvPairsMatcher = splitParam.option...
@Test void testDisableDuplicateKeys() { final Map<String, Expression> arguments = Map.of("value", valueExpression, "allow_dup_keys", new BooleanExpression(new CommonToken(0), false)); Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.evaluate(new FunctionA...
@Override public void execute(Runnable runnable) { // run the task synchronously runnable.run(); }
@Test public void testSynchronousExecutorService() { String name1 = Thread.currentThread().getName(); ExecutorService service = new SynchronousExecutorService(); service.execute(new Runnable() { public void run() { invoked = true; name2 = Thread.c...
public static VersionedBytesStoreSupplier persistentVersionedKeyValueStore(final String name, final Duration historyRetention) { Objects.requireNonNull(name, "name cannot be null"); final String hrMsgPrefix = prepareMillisChe...
@Test public void shouldThrowIfPersistentVersionedKeyValueStoreSegmentIntervalIsZeroOrNegative() { Exception e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentVersionedKeyValueStore("anyName", ZERO, ZERO)); assertEquals("segmentInterval cannot be zero or negative", e.getMessage...
@Override public void register(String path, ServiceRecord record) throws IOException { op(path, record, addRecordCommand); }
@Test public void testAAAALookup() throws Exception { ServiceRecord record = getMarshal().fromBytes("somepath", CONTAINER_RECORD.getBytes()); getRegistryDNS().register( "/registry/users/root/services/org-apache-slider/test1/components/" + "ctr-e50-1451931954322-0016-01-000002", ...
public static String md5Hex (String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex (md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } ...
@Test public void testMd5Hex() { String md5 = HashUtil.md5Hex("stevehu@gmail.com"); Assert.assertEquals(md5, "417bed6d9644f12d8bc709059c225c27"); }
public void clear() { mUserProps.clear(); mSources.clear(); }
@Test public void clear() { mProperties.put(mKeyWithValue, "ignored1", Source.RUNTIME); mProperties.put(mKeyWithoutValue, "ignored2", Source.RUNTIME); mProperties.clear(); assertEquals(null, mProperties.get(mKeyWithoutValue)); assertEquals("value", mProperties.get(mKeyWithValue)); }
public static DeviceKey createDeviceKeyUsingCommunityName(DeviceKeyId id, String label, String name) { DefaultAnnotations annotations = builder().set(AnnotationKeys.NAME, name).build(); return new DeviceKey(id, label, Type.COMMUNITY_NAME, annotations); }
@Test public void testCreateDeviceKeyUsingCommunityName() { DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue); DeviceKey deviceKey = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId, deviceKeyLabel, d...
public String getHost() { return host; }
@Test public void testGetHost() { shenyuRequestLog.setHost("test"); Assertions.assertEquals(shenyuRequestLog.getHost(), "test"); }
@Deprecated public static BoundedSource<Long> upTo(long numElements) { checkArgument( numElements >= 0, "numElements (%s) must be greater than or equal to 0", numElements); return new BoundedCountingSource(0, numElements); }
@Test @Category(NeedsRunner.class) public void testBoundedSource() { long numElements = 1000; PCollection<Long> input = p.apply(Read.from(CountingSource.upTo(numElements))); addCountingAsserts(input, numElements); p.run(); }
@Override public void verify(X509Certificate certificate, Date date) { logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal()); // Create trustAnchors final Set<TrustAnchor> trustAnchors = getTrusted().stream().map( ...
@Test public void shouldThrowExceptionIfCertificateIsRevoked() { thrown.expect(VerificationException.class); thrown.expectMessage("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"); ...
public Exporter getCompatibleExporter(TransferExtension extension, DataVertical jobType) { Exporter<?, ?> exporter = getExporterOrNull(extension, jobType); if (exporter != null) { return exporter; } switch (jobType) { case MEDIA: exporter = getMediaExporter(extension); break...
@Test public void shouldConstructPhotoAndVideoExportersFromMedia() { TransferExtension ext = mock(TransferExtension.class); when(ext.getExporter(eq(MEDIA))).thenReturn(mock(Exporter.class)); assertThat(compatibilityProvider.getCompatibleExporter(ext, PHOTOS)) .isInstanceOf(AnyToAnyExporter.class)...
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { if (userSession.hasSession() && userSession.isLoggedIn() && userSession.shouldResetPassword()) { redirectTo(response, request.getContextPath() + RESET_PASSWORD_PATH); } chain.doFilter(...
@Test public void redirect_if_reset_password_set() throws Exception { underTest.doFilter(request, response, chain); verify(response).sendRedirect("/account/reset_password"); }
public static Combine.CombineFn<Boolean, ?, Long> combineFn() { return new CountIfFn(); }
@Test public void testCreatesAccumulatorCoder() throws CannotProvideCoderException { assertNotNull( CountIf.combineFn().getAccumulatorCoder(CoderRegistry.createDefault(), BooleanCoder.of())); }
@Override public Map<String, String> getMetadata(final Path file) throws BackgroundException { return new S3AttributesFinderFeature(session, acl).find(file).getMetadata(); }
@Test public void testGetMetadataBucket() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(con...
@Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { startQosServer(url, false); return protocol.refer(type, url); }
@Test void testRefer() throws Exception { wrapper.refer(BaseCommand.class, url); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); assertThat(server.getPort(), is(12345)); assertThat(server.isAcceptForeignIp(), is(false)); verify...
public static Optional<PfxOptions> getPfxKeyStoreOptions(final Map<String, String> props) { // PFX key stores do not have a Private key password final String location = getKeyStoreLocation(props); final String password = getKeyStorePassword(props); if (!Strings.isNullOrEmpty(location)) { return O...
@Test public void shouldReturnEmptyKeyStorePfxOptionsIfLocationIsEmpty() { // When final Optional<PfxOptions> pfxOptions = VertxSslOptionsFactory.getPfxKeyStoreOptions( ImmutableMap.of() ); // Then assertThat(pfxOptions, is(Optional.empty())); }
public static ParameterizedType parameterizedType(Class<?> rawType, Type... typeArguments) { var typeParamsCount = rawType.getTypeParameters().length; if (typeParamsCount == 0) { throw new IllegalArgumentException( String.format( "Cannot parameterize `%s` because it does not have a...
@Test public void createParameterizedTypeWithIncompatibleTypeArgument() { Throwable t = catchThrowable(() -> Types.parameterizedType(Foo.class, String.class)); assertThat(t) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Type argument `java.lang.String` for type param...
public void setClickHouseLogConfig(final ClickHouseLogConfig clickHouseLogConfig) { this.clickHouseLogConfig = clickHouseLogConfig; }
@Test public void testSetClickHouseLogConfig() { clickHouseLogCollectConfig.setClickHouseLogConfig(clickHouseLogConfig); Assertions.assertNull(null); }
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("BatchEventData{"); for (QueryCacheEventData event : events) { stringBuilder.append(event); } stringBuilder.append("}"); return stringBuilder.toStr...
@Test public void testToString() { assertContains(batchEventData.toString(), "BatchEventData"); }
@Deprecated public static SegwitAddress fromBech32(@Nullable NetworkParameters params, String bech32) throws AddressFormatException { return (SegwitAddress) AddressParser.getLegacy(params).parseAddress(bech32); }
@Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBech32m_taprootTooShort() { // Taproot, valid bech32m encoding, checksum ok, padding ok, but no valid Segwit v1 program // (this program is 20 bytes long, but only 32 bytes program length are valid for Segwit v1/Taproot...
@Override public TCreatePartitionResult createPartition(TCreatePartitionRequest request) throws TException { LOG.info("Receive create partition: {}", request); TCreatePartitionResult result; try { if (partitionRequestNum.incrementAndGet() >= Config.thrift_server_max_worker_thre...
@Test public void testCreatePartitionApiSlice() throws TException { new MockUp<GlobalTransactionMgr>() { @Mock public TransactionState getTransactionState(long dbId, long transactionId) { return new TransactionState(); } }; Database db = G...
void doSyntaxCheck(NamespaceTextModel model) { if (StringUtils.isBlank(model.getConfigText())) { return; } // only support yaml syntax check if (model.getFormat() != ConfigFileFormat.YAML && model.getFormat() != ConfigFileFormat.YML) { return; } // use YamlPropertiesFactoryBean to ...
@Test public void yamlSyntaxCheckOK() throws Exception { String yaml = loadYaml("case1.yaml"); itemController.doSyntaxCheck(assemble(ConfigFileFormat.YAML.getValue(), yaml)); }
private Collection<Integer> transform(Transformation<?> transform) { if (alreadyTransformed.containsKey(transform)) { return alreadyTransformed.get(transform); } LOG.debug("Transforming " + transform); if (transform.getMaxParallelism() <= 0) { // if the max par...
@Test void testOutputTypeConfigurationWithUdfStreamOperator() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); OutputTypeConfigurableFunction<Integer> function = new OutputTypeConfigurableFunction<>(); DataStream<Integer> source = env.fromData(1, 10)...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMapPutIfAbsentNoReadSucceeds() throws Exception { StateTag<MapState<String, Integer>> addr = StateTags.map("map", StringUtf8Coder.of(), VarIntCoder.of()); MapState<String, Integer> mapState = underTest.state(NAMESPACE, addr); final String tag1 = "tag1"; SettableFuture<In...
@Override public TreeEntryNode<K, V> putNode(K key, V value) { TreeEntryNode<K, V> target = nodes.get(key); if (ObjectUtil.isNotNull(target)) { final V oldVal = target.getValue(); target.setValue(value); return target.copy(oldVal); } target = new TreeEntryNode<>(null, key, value); nodes.put(key, tar...
@Test public void getNodeValueTest() { final ForestMap<String, String> map = new LinkedForestMap<>(false); map.putNode("a", "aaa"); assertEquals("aaa", map.getNodeValue("a")); assertNull(map.getNodeValue("b")); }
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testGreaterThan() { Evaluator evaluator = new Evaluator(STRUCT, greaterThan("x", 7)); assertThat(evaluator.eval(TestHelpers.Row.of(7, 8, null))).as("7 > 7 => false").isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of(6, 8, null))).as("6 > 7 => false").isFalse(); assertThat(evalu...
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testConcurrency_MultiInstance() throws InterruptedException { int iterations = 100; final AtomicInteger lockedCounter = new AtomicInteger(); testMultiInstanceConcurrency(iterations, r -> { Lock lock = r.getLock("testConcurrency_MultiInstance2"); loc...
public long parseForStore(TimelineDataManager tdm, Path appDirPath, boolean appCompleted, JsonFactory jsonFactory, ObjectMapper objMapper, FileSystem fs) throws IOException { LOG.debug("Parsing for log dir {} on attempt {}", appDirPath, attemptDirName); Path logPath = getPath(appDirPath); ...
@Test void testParseBrokenEntity() throws Exception { // Load test data TimelineDataManager tdm = PluginStoreTestUtils.getTdmWithMemStore(config); EntityLogInfo testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_BROKEN_FILE_NAME, UserGroupInformation.getLoginUser().getUserName());...
public static SerdeFeatures of(final SerdeFeature... features) { return new SerdeFeatures(ImmutableSet.copyOf(features)); }
@Test public void shouldSerializeAsValue() throws Exception { // Given: final SerdeFeatures features = SerdeFeatures.of(WRAP_SINGLES); // When: final String json = MAPPER.writeValueAsString(features); // Then: assertThat(json, is("[\"WRAP_SINGLES\"]")); }
public void initNewOpenIssue(DefaultIssue issue) { Preconditions.checkArgument(issue.isFromExternalRuleEngine() != (issue.type() == null), "At this stage issue type should be set for and only for external issues"); Rule rule = ruleRepository.getByKey(issue.ruleKey()); issue.setKey(Uuids.create()); issue...
@Test public void initNewOpenIssue() { DefaultIssue issue = new DefaultIssue() .setRuleKey(XOO_X1); when(debtCalculator.calculate(issue)).thenReturn(DEFAULT_DURATION); underTest.initNewOpenIssue(issue); assertThat(issue.key()).isNotNull(); assertThat(issue.creationDate()).isNotNull(); ...
public static boolean shouldLoadInIsolation(String name) { return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches()); }
@Test public void testConnectRuntimeClasses() { // Only list packages, because there are too many classes. List<String> runtimeClasses = Arrays.asList( "org.apache.kafka.connect.cli.", //"org.apache.kafka.connect.connector.policy.", isolated by default //"org.apac...
@Override public boolean put(K key, V value) { return get(putAsync(key, value)); }
@Test public void testReadAllKeySet() { RListMultimap<String, String> map = redisson.getListMultimap("test1"); map.put("1", "4"); map.put("2", "5"); map.put("3", "6"); assertThat(map.readAllKeySet()).containsExactly("1", "2", "3"); }
public static Builder builder() { return new Builder(); }
@Test void whenReturnTypeIsResponseNoErrorHandling() { Map<String, Collection<String>> headers = new LinkedHashMap<>(); headers.put("Location", Collections.singletonList("http://bar.com")); final Response response = Response.builder().status(302).reason("Found").headers(headers) .request(Request.c...
@Override public DarkClusterConfigMap getDarkClusterConfigMap(String clusterName) throws ServiceUnavailableException { FutureCallback<DarkClusterConfigMap> darkClusterConfigMapFutureCallback = new FutureCallback<>(); getDarkClusterConfigMap(clusterName, darkClusterConfigMapFutureCallback); try { ...
@Test public void testClusterInfoProviderGetDarkClustersNoUris() throws InterruptedException, ExecutionException, ServiceUnavailableException { MockStore<ServiceProperties> serviceRegistry = new MockStore<>(); MockStore<ClusterProperties> clusterRegistry = new MockStore<>(); MockStore<UriPropertie...
public static <T> void swapElement(List<T> list, T element, T targetElement) { if (CollUtil.isNotEmpty(list)) { final int targetIndex = list.indexOf(targetElement); if (targetIndex >= 0) { swapTo(list, element, targetIndex); } } }
@Test public void swapElement() { final Map<String, String> map1 = new HashMap<>(); map1.put("1", "张三"); final Map<String, String> map2 = new HashMap<>(); map2.put("2", "李四"); final Map<String, String> map3 = new HashMap<>(); map3.put("3", "王五"); final List<Map<String, String>> list = Arrays.asList(map1,...
public IndexRecord getIndexInformation(String mapId, int reduce, Path fileName, String expectedIndexOwner) throws IOException { IndexInformation info = cache.get(mapId); if (info == null) { info = readIndexFileToCache(fileName, mapId, expectedIndexOwner); ...
@Test public void testBadIndex() throws Exception { final int parts = 30; fs.delete(p, true); conf.setInt(MRJobConfig.SHUFFLE_INDEX_CACHE, 1); IndexCache cache = new IndexCache(conf); Path f = new Path(p, "badindex"); FSDataOutputStream out = fs.create(f, false); CheckedOutputStream iout ...
public static GSBlobIdentifier parseUri(URI uri) { Preconditions.checkArgument( uri.getScheme().equals(GSFileSystemFactory.SCHEME), String.format("URI scheme for %s must be %s", uri, GSFileSystemFactory.SCHEME)); String finalBucketName = uri.getAuthority(); if (S...
@Test public void shouldParseValidUri() { GSBlobIdentifier blobIdentifier = BlobUtils.parseUri(URI.create("gs://bucket/foo/bar")); assertEquals("bucket", blobIdentifier.bucketName); assertEquals("foo/bar", blobIdentifier.objectName); }
@Override public String getBucketId(IN element, BucketAssigner.Context context) { if (dateTimeFormatter == null) { dateTimeFormatter = DateTimeFormatter.ofPattern(formatString).withZone(zoneId); } return dateTimeFormatter.format(Instant.ofEpochMilli(context.currentProcessingTime(...
@Test void testGetBucketPathWithSpecifiedTimezone() { DateTimeBucketAssigner bucketAssigner = new DateTimeBucketAssigner(ZoneId.of("America/Los_Angeles")); assertThat(bucketAssigner.getBucketId(null, mockedContext)).isEqualTo("2018-08-03--23"); }
public static SortDir sortDir(String s) { return !DESC.equals(s) ? SortDir.ASC : SortDir.DESC; }
@Test public void sortDirOther() { assertEquals("other sort dir", SortDir.ASC, TableModel.sortDir("other")); }
public synchronized Map<String, Object> getSubtaskProgress(String taskName, @Nullable String subtaskNames, Executor executor, HttpClientConnectionManager connMgr, Map<String, String> workerEndpoints, Map<String, String> requestHeaders, int timeoutMs) throws Exception { return getSubtaskProgress(ta...
@Test public void testGetSubtaskProgressNoResponse() throws Exception { TaskDriver taskDriver = mock(TaskDriver.class); JobConfig jobConfig = mock(JobConfig.class); when(taskDriver.getJobConfig(anyString())).thenReturn(jobConfig); JobContext jobContext = mock(JobContext.class); when(taskDriv...
public static StreamDecoder create(Decoder iteratorDecoder) { return new StreamDecoder(iteratorDecoder, null); }
@Test void simpleDeleteDecoderTest() { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo\nbar")); StreamInterface api = Feign.builder() .decoder(StreamDecoder.create((r, t) -> { BufferedReader bufferedReader = new BufferedReader(r.body().asReader...
@Override public boolean isActive(CommandLine commandLine) { return configuration.getOptional(DeploymentOptions.TARGET).isPresent() || commandLine.hasOption(executorOption.getOpt()) || commandLine.hasOption(targetOption.getOpt()); }
@Test void isActiveWhenTargetOnlyInConfig() throws CliArgsException { final String expectedExecutorName = "test-executor"; final Configuration loadedConfig = new Configuration(); loadedConfig.set(DeploymentOptions.TARGET, expectedExecutorName); final GenericCLI cliUnderTest = ...
@Override public TStreamLoadPutResult streamLoadPut(TStreamLoadPutRequest request) { String clientAddr = getClientAddrAsString(); LOG.info("receive stream load put request. db:{}, tbl: {}, txn_id: {}, load id: {}, backend: {}", request.getDb(), request.getTbl(), request.getTxnId(), D...
@Test public void testStreamLoadPutColumnMapException() { FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv); TStreamLoadPutRequest request = new TStreamLoadPutRequest(); request.setDb("test"); request.setTbl("site_access_hour"); request.setUser("root"); reque...
public SemanticRules(List<RuleBase> ruleBases) { this.ruleBases = ruleBases; }
@Test void semanticRulesTest() throws ParseException, IOException { SemanticRuleBuilder ruleBuilder = new SemanticRuleBuilder(); SemanticRules rules = ruleBuilder.build(FilesApplicationPackage.fromFile(new File(root))); SemanticRulesConfig.Builder configBuilder = new SemanticRulesConfig.Buil...
private static Schema optional(Schema original) { // null is first in the union because Parquet's default is always null return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), original)); }
@Test public void testOptionalFields() throws Exception { Schema schema = Schema.createRecord("record1", null, null, false); Schema optionalInt = optional(Schema.create(INT)); schema.setFields( Collections.singletonList(new Schema.Field("myint", optionalInt, null, JsonProperties.NULL_VALUE))); ...
@Override public void validateRoleList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得角色信息 List<RoleDO> roles = roleMapper.selectBatchIds(ids); Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId); // 校验 ids.forEach(id ...
@Test public void testValidateRoleList_success() { // mock 数据 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); roleMapper.insert(roleDO); // 准备参数 List<Long> ids = singletonList(roleDO.getId()); // 调用,无需断言 roleSe...
@Operation(summary = "verifyNamespaceK8s", description = "VERIFY_NAMESPACE_K8S_NOTES") @Parameters({ @Parameter(name = "namespace", description = "NAMESPACE", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "clusterCode", description = "CLUSTER_CODE", req...
@Test public void verifyNamespace() throws Exception { // queue value exist MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("namespace", "NAMESPACE_CREATE_STRING"); paramsMap.add("clusterCode", "100"); // success MvcResult mvcRes...
@VisibleForTesting List<MessageSummary> getMessageBacklog(EventNotificationContext ctx, TeamsEventNotificationConfigV2 config) { List<MessageSummary> backlog = notificationCallbackService.getBacklogForEvent(ctx); if (config.backlogSize() > 0 && backlog != null) { return backlog.stream()....
@Test public void testBacklogMessageLimitWhenEventNotificationContextIsNull() { TeamsEventNotificationConfigV2 config = TeamsEventNotificationConfigV2.builder() .backlogSize(0) .build(); // Global setting is at 50 and the eventNotificationContext is null then the mes...
public synchronized long nextGtid() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { timestamp = lastTimestamp; } if (lastTimestamp == timestamp) { sequence = (sequence + 1) & MAX_SEQUENCE; if (sequence == 0) { timestamp...
@Test public void testNextGtidIncrementsSequenceOnSameMillisecond() { long firstGtid = gtidGenerator.nextGtid(); long secondGtid = gtidGenerator.nextGtid(); Assertions.assertNotEquals(firstGtid, secondGtid, "GTIDs should be unique"); Assertions.assertEquals((firstGtid & GtidGenerato...
public static ParseFiles parseFiles() { return new AutoValue_TikaIO_ParseFiles.Builder().build(); }
@Test public void testParseFilesDisplayData() { TikaIO.ParseFiles parseFiles = TikaIO.parseFiles() .withTikaConfigPath("/tikaConfigPath") .withContentTypeHint("application/pdf"); DisplayData displayData = DisplayData.from(parseFiles); assertThat(displayData, hasDisplayIte...
@VisibleForTesting static DefaultIssue toDefaultIssue(IssueCache.Issue next) { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setKey(next.getKey()); defaultIssue.setType(RuleType.valueOf(next.getRuleType())); defaultIssue.setComponentUuid(next.hasComponentUuid() ? next.getComponentUuid()...
@Test public void toDefaultIssue_whenCleanCodeAttributeIsSet_shouldSetItInDefaultIssue() { IssueCache.Issue issue = prepareIssueWithCompulsoryFields() .setCleanCodeAttribute(CleanCodeAttribute.FOCUSED.name()) .build(); DefaultIssue defaultIssue = ProtobufIssueDiskCache.toDefaultIssue(issue); ...
@Override public AddToClusterNodeLabelsResponse addToClusterNodeLabels( AddToClusterNodeLabelsRequest request) throws YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterServerUtil.logAndThrowExceptio...
@Test public void testAddToClusterNodeLabelsEmptyRequest() throws Exception { // null request1. LambdaTestUtils.intercept(YarnException.class, "Missing AddToClusterNodeLabels request.", () -> interceptor.addToClusterNodeLabels(null)); // null request2. AddToClusterNodeLabelsRequest request = ...
@Override public void checkBeforeUpdate(final CreateReadwriteSplittingRuleStatement sqlStatement) { ReadwriteSplittingRuleStatementChecker.checkCreation(database, sqlStatement.getRules(), null == rule ? null : rule.getConfiguration(), sqlStatement.isIfNotExists()); }
@Test void assertCheckSQLStatementWithDuplicateReadResourceNames() { ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class); when(rule.getConfiguration()).thenReturn(createCurrentRuleConfiguration()); executor.setRule(rule); assertThrows(DuplicateReadwriteSplittingActualDat...
@Override public IndexType.IndexMainType getMainType() { return mainType; }
@Test public void getMainType_returns_main_type_of_authorization_for_index_of_constructor() { NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration); assertThat(underTest.getMainType()).isEqualTo(IndexType.main(someIndex, "auth")); }
public static boolean isContent(ServiceCluster cluster) { return isContent(cluster.serviceType()); }
@Test public void verifyContentClusterIsRecognized() { ServiceCluster cluster = createServiceCluster(ServiceType.DISTRIBUTOR); assertTrue(VespaModelUtil.isContent(cluster)); cluster = createServiceCluster(ServiceType.STORAGE); assertTrue(VespaModelUtil.isContent(cluster)); cl...
static SortKey[] rangeBounds( int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) { // sort the keys first Arrays.sort(samples, comparator); int numCandidates = numPartitions - 1; SortKey[] candidates = new SortKey[numCandidates]; int step = (int) Math.ceil((double) sample...
@Test public void testRangeBoundsSkipDuplicates() { // step is 3 = ceiling(11/4) assertThat( SketchUtil.rangeBounds( 4, SORT_ORDER_COMPARTOR, new SortKey[] { CHAR_KEYS.get("a"), CHAR_KEYS.get("b"), ...
@Override public List<Intent> compile(LinkCollectionIntent intent, List<Intent> installable) { SetMultimap<DeviceId, PortNumber> inputPorts = HashMultimap.create(); SetMultimap<DeviceId, PortNumber> outputPorts = HashMultimap.create(); Map<ConnectPoint, Identifier<?>> labels = ImmutableMap....
@Test public void testFilteredConnectPointForMpWithEncap() throws Exception { LinkCollectionCompiler.labelAllocator.setLabelSelection(LABEL_SELECTION); Set<Link> testLinks = ImmutableSet.of( DefaultLink.builder().providerId(PID).src(of1p2).dst(of2p1).type(DIRECT).build(), ...
public static GlobalTransaction reload(String xid) throws TransactionException { return new DefaultGlobalTransaction(xid, GlobalStatus.UnKnown, GlobalTransactionRole.Launcher) { @Override public void begin(int timeout, String name) throws TransactionException { throw new ...
@Test void reloadTest() throws TransactionException { GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate(); tx = GlobalTransactionContext.reload(DEFAULT_XID); GlobalTransaction finalTx = tx; Assertions.assertThrows(IllegalStateException.class, finalTx::begin); }
static <T extends Comparable<? super T>> int compareListWithFillValue( List<T> left, List<T> right, T fillValue) { int longest = Math.max(left.size(), right.size()); for (int i = 0; i < longest; i++) { T leftElement = fillValue; T rightElement = fillValue; if (i < left.size()) { ...
@Test public void compareWithFillValue_oneEmptyListAndLargeFillValue_returnsPositive() { assertThat( ComparisonUtility.compareListWithFillValue( Lists.newArrayList(), Lists.newArrayList(1, 2, 3), 100)) .isGreaterThan(0); }
@Override public ByteBuffer read(long offset, long length) throws IOException { if (length == 0 || offset >= mFileSize) { return EMPTY_BYTE_BUFFER; } // cap length to the remaining of block, as the caller may pass in a longer length than what // is left in the block, but expect as many bytes as...
@Test public void read() throws IOException { int testNum = Math.min(mFileLen, mMinTestNum); for (int i = 0; i < testNum; i++) { int offset = mRandom.nextInt(mFileLen); int readLength = mRandom.nextInt(mFileLen - offset); byte[] tmpBytes = Files.readAllBytes(Paths.get(mTestFileName)); ...
public String getMetricsByConfigId(String configId) { List<VespaService> services = vespaServices.getInstancesById(configId); vespaServices.updateServices(services); return vespaMetrics.getMetricsAsString(services); }
@Test public void verify_expected_output_from_getMetricsById() { String dummy0Metrics = metricsManager.getMetricsByConfigId(SERVICE_0_ID); assertTrue(dummy0Metrics.contains("'dummy.id.0'.val=1.050")); assertTrue(dummy0Metrics.contains("'dummy.id.0'.c_test=1")); String dummy1Metrics ...
public List<Instance> findInstancesByIds(Set<Long> instanceIds) { Iterable<Instance> instances = instanceRepository.findAllById(instanceIds); return Lists.newArrayList(instances); }
@Test @Rollback public void testFindInstancesByIds() throws Exception { String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someDataCenter = "someDataCenter"; String someIp = "someIp"; String anotherIp = "anotherIp"; Instance someInstance = instanceService.cre...
@Override public SelType binaryOps(SelOp op, SelType rhs) { if (rhs.type() == SelTypes.NULL) { if (op == SelOp.EQUAL || op == SelOp.NOT_EQUAL) { return rhs.binaryOps(op, this); } else { throw new UnsupportedOperationException( this.type() + " DO NOT support " + op + " for r...
@Test(expected = UnsupportedOperationException.class) public void testInvalidBinaryOpType() { one.binaryOps(SelOp.ADD, SelType.NULL); }
@Override public final void mark(int readlimit) { mark = pos; }
@Test public void testMark() { in.position(1); in.mark(1); assertEquals(1, in.mark); }
public static void delete(final File rootFile) throws IOException { if (rootFile == null) return; Files.walkFileTree(rootFile.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException { ...
@Timeout(120) @Test public void testRecursiveDelete() throws IOException { Utils.delete(null); // delete of null does nothing. // Test that deleting a temporary file works. File tempFile = TestUtils.tempFile(); Utils.delete(tempFile); assertFalse(Files.exists(tempFile.to...
public void handleEventFromOperator(int subtask, int attemptNumber, OperatorEvent event) throws Exception { mainThreadExecutor.assertRunningInMainThread(); if (event instanceof AcknowledgeCheckpointEvent) { subtaskGatewayMap .get(subtask) ....
@Test void takeCheckpointAfterSuccessfulCheckpoint() throws Exception { final EventReceivingTasks tasks = EventReceivingTasks.createForRunningTasks(); final OperatorCoordinatorHolder holder = createCoordinatorHolder(tasks, TestingOperatorCoordinator::new); getCoordinator(hol...
public static <T> T fillBeanWithMapIgnoreCase(Map<?, ?> map, T bean, boolean isIgnoreError) { return fillBeanWithMap(map, bean, CopyOptions.create().setIgnoreCase(true).setIgnoreError(isIgnoreError)); }
@Test public void fillBeanWithMapIgnoreCaseTest() { final Map<String, Object> map = MapBuilder.<String, Object>create() .put("Name", "Joe") .put("aGe", 12) .put("openId", "DFDFSDFWERWER") .build(); final SubPerson person = BeanUtil.fillBeanWithMapIgnoreCase(map, new SubPerson(), false); assertEquals(...
@Override public ExecuteContext before(ExecuteContext context) { Set<String> matchKeys = configService.getMatchKeys(); Set<String> injectTags = configService.getInjectTags(); if (CollectionUtils.isEmpty(matchKeys) && CollectionUtils.isEmpty(injectTags)) { // The staining mark is ...
@Test public void testBefore() { // Test before method interceptor.before(context); RequestTag requestTag = ThreadLocalUtils.getRequestTag(); Map<String, List<String>> header = requestTag.getTag(); Assert.assertNotNull(header); Assert.assertEquals(2, header.size()); ...
public static boolean isNoneBlank(final CharSequence... css) { return !isAnyBlank(css); }
@Test void testIsNoneBlank() { assertFalse(StringUtils.isNoneBlank(null)); assertFalse(StringUtils.isNoneBlank(null, "foo")); assertFalse(StringUtils.isNoneBlank(null, null)); assertFalse(StringUtils.isNoneBlank("", "bar")); assertFalse(StringUtils.isNoneBlank("bob", "")); ...
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException { byte[] bytes = pollEntryBytes(timeout); if (bytes == null) { return null; } return DLQEntry.deserialize(bytes); }
@Test public void testReaderWhenAllRemaningSegmentsAreRemoved() throws IOException, InterruptedException { int remainingEventsInSegment = prepareFilledSegmentFiles(3); try (DeadLetterQueueReader reader = new DeadLetterQueueReader(dir)) { // read the first event to initialize reader stru...
public void setDepth(int depth) { int[] allowedValues = {2, 4, 8, 16, 32, 64, 256, 4096}; for (int allowedValue : allowedValues) { if (depth == allowedValue) { this.depth = depth; userConfigured.add("depth"); return; } } ...
@Test public void testValidateDepth() { TesseractOCRConfig config = new TesseractOCRConfig(); config.setDepth(4); config.setDepth(8); assertTrue(true, "Couldn't set valid values"); assertThrows(IllegalArgumentException.class, () -> { config.setDepth(6); })...
@Override public long readLong(@Nonnull String fieldName) throws IOException { FieldDefinition fd = cd.getField(fieldName); if (fd == null) { return 0L; } switch (fd.getType()) { case LONG: return super.readLong(fieldName); case INT...
@Test(expected = IncompatibleClassChangeError.class) public void testReadLong_IncompatibleClass() throws Exception { reader.readLong("string"); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { var msgDataAsJsonNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null; processFieldsData(ctx, msg, msg.getOriginator(), msgDataAsJsonNode, config.isIgnoreN...
@Test public void givenValidMsgAndFetchToMetaData_whenOnMsg_thenShouldTellSuccessAndFetchToMetaData() throws TbNodeException, ExecutionException, InterruptedException { // GIVEN var device = new Device(); device.setId(DUMMY_DEVICE_ORIGINATOR); device.setName("Test device"); d...
public static UParens create(UExpression expression) { return new AutoValue_UParens(expression); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UParens.create(ULiteral.longLit(5L))) .addEqualityGroup(UParens.create(ULiteral.intLit(5))) .addEqualityGroup(UParens.create(UUnary.create(Kind.UNARY_MINUS, ULiteral.intLit(5)))) .addEqualityGroup( UPar...
@Override public LogicalSchema getSchema() { return schema; }
@Test public void shouldBuildCorrectVarArgAggregateSchema() { // When: final SchemaKStream<?> stream = buildQuery("SELECT col0, var_arg(col0, col1, col2) FROM test1 " + "window TUMBLING (size 2 second) " + "WHERE col0 > 100 GROUP BY col0 EMIT CHANGES;"); // Then: assertThat(st...
public String deserialize(String password, String encryptedPassword, Validatable config) { if (isNotBlank(password) && isNotBlank(encryptedPassword)) { config.addError(PASSWORD, "You may only specify `password` or `encrypted_password`, not both!"); config.addError(ScmMaterialConfig.ENCRY...
@Test public void shouldEncryptClearTextPasswordSentByUser() throws CryptoException { SvnMaterialConfig svnMaterialConfig = svn(); PasswordDeserializer passwordDeserializer = new PasswordDeserializer(); String encrypted = passwordDeserializer.deserialize("password", null, svnMaterialConfig);...
void addFunction(final T function) { final List<ParameterInfo> parameters = function.parameterInfo(); if (allFunctions.put(function.parameters(), function) != null) { throw new KsqlFunctionException( "Can't add function " + function.name() + " with parameters " + function.parameter...
@Test public void shouldThrowOnAddFunctionSameParamsExceptOneVariadic() { // Given: givenFunctions( function(EXPECTED, -1, STRING_VARARGS) ); // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> udfIndex.addFunction(function(EXPECTED, 0...
static List<String> parse(String cmdline) { List<String> matchList = new ArrayList<>(); Matcher shellwordsMatcher = SHELLWORDS_PATTERN.matcher(cmdline); while (shellwordsMatcher.find()) { if (shellwordsMatcher.group(1) != null) { matchList.add(shellwordsMatcher.group(...
@Test void parses_single_quoted_strings() { assertThat(ShellWords.parse("--name 'The Fox'"), is(equalTo(asList("--name", "The Fox")))); }
@Udf public String extractProtocol( @UdfParameter(description = "a valid URL to extract a protocl from") final String input) { return UrlParser.extract(input, URI::getScheme); }
@Test public void shouldExtractProtocolIfPresent() { assertThat( extractUdf.extractProtocol("https://docs.confluent.io/current/ksql/docs/syntax-reference.html#scalar-functions"), equalTo("https")); }