focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public AwsProxyResponse handle(Throwable ex) { log.error("Called exception handler for:", ex); // adding a print stack trace in case we have no appender or we are running inside SAM local, where need the // output to go to the stderr. ex.printStackTrace(); if (ex i...
@Test void streamHandle_InvalidRequestEventException_responseString() throws IOException { ByteArrayOutputStream respStream = new ByteArrayOutputStream(); exceptionHandler.handle(new InvalidRequestEventException(INVALID_REQUEST_MESSAGE, null), respStream); assertNotNull(respStre...
public static ObjectNode convertFromGHResponse(GHResponse ghResponse, TranslationMap translationMap, Locale locale, DistanceConfig distanceConfig) { ObjectNode json = JsonNodeFactory.instance.objectNode(); if (ghResponse.hasErrors()) throw new IllegalStateException( ...
@Test @Disabled public void alternativeRoutesTest() { GHResponse rsp = hopper.route(new GHRequest(42.554851, 1.536198, 42.510071, 1.548128).setProfile(profile) .setAlgorithm(Parameters.Algorithms.ALT_ROUTE)); assertEquals(2, rsp.getAll().size()); ObjectNode json = Navi...
public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); }
@Test public void testValidateValueMismatchArray() { assertThrows(DataException.class, () -> ConnectSchema.validateValue(SchemaBuilder.array(Schema.INT32_SCHEMA).build(), Arrays.asList("a", "b", "c"))); }
@Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { return super.touch(file, status.withChecksum(write.checksum(file, status).compute(new NullInputStream(0L), status))); }
@Test public void testTouchVersioning() throws Exception { final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)); ...
@PostMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId, @RequestParam("namespaceName") String namespaceName, @RequestParam(value = "namesp...
@Test void testCreateNamespaceWithAutoId() throws Exception { assertFalse(namespaceController.createNamespace("", "testName", "testDesc")); verify(namespaceOperationService).createNamespace( matches("[A-Za-z\\d]{8}-[A-Za-z\\d]{4}-[A-Za-z\\d]{4}-[A-Za-z\\d]{4}-[A-Za-z\\d]{12}"), eq("t...
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = ResourceConfigException.class) public void failsOnNonPublicCreateMethod() { @RestLiCollection(name = "nonPublicCreateMethod") class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> { @RestMethod.Create CreateResponse protectedCreate(EmptyRecord ent...
@Deprecated public static DnsServerAddresses defaultAddresses() { return DefaultDnsServerAddressStreamProvider.defaultAddresses(); }
@Test public void testDefaultAddresses() { assertThat(defaultAddressList().size(), is(greaterThan(0))); }
public static java.util.regex.Pattern compilePattern(String expression) { return compilePattern(expression, 0); }
@Test void testCompilePatternInvalid() { assertThrows(PatternSyntaxException.class, () -> JMeterUtils.compilePattern("[missing closing bracket")); }
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); DecimalColumnStatsDataInspector aggregateData = decimalInspectorFromStats(aggregateColStats); Dec...
@Test public void testMergeNonNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(Decimal.class) .low(DECIMAL_1) .high(DECIMAL_1) .numNulls(2) .numDVs(1) .hll(2) .kll(2) .build()); ColumnStatisticsObj newObj = cre...
public static Locale setupRuntimeLocale() { Locale systemDefault = Locale.getDefault(); log.info("System Default Locale: [{}]", systemDefault); // TODO: Review- do we need to store the system default anywhere? // Useful to log the "user.*" properties for debugging... Set<String>...
@Test public void runtimeLocale() { title("runtimeLocale"); Locale runtime = LionUtils.setupRuntimeLocale(); print("locale is [%s]", runtime); // NOTE: // Yeah, I know, "a unit test without asserts is not a unit test". // // But it would NOT be a good ide...
public Result resolve(List<PluginDescriptor> plugins) { // create graphs dependenciesGraph = new DirectedGraph<>(); dependentsGraph = new DirectedGraph<>(); // populate graphs Map<String, PluginDescriptor> pluginByIds = new HashMap<>(); for (PluginDescriptor plugin : plu...
@Test void wrongDependencyVersion() { PluginDescriptor pd1 = new DefaultPluginDescriptor() .setPluginId("p1") // .setDependencies("p2@2.0.0"); // simple version .setDependencies("p2@>=1.5.0 & <1.6.0"); // range version PluginDescriptor pd2 = new DefaultPluginDescr...
public String getName() { return name; }
@Test void testWithoutEndpointContextPath() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); String endpointPort = "9090"; properties.setProperty(PropertyKeyConst.ENDP...
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_handle_background() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: feature name\n" + " Background: background name\n" + " Given first step\n" + " Scenario: s1\n" + " The...
static Result coerceUserList( final Collection<Expression> expressions, final ExpressionTypeManager typeManager ) { return coerceUserList(expressions, typeManager, Collections.emptyMap()); }
@Test public void shouldCoerceToBigIntIfStringNumericTooWideForInt() { // Given: final ImmutableList<Expression> expressions = ImmutableList.of( new IntegerLiteral(10), new StringLiteral("1234567890000") ); // When: final Result result = CoercionUtil.coerceUserList(expressions, ty...
@VisibleForTesting DeletionMeta globalLogCleanup(long size) throws Exception { List<Path> workerDirs = new ArrayList<>(workerLogs.getAllWorkerDirs()); Set<Path> aliveWorkerDirs = workerLogs.getAliveWorkerDirs(); return directoryCleaner.deleteOldestWhileTooLarge(workerDirs, size, false, aliv...
@Test public void testGlobalLogCleanup() throws Exception { long nowMillis = Time.currentTimeMillis(); try (TmpPath testDir = new TmpPath()) { Files.createDirectories(testDir.getFile().toPath()); Path rootDir = createDir(testDir.getFile().toPath(), "workers-artifacts"); ...
public static DateTimeFormatter getShortMillsFormatter() { return SHORT_MILLS; }
@Test void assertGetShortMillsFormatter() { assertThat(DateTimeFormatterFactory.getShortMillsFormatter().parse("1970-01-01 00:00:00.0").toString(), is("{},ISO resolved to 1970-01-01T00:00")); }
public static L3ModificationInstruction modL3Src(IpAddress addr) { checkNotNull(addr, "Src l3 IPv4 address cannot be null"); return new ModIPInstruction(L3SubType.IPV4_SRC, addr); }
@Test public void testModL3SrcMethod() { final Instruction instruction = Instructions.modL3Src(ip41); final L3ModificationInstruction.ModIPInstruction modIPInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, L3Mo...
private void invokeToLeader(final String group, final Message request, final int timeoutMillis, FailoverClosure closure) { try { final Endpoint leaderIp = Optional.ofNullable(getLeader(group)) .orElseThrow(() -> new NoLeaderException(group)).getEndpoint(); ...
@Test void testInvokeToLeader() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, RemotingException, InterruptedException { when(cliClientServiceMock.getRpcClient()).thenReturn(rpcClient); setLeaderAs(peerId1); int timeout = 3000; Method inv...
@Nonnull @Override public CreatedAggregations<AggregationBuilder> doCreateAggregation(Direction direction, String name, Pivot pivot, Time timeSpec, OSGeneratedQueryContext queryContext, Query query) { AggregationBuilder root = null; AggregationBuilder leaf = null; final Interval interval...
@Test public void timeSpecIntervalIsCalculatedOnQueryTimeRangeIfNoPivotTimeRange() throws InvalidRangeParametersException { final ArgumentCaptor<TimeRange> timeRangeCaptor = ArgumentCaptor.forClass(TimeRange.class); when(interval.toDateInterval(timeRangeCaptor.capture())).thenReturn(DateInterval.day...
private void rebalance() { int activeNodes = (int) clusterService.getNodes() .stream() .filter(node -> clusterService.getState(node.id()).isActive()) .count(); int myShare = (int) Math.ceil((double) NUM_PARTITIONS / activeNodes); // First make su...
@Test public void testRebalance() { // We have all the partitions so we'll need to relinquish some setUpLeadershipService(WorkPartitionManager.NUM_PARTITIONS); leadershipService.withdraw(anyString()); expectLastCall().times(7); replay(leadershipService); partitionM...
@Override public Map<K, V> getCachedMap() { return localCacheView.getCachedMap(); }
@Test public void testSizeCache() { RLocalCachedMap<String, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test")); Map<String, Integer> cache = map.getCachedMap(); map.put("12", 1); map.put("14", 2); map.put("15", 3); assertThat(cache...
static String getAbbreviation(Exception ex, Integer statusCode, String storageErrorMessage) { String result = null; for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) { final String abbreviation = retryReasonCategory.captureAndGetAbbreviation(ex, statusC...
@Test public void testConnectionTimeoutRetryReason() { SocketTimeoutException connectionTimeoutException = new SocketTimeoutException(CONNECTION_TIMEOUT_JDK_MESSAGE); Assertions.assertThat(RetryReason.getAbbreviation(connectionTimeoutException, null, null)).isEqualTo( CONNECTION_TIMEOUT_ABBREVIATION ...
@Override @SuppressWarnings("rawtypes") public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String,...
@Test public void sendsMetricAttributesAsTagsIfEnabled() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); getReporterThatSendsMetricAttributesAsTags().report(map(), map("counter", counter), map(), ...
public static CatalogTable buildWithConfig(Config config) { ReadonlyConfig readonlyConfig = ReadonlyConfig.fromConfig(config); return buildWithConfig(readonlyConfig); }
@Test public void testDefaultTablePath() throws FileNotFoundException, URISyntaxException { String path = getTestConfigFile("/conf/default_tablepath.conf"); Config config = ConfigFactory.parseFile(new File(path)); Config source = config.getConfigList("source").get(0); ReadonlyConfig ...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertChar() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("bpchar") .dataType("bpchar") .build(); Column column = Postg...
@Override public void finished(boolean allStepsExecuted) { if (postProjectAnalysisTasks.length == 0) { return; } ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED); for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) { ...
@Test @UseDataProvider("booleanValues") public void logStatistics_add_fails_with_IAE_if_same_key_with_exact_case_added_twice(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); PostProjectAnalysisTask.LogStatistics log...
public Bson parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) { final Filter filter = singleFilterParser.parseSingleExpression(filterExpression, attributes); return filter.toBson(); }
@Test void parsesFilterExpressionCorrectlyForDateRanges() { final String fromString = "2012-12-12 12:12:12"; final String toString = "2022-12-12 12:12:12"; final List<EntityAttribute> entityAttributes = List.of(EntityAttribute.builder() .id("created_at") .tit...
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = ResourceConfigException.class) public void failsOnInvalidActionReturnType() { @RestLiCollection(name = "invalidReturnType") class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> { @Action(name = "invalidReturnType") public Object invalidReturnType(@Acti...
@Override public PinotDataBuffer newBuffer(String column, IndexType<?, ?, ?> type, long sizeBytes) throws IOException { return allocNewBufferInternal(column, type, sizeBytes, type.getId().toLowerCase() + ".create"); }
@Test(expectedExceptions = RuntimeException.class) public void testWriteExisting() throws Exception { try (SingleFileIndexDirectory columnDirectory = new SingleFileIndexDirectory(TEMP_DIR, _segmentMetadata, ReadMode.mmap)) { columnDirectory.newBuffer("column1", StandardIndexes.dictionary(), 10...
public static ValueReference ofNullable(@Nullable String value) { if (value == null) { return null; } else { return of(value); } }
@Test public void testOfNullable() { assertThat(ValueReference.ofNullable("test")).isNotNull(); assertThat(ValueReference.ofNullable((String) null)).isNull(); assertThat(ValueReference.ofNullable(TestEnum.A)).isNotNull(); assertThat(ValueReference.ofNullable((TestEnum) null)).isNull(...
@ApiOperation(value = "Get a single group", tags = { "Groups" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the group exists and is returned."), @ApiResponse(code = 404, message = "Indicates the requested group does not exist.") }) @GetMapping(value = "/ide...
@Test public void testGetGroup() throws Exception { try { Group testGroup = identityService.newGroup("testgroup"); testGroup.setName("Test group"); testGroup.setType("Test type"); identityService.saveGroup(testGroup); CloseableHttpResponse respons...
public static String relativize(String root, final String path) { if(StringUtils.isBlank(root)) { return path; } if(StringUtils.equals(root, path)) { return StringUtils.EMPTY; } if(!StringUtils.equals(root, String.valueOf(Path.DELIMITER))) { if...
@Test public void testRelativize() { assertEquals("", PathRelativizer.relativize("/r", "/r")); assertEquals("/", PathRelativizer.relativize("/r", "/r//")); assertEquals("a", PathRelativizer.relativize("/", "/a")); assertEquals("/b/path", PathRelativizer.relativize("/a", "/b/path")); ...
EventLoopGroup getSharedOrCreateEventLoopGroup(EventLoopGroup eventLoopGroupShared) { if (eventLoopGroupShared != null) { return eventLoopGroupShared; } return this.eventLoopGroup = new NioEventLoopGroup(); }
@Test public void givenSharedEventLoop_whenGetEventLoop_ThenReturnShared() { eventLoop = mock(EventLoopGroup.class); assertThat(client.getSharedOrCreateEventLoopGroup(eventLoop), is(eventLoop)); }
@ScalarOperator(CAST) @LiteralParameters("x") @SqlType("varchar(x)") public static Slice castToVarchar(@SqlType(StandardTypes.DOUBLE) double value) { return utf8Slice(String.valueOf(value)); }
@Test public void testCastToVarchar() { assertFunction("cast(37.7E0 as varchar)", VARCHAR, "37.7"); assertFunction("cast(17.1E0 as varchar)", VARCHAR, "17.1"); }
@Override public String render(String text) { if (StringUtils.isBlank(text)) { return ""; } if (regex.isEmpty() || link.isEmpty()) { Comment comment = new Comment(); comment.escapeAndAdd(text); return comment.render(); } try { ...
@Test public void shouldEscapeDynamicLink() { String link = "http://jira.example.com/${ID}"; String regex = "^ABC-[^ ]+"; trackingTool = new DefaultCommentRenderer(link, regex); String result = trackingTool.render("ABC-\"><svg/onload=\"alert(1)"); assertThat(result, ...
public StructuralByteArray(byte[] value) { this.value = value; }
@Test public void testStructuralByteArray() throws Exception { assertEquals( new StructuralByteArray("test string".getBytes(StandardCharsets.UTF_8)), new StructuralByteArray("test string".getBytes(StandardCharsets.UTF_8))); assertFalse( new StructuralByteArray("test string".getBytes(St...
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KST...
@Test public void shouldReplaceTableSourceV2WithMatchingPseudoColumnVersion() { // Given: givenNonWindowedTable(); givenExistingQueryWithOldPseudoColumnVersion(tableSource); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSource, ...
public int floor(T v) { return Boundary.FLOOR.apply(find(v)); }
@Test public void testFloor() { assertEquals(-1, l.floor("A")); assertEquals(0, l.floor("B")); assertEquals(0, l.floor("C")); assertEquals(1, l.floor("D")); assertEquals(1, l.floor("E")); assertEquals(2, l.floor("F")); assertEquals(2, l.floor("G")); }
public ClientAuth getClientAuth() { String clientAuth = getString(SSL_CLIENT_AUTHENTICATION_CONFIG); if (originals().containsKey(SSL_CLIENT_AUTH_CONFIG)) { if (originals().containsKey(SSL_CLIENT_AUTHENTICATION_CONFIG)) { log.warn( "The {} configuration is deprecated. Since a value has...
@Test public void shouldResolveClientAuthenticationRequest() { // Given: final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder() .put(KsqlRestConfig.SSL_CLIENT_AUTHENTICATION_CONFIG, KsqlRestConfig.SSL_CLIENT_AUTHENTICATION_REQUESTED) .build() );...
@Override public Set<byte[]> zDiff(byte[]... sets) { List<Object> args = new ArrayList<>(sets.length + 1); args.add(sets.length); args.addAll(Arrays.asList(sets)); return write(sets[0], ByteArrayCodec.INSTANCE, ZDIFF, args.toArray()); }
@Test public void testZDiff() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boun...
public boolean setResolution(DefaultIssue issue, @Nullable String resolution, IssueChangeContext context) { if (!Objects.equals(resolution, issue.resolution())) { issue.setFieldChange(context, RESOLUTION, issue.resolution(), resolution); issue.setResolution(resolution); issue.setUpdateDate(context...
@Test void not_change_resolution() { issue.setResolution(Issue.RESOLUTION_FIXED); boolean updated = underTest.setResolution(issue, Issue.RESOLUTION_FIXED, context); assertThat(updated).isFalse(); assertThat(issue.resolution()).isEqualTo(Issue.RESOLUTION_FIXED); assertThat(issue.currentChange()).is...
@Override public SQLParserRuleConfiguration swapToObject(final YamlSQLParserRuleConfiguration yamlConfig) { CacheOption parseTreeCacheOption = null == yamlConfig.getParseTreeCache() ? DefaultSQLParserRuleConfigurationBuilder.PARSE_TREE_CACHE_OPTION : cacheOptionSwapper.swapTo...
@Test void assertSwapToObjectWithDefaultConfig() { YamlSQLParserRuleConfiguration yamlConfig = new YamlSQLParserRuleConfiguration(); SQLParserRuleConfiguration actual = new YamlSQLParserRuleConfigurationSwapper().swapToObject(yamlConfig); assertThat(actual.getParseTreeCache().getInitialCapac...
public static <T> CompletableFuture<T> addTimeoutHandling(CompletableFuture<T> future, Duration timeout, ScheduledExecutorService executor, Supplier<Throwable> exceptionSupplier) { ScheduledFuture<?> scheduledFuture = ...
@Test public void testTimeoutHandlingNoTimeout() throws ExecutionException, InterruptedException { CompletableFuture<Void> future = new CompletableFuture<>(); @Cleanup("shutdownNow") ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); FutureUtil.addTimeoutHandlin...
@Override public void resetLocal() { this.min = Integer.MAX_VALUE; }
@Test void testResetLocal() { IntMinimum min = new IntMinimum(); int value = 13; min.add(value); assertThat(min.getLocalValue().intValue()).isEqualTo(value); min.resetLocal(); assertThat(min.getLocalValue().intValue()).isEqualTo(Integer.MAX_VALUE); }
public String name() { return name; }
@Test void nameCannotContainSpaces() { Assertions.assertThrows(IllegalArgumentException.class, () -> DefaultBot.getDefaultBuilder().name("test test").build()); }
@Bean public BulkheadRegistry bulkheadRegistry( BulkheadConfigurationProperties bulkheadConfigurationProperties, EventConsumerRegistry<BulkheadEvent> bulkheadEventConsumerRegistry, RegistryEventConsumer<Bulkhead> bulkheadRegistryEventConsumer, @Qualifier("compositeBulkheadCustomizer"...
@Test public void testCreateBulkHeadRegistryWithSharedConfigs() { //Given io.github.resilience4j.common.bulkhead.configuration.CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new io.github.resilience4j.common.bulkhead.configuration.CommonBulkheadConfigurationProperties.I...
public Transfer create(final CommandLine input, final Host host, final Path remote, final List<TransferItem> items) throws BackgroundException { final Transfer transfer; final TerminalAction type = TerminalActionFinder.get(input); if(null == type) { throw new BackgroundEx...
@Test public void testFilter() throws Exception { final CommandLineParser parser = new PosixParser(); final Transfer transfer = new TerminalTransferFactory().create(parser.parse(TerminalOptionsBuilder.options(), new String[]{"--download", "rackspace://cdn.cyberduck.ch/remote/*.css"}), ...
public static Formatter forNumbers(@Nonnull String format) { return new NumberFormat(format); }
@Test public void testRounding() { Formatter f = forNumbers("FM0.9"); check(0.15, f, "0.2"); f = forNumbers("FM.99"); check(0.015, f, ".02"); f = forNumbers("FM99"); check(9.9, f, "10"); }
@VisibleForTesting Path stringToPath(String s) { try { URI uri = new URI(s); return new Path(uri.getScheme(), uri.getAuthority(), uri.getPath()); } catch (URISyntaxException e) { throw new IllegalArgumentException( "Error parsing argument." + " Argument must be a valid URI: " + s, ...
@Test public void testStringToPath() throws IOException { Configuration conf = new Configuration(); JobResourceUploader uploader = new JobResourceUploader(FileSystem.getLocal(conf), false); Assert.assertEquals("Failed: absolute, no scheme, with fragment", "/testWithFragment.txt", ...
public static boolean isNotNull(Object value) { return value != null; }
@SuppressWarnings({"ConstantConditions", "SimplifiableJUnitAssertion"}) @Test public void isNotNull() { assertEquals(true, TernaryLogic.isNotNull(false)); assertEquals(true, TernaryLogic.isNotNull(true)); assertEquals(false, TernaryLogic.isNotNull(null)); assertEquals(true, Terna...
static KiePMMLFieldColumnPair getKiePMMLFieldColumnPair(final FieldColumnPair fieldColumnPair) { return new KiePMMLFieldColumnPair(fieldColumnPair.getField(), getKiePMMLExtensions(fieldColumnPair.getExtensions()), fieldColumnPai...
@Test void getKiePMMLFieldColumnPair() { final FieldColumnPair toConvert = getRandomFieldColumnPair(); final KiePMMLFieldColumnPair retrieved = KiePMMLFieldColumnPairInstanceFactory.getKiePMMLFieldColumnPair(toConvert); commonVerifyKiePMMLFieldColumnPair(retrieved, toConvert); }
public void setOuterJoinType(OuterJoinType outerJoinType) { this.outerJoinType = outerJoinType; }
@Test void testFullOuterJoinWithEmptyLeftInput() throws Exception { final List<String> leftInput = Collections.emptyList(); final List<String> rightInput = Arrays.asList("foo", "bar", "foobar"); baseOperator.setOuterJoinType(OuterJoinOperatorBase.OuterJoinType.FULL); List<String> exp...
public Response downloadLogFile(String host, String fileName, String user) throws IOException { workerLogs.setLogFilePermission(fileName); return logFileDownloadHelper.downloadFile(host, fileName, user, false); }
@Test public void testDownloadLogFileTraversal() throws IOException { try (TmpPath rootPath = new TmpPath()) { LogviewerLogDownloadHandler handler = createHandlerTraversalTests(rootPath.getFile().toPath()); Response topoAResponse = handler.downloadLogFile("host","../nimbus.log", "u...
@SuppressWarnings("WeakerAccess") public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) { final Map<String, Object> consumerProps = getCommonConsumerConfigs(); // Get main consumer override configs final Map<String, Object> mainC...
@Test public void shouldNotSetInternalThrowOnFetchStableOffsetUnsupportedConfigToFalseInConsumerForEosV2() { props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, EXACTLY_ONCE_V2); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> consumerConfigs = stream...
protected static int castToIntSafely(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return Long.valueOf(value).intValue(); }
@Test void testCastToIntSafely() { assertEquals(0, Resource.castToIntSafely(0)); assertEquals(1, Resource.castToIntSafely(1)); assertEquals(Integer.MAX_VALUE, Resource.castToIntSafely(Integer.MAX_VALUE)); assertEquals(Integer.MAX_VALUE, Resource.castToIntSafely(Integer.MAX_VALUE + 1L)...
@Bean("CiConfiguration") public CiConfiguration provide(Configuration configuration, CiVendor[] ciVendors) { boolean disabled = configuration.getBoolean(PROP_DISABLED).orElse(false); if (disabled) { return new EmptyCiConfiguration(); } List<CiVendor> detectedVendors = Arrays.stream(ciVendors) ...
@Test public void configuration_defined_by_ci_vendor() { CiConfiguration ciConfiguration = underTest.provide(cli.asConfig(), new CiVendor[]{new DisabledCiVendor("vendor1"), new EnabledCiVendor("vendor2")}); assertThat(ciConfiguration.getScmRevision()).hasValue(EnabledCiVendor.SHA); }
GroupFilter groupFilter() { return getConfiguredInstance(GROUP_FILTER_CLASS, GroupFilter.class); }
@Test public void testGroupMatching() { MirrorCheckpointConfig config = new MirrorCheckpointConfig(makeProps("groups", "group1")); assertTrue(config.groupFilter().shouldReplicateGroup("group1"), "topic1 group matching property configuration failed"); assertFalse(config.groupF...
public static HostRestrictingAuthorizationFilter initializeState(Configuration conf) { String confName = HostRestrictingAuthorizationFilter.HDFS_CONFIG_PREFIX + HostRestrictingAuthorizationFilter.RESTRICTION_CONFIG; String confValue = conf.get(confName); // simply pass a blank value if we do not h...
@Test public void testMultipleAcceptedGETsOneChannel() { Configuration conf = new Configuration(); conf.set(CONFNAME, "*,*,/allowed"); HostRestrictingAuthorizationFilter filter = HostRestrictingAuthorizationFilterHandler.initializeState(conf); EmbeddedChannel channel = new CustomEmbeddedChanne...
public final AccessControlEntry entry() { return entry; }
@Test public void shouldThrowOnMatchPatternType() { assertThrows(IllegalArgumentException.class, () -> new AclBinding(new ResourcePattern(ResourceType.TOPIC, "foo", PatternType.MATCH), ACL1.entry())); }
public static DynamicVoters parse(String input) { input = input.trim(); List<DynamicVoter> voters = new ArrayList<>(); for (String voterString : input.split(",")) { if (!voterString.isEmpty()) { voters.add(DynamicVoter.parse(voterString)); } } ...
@Test public void testParsingSingleDynamicVoter() { assertEquals(new DynamicVoters(Arrays.asList( new DynamicVoter( Uuid.fromString("K90IZ-0DRNazJ49kCZ1EMQ"), 2, "localhost", (short) 8020))), DynamicVoters.parse("2@local...
public static ParamType getVarArgsSchemaFromType(final Type type) { return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE); }
@Test public void shouldGetPartialGenericFunctionVariadic() throws NoSuchMethodException { // Given: final Type genericType = getClass().getMethod("partialGenericFunctionType").getGenericReturnType(); // When: final ParamType returnType = UdfUtil.getVarArgsSchemaFromType(genericType); // Then: ...
static byte[] deriveEnc(byte[] seed, int offset, int length) { final MessageDigest md = DigestUtils.digest("SHA1"); md.update(seed, offset, length); md.update(new byte[] {0, 0, 0, 1}); return Arrays.copyOfRange(md.digest(), 0, 16); }
@Test public void shouldDeriveEncryptionKey() { assertEquals( "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", ByteArrayUtils.prettyHex(TDEASecureMessaging.deriveEnc( Hex.decode("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"),0, 16) ) ); }
@Override public Name getLocation(final Path file) throws BackgroundException { final Path container = containerService.getContainer(file); if(container.isRoot()) { return unknown; } if(cache.containsKey(container)) { return cache.get(container); } ...
@Test public void testFindLocation() throws Exception { assertEquals(new SwiftLocationFeature.SwiftRegion("IAD"), new SwiftLocationFeature(session).getLocation( new Path("cdn.duck.sh", EnumSet.of(Path.Type.volume, Path.Type.directory)))); assertEquals(unknown, new SwiftLocationFeature(se...
@Deprecated public static String updateSerializedOptions( String serializedOptions, Map<String, String> runtimeValues) { ObjectNode root, options; try { root = PipelineOptionsFactory.MAPPER.readValue(serializedOptions, ObjectNode.class); options = (ObjectNode) root.get("options"); chec...
@Test public void testUpdateSerialize() throws Exception { TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); String serializedOptions = MAPPER.writeValueAsString(submitOptions); String updatedOptions = ValueProviders.updateSerializedOptions(serializedOptions, ImmutableMap.o...
@Override public void childEntriesWillBecomeVisible(final Entry submenu) { UserRole userRole = currentUserRole(); childEntriesWillBecomeVisible(submenu, userRole); }
@Test public void dontActivateSelectOnPopup_forNotCheckSelectionOnPopup() { Entry menuEntry = new Entry(); Entry actionEntry = new Entry(); menuEntry.addChild(actionEntry); final AFreeplaneAction someAction = Mockito.mock(AFreeplaneAction.class); when(someAction.checkSelectionOnPopup()).thenReturn(false); ...
@Override @SuppressWarnings("unchecked") public synchronized boolean addAll(Collection<? extends E> c) { if (c instanceof BitList) { rootSet.or(((BitList<? extends E>) c).rootSet); if (((BitList<? extends E>) c).hasMoreElementInTailList()) { for (E e : ((BitList<?...
@Test void testAddAll() { List<String> list = Arrays.asList("A", "B", "C"); BitList<String> bitList1 = new BitList<>(list); BitList<String> bitList2 = new BitList<>(list); bitList1.removeAll(list); Assertions.assertEquals(0, bitList1.size()); bitList1.addAll(bitList...
@Override public boolean accept(final Path file, final Local local, final TransferStatus parent) throws BackgroundException { if(super.accept(file, local, parent)) { if(local.isFile()) { if(parent.isExists()) { if(find.find(file)) { fin...
@Test public void testAccept() throws Exception { final ResumeFilter f = new ResumeFilter(new DisabledUploadSymlinkResolver(), new NullSession(new Host(new TestProtocol()))); assertTrue(f.accept(new Path("t", EnumSet.of(Path.Type.file)), new NullLocal("a") { @Override public ...
public static Path copyContent(Path src, Path target, CopyOption... options) throws IORuntimeException { Assert.notNull(src, "Src path must be not null !"); Assert.notNull(target, "Target path must be not null !"); try { Files.walkFileTree(src, new CopyVisitor(src, target, options)); } catch (IOException e)...
@Test @Disabled public void copyContentTest(){ PathUtil.copyContent( Paths.get("d:/Red2_LYY"), Paths.get("d:/test/aaa/") ); }
@Override public void execute(MigrationStatusListener listener) { MigrationContainer migrationContainer = new MigrationContainerImpl(serverContainer, MigrationStepsExecutorImpl.class); try { MigrationStepsExecutor stepsExecutor = migrationContainer.getComponentByType(MigrationStepsExecutor.class); ...
@Test void execute_execute_steps_from_last_migration_number_plus_1() { when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.of(50L)); List<RegisteredMigrationStep> steps = singletonList(new RegisteredMigrationStep(1, "doo", TestMigrationStep.class)); when(migrationSteps.readFrom(51)).thenRe...
@Override public void write(final PostgreSQLPacketPayload payload, final Object value) { throw new UnsupportedSQLOperationException("PostgreSQLStringArrayBinaryProtocolValue.write()"); }
@Test void assertWrite() { assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().write(new PostgreSQLPacketPayload(null, StandardCharsets.UTF_8), "val")); }
public static Collection<SubquerySegment> getSubquerySegments(final SelectStatement selectStatement) { List<SubquerySegment> result = new LinkedList<>(); extractSubquerySegments(result, selectStatement); return result; }
@Test void assertGetSubquerySegmentsInProjection() { ColumnSegment left = new ColumnSegment(41, 48, new IdentifierValue("order_id")); ColumnSegment right = new ColumnSegment(52, 62, new IdentifierValue("order_id")); SelectStatement subquerySelectStatement = mock(SelectStatement.class); ...
public static void boundsCheck(int capacity, int index, int length) { if (capacity < 0 || index < 0 || length < 0 || (index > (capacity - length))) { throw new IndexOutOfBoundsException(String.format("index=%d, length=%d, capacity=%d", index, length, capacity)); } }
@Test(expected = IndexOutOfBoundsException.class) public void boundsCheck_whenMoreThanCapacity() { ArrayUtils.boundsCheck(100, 0, 110); }
public static String trim(final String str, final char ch) { if (isEmpty(str)) { return null; } final char[] chars = str.toCharArray(); int i = 0, j = chars.length - 1; // noinspection StatementWithEmptyBody for (; i < chars.length && chars[i] == ch; i++) { ...
@Test public void testTrim() { assertEquals(StringUtil.trim("aaabcdefaaa", 'a'), "bcdef"); assertEquals(StringUtil.trim("bcdef", 'a'), "bcdef"); assertEquals(StringUtil.trim("abcdef", 'a'), "bcdef"); assertEquals(StringUtil.trim("abcdef", 'f'), "abcde"); }
@ApiOperation(value = "Create Or update Tenant Profile (saveTenantProfile)", notes = "Create or update the Tenant Profile. When creating tenant profile, platform generates Tenant Profile Id as " + UUID_WIKI_LINK + "The newly created Tenant Profile Id will be present in the response. " + ...
@Test public void testSaveTenantProfile() throws Exception { loginSysAdmin(); Mockito.reset(tbClusterService); TenantProfile tenantProfile = this.createTenantProfile("Tenant Profile"); TenantProfile savedTenantProfile = doPost("/api/tenantProfile", tenantProfile, TenantProfile.clas...
@Override public void unsubscribe() { acquireAndEnsureOpen(); try { fetchBuffer.retainAll(Collections.emptySet()); Timer timer = time.timer(Long.MAX_VALUE); UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer)); applicati...
@Test void testReaperInvokedInUnsubscribe() { consumer = newConsumer(); completeUnsubscribeApplicationEventSuccessfully(); consumer.unsubscribe(); verify(backgroundEventReaper).reap(time.milliseconds()); }
@Override public int choosePartition(Message<?> msg, TopicMetadata metadata) { // If the message has a key, it supersedes the single partition routing policy if (msg.hasKey()) { return signSafeMod(hash.makeHash(msg.getKey()), metadata.numPartitions()); } return partition...
@Test public void testChoosePartitionWithoutKey() { Message<?> msg = mock(Message.class); when(msg.getKey()).thenReturn(null); SinglePartitionMessageRouterImpl router = new SinglePartitionMessageRouterImpl(1234, HashingScheme.JavaStringHash); assertEquals(1234, router.choosePartitio...
public static String fromParts(String... parts) { return fromPartsAndSeparator(ID_SEPARATOR, parts); }
@Test void fromParts() { String id = IdUtils.fromParts("namespace", "flow"); assertThat(id, notNullValue()); assertThat(id, is("namespace_flow")); String idWithNull = IdUtils.fromParts(null, "namespace", "flow"); assertThat(idWithNull, notNullValue()); assertThat(idW...
public static long parseLong(String number) { if (StrUtil.isBlank(number)) { return 0L; } if (number.startsWith("0x")) { // 0x04表示16进制数 return Long.parseLong(number.substring(2), 16); } try { return Long.parseLong(number); } catch (NumberFormatException e) { return parseNumber(number).longV...
@Test public void parseLongTest2() { // -------------------------- Parse failed ----------------------- final Long v1 = NumberUtil.parseLong(null, null); assertNull(v1); final Long v2 = NumberUtil.parseLong(StrUtil.EMPTY, null); assertNull(v2); final Long v3 = NumberUtil.parseLong("L3221", 1233L); as...
@Override public KTable<K, VOut> aggregate(final Initializer<VOut> initializer, final Materialized<K, VOut, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(initializer, NamedInternal.empty(), materialized); }
@Test public void shouldNotHaveNullNamedOnAggregateWithMateriazlied() { assertThrows(NullPointerException.class, () -> cogroupedStream.aggregate(STRING_INITIALIZER, null, Materialized.as("store"))); }
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldParseTerminateStatement() { // When: List<CommandParser.ParsedCommand> commands = parse("terminate some_query_id;"); // Then: assertThat(commands.size(), is(1)); assertThat(commands.get(0).getStatement().isPresent(), is (false)); assertThat(commands.get(0).getCommand()...
public static int indexOfNonWhiteSpace(CharSequence seq, int offset) { for (; offset < seq.length(); ++offset) { if (!Character.isWhitespace(seq.charAt(offset))) { return offset; } } return -1; }
@Test public void testIndexOfNonWhiteSpace() { assertEquals(-1, indexOfNonWhiteSpace("", 0)); assertEquals(-1, indexOfNonWhiteSpace(" ", 0)); assertEquals(-1, indexOfNonWhiteSpace(" \t", 0)); assertEquals(-1, indexOfNonWhiteSpace(" \t\r\n", 0)); assertEquals(2, indexOfNonWhit...
@SuppressWarnings("unchecked") public E lookup(final int key) { @DoNotSub int size = this.size; final int[] keys = this.keys; final Object[] values = this.values; for (@DoNotSub int i = 0; i < size; i++) { if (key == keys[i]) { fin...
@Test void shouldSupportKeyOfZero() { final AutoCloseable actual = cache.lookup(0); assertSame(lastValue, actual); assertNotNull(lastValue); }
@Override public String getRmAppPageUrlBase(ApplicationId appId) throws IOException, YarnException { SubClusterId scid = federationFacade.getApplicationHomeSubCluster(appId); createSubclusterIfAbsent(scid); SubClusterInfo subClusterInfo = subClusters.get(scid).getLeft(); String scheme = WebAppU...
@Test public void testGetRmAppPageUrlBase() throws IOException, YarnException { testHelper(true); String scheme = WebAppUtils.getHttpSchemePrefix(conf); Assert.assertEquals(fetcher.getRmAppPageUrlBase(appId1), StringHelper.pjoin(scheme + clusterInfo1.getRMWebServiceAddress(), "cluster", "app")); ...
static PiPreEntry translate(Group group, PiPipeconf pipeconf, Device device) throws PiTranslationException { checkNotNull(group); final List<OutputInstruction> outInstructions = Lists.newArrayList(); int truncateMaxLen = PiCloneSessionEntry.DO_NOT_TRUNCATE; for (GroupBucket...
@Test public void testInvalidPreGroups() { try { PiReplicationGroupTranslatorImpl .translate(INVALID_ALL_GROUP, null, null); Assert.fail("Did not get expected exception."); } catch (PiTranslationException ex) { Assert.assertEquals("support only...
public boolean isPresent(final UUID accountUuid, final byte deviceId) { return checkPresenceTimer.record(() -> presenceCluster.withCluster(connection -> connection.sync().exists(getPresenceKey(accountUuid, deviceId))) == 1); }
@Test void testIsPresent() { final UUID accountUuid = UUID.randomUUID(); final byte deviceId = 1; assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId)); clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP); assertTrue(clientPresenceManager.isPresent(accountUuid, deviceId)...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsNoneOf_primitiveFloatArray_failure() { expectFailureWhenTestingThat(array(1.1f, 2.2f, 3.3f)) .usingExactEquality() .containsNoneOf(array(99.99f, 2.2f)); assertFailureKeys( "value of", "expected not to contain any of", "testin...
public static boolean hasDirectChild(Element parent, String namespace, String tag) { NodeList children = parent.getElementsByTagNameNS(namespace, tag); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE && child.getP...
@Test void hasDirectChild() { assertTrue(XmlUtil.hasDirectChild(parent, "http://example.com", "child")); assertFalse(XmlUtil.hasDirectChild(parent, "http://example.com", "nonExistentChild")); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { return new MantaObjectAttributeAdapter(session) .toAttributes(session.g...
@Test public void testFindFile() throws Exception { final Path file = randomFile(); new MantaTouchFeature(session).touch(file, new TransferStatus().withMime("x-application/cyberduck")); final PathAttributes attributes = new MantaAttributesFinderFeature(session).find(file); assertNotN...
public static String truncateMessageLineLength(Object message) { return truncateMessageLineLength(message, MAX_TRUNCATED_LENGTH); }
@Test public void truncateSpecificLength() throws Exception { String s = CommonUtils.randomAlphaNumString(LogUtils.MAX_TRUNCATED_LENGTH); for (int length = 1; length < LogUtils.MAX_TRUNCATED_LENGTH; length++) { String truncated = LogUtils.truncateMessageLineLength(s, length); assertTrue(truncated...
public <T> void postForm(String url, Header header, Query query, Map<String, String> bodyValues, Type responseType, Callback<T> callback) { execute(url, HttpMethod.POST, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues), ...
@Test void testPostForm() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.postForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback); verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));...
public static String toJson(final Object obj, boolean prettyFormat) { return JSON.toJSONString(obj, prettyFormat); }
@Test public void testToJson_prettyString() { RemotingSerializable serializable = new RemotingSerializable() { private List<String> stringList = Arrays.asList("a", "o", "e", "i", "u", "v"); public List<String> getStringList() { return stringList; } ...
@Override public UpdateNodeResourceResponse updateNodeResource(UpdateNodeResourceRequest request) throws YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrUpdateNodeResourceFailedRetrieved(); RouterServerUtil.logAndThrowException("Missing Updat...
@Test public void testUpdateNodeResourceEmptyRequest() throws Exception { // null request1. LambdaTestUtils.intercept(YarnException.class, "Missing UpdateNodeResource request.", () -> interceptor.updateNodeResource(null)); // null request2. Map<NodeId, ResourceOption> nodeResourceMap = new Ha...
public boolean downloadIfNecessary(final DownloadableFile downloadableFile) { boolean updated = false; boolean downloaded = false; while (!updated) try { fetchUpdateCheckHeaders(downloadableFile); if (downloadableFile.doesNotExist() || !downloadableFile.isChecksumEquals(g...
@Test public void shouldReturnTrueIfTheFileIsDownloaded() { ServerBinaryDownloader downloader = new ServerBinaryDownloader(new GoAgentServerHttpClientBuilder(null, SslVerificationMode.NONE, null, null, null), ServerUrlGeneratorMother.generatorFor("localhost", server.getPort())); assertThat(downloade...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } final Region region = regionService.lookup(file); try { if(containerService.isContainer(f...
@Test public void testFindRoot() throws Exception { final SwiftAttributesFinderFeature f = new SwiftAttributesFinderFeature(session); assertEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.directory)))); }
@Override public PageResult<DiyTemplateDO> getDiyTemplatePage(DiyTemplatePageReqVO pageReqVO) { return diyTemplateMapper.selectPage(pageReqVO); }
@Test @Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解 public void testGetDiyTemplatePage() { // mock 数据 DiyTemplateDO dbDiyTemplate = randomPojo(DiyTemplateDO.class, o -> { // 等会查询到 o.setName(null); o.setUsed(null); o.setUsedTime(null); o.setRe...
@Override public Map<String, String> properties() { return Collections.unmodifiableMap(systemPropertiesConfigParser.parse(systemPropertiesProvider.get())); }
@Test public void testNonStringSystemPropertyValue() { String key = getClass().getSimpleName(); systemProperties.put(key, true); assertNull(provider.properties().get(key)); }
public void updateInstanceMetadata(Service service, String metadataId, InstanceMetadata instanceMetadata) { instanceMetadataMap.computeIfAbsent(service, k -> new ConcurrentHashMap<>(INITIAL_CAPACITY)).put(metadataId, instanceMetadata); }
@Test void testUpdateInstanceMetadata() throws NoSuchFieldException, IllegalAccessException { InstanceMetadata instanceMetadata = new InstanceMetadata(); Class<InstanceMetadata> instanceMetadataClass = InstanceMetadata.class; Field enabled = instanceMetadataClass.getDeclaredField("enabled");...
@Override public boolean equals(Object other) { return other instanceof SourceAndTarget && toString().equals(other.toString()); }
@Test public void testEquals() { SourceAndTarget sourceAndTarget = new SourceAndTarget("source", "target"); SourceAndTarget sourceAndTarget2 = new SourceAndTarget("source", "target"); SourceAndTarget sourceAndTarget3 = new SourceAndTarget("error-source", "target"); assertEquals(sourc...
@Override public void setPreparedStatementValue( DatabaseMeta databaseMeta, PreparedStatement preparedStatement, int index, Object data ) throws KettleDatabaseException { try { if ( data != null ) { preparedStatement.setTimestamp( index, getTimestamp( data )...
@Test public void testSetPreparedStatementValue() throws Exception { ValueMetaTimestamp vm = new ValueMetaTimestamp(); PreparedStatement ps = mock( PreparedStatement.class ); doAnswer( (Answer<Object>) invocationOnMock -> { Object ts = invocationOnMock.getArguments()[ 1 ]; return ts.toString()...
public static SubscriptionData build(final String topic, final String subString, final String type) throws Exception { if (ExpressionType.TAG.equals(type) || type == null) { return buildSubscriptionData(topic, subString); } if (StringUtils.isEmpty(subString)) { t...
@Test public void testBuildSQL() { try { SubscriptionData subscriptionData = FilterAPI.build( "TOPIC", "a is not null", ExpressionType.SQL92 ); assertThat(subscriptionData).isNotNull(); assertThat(subscriptionData.getTopic()).isEqualTo("TO...