focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean hasErrors() { for (ConfigurationProperty property : this) { if (property.hasErrors()) { return true; } } return false; }
@Test void hasErrorsShouldVerifyIfAnyConfigurationPropertyHasErrors() { ConfigurationProperty outputDirectory = mock(ConfigurationProperty.class); ConfigurationProperty inputDirectory = mock(ConfigurationProperty.class); when(outputDirectory.hasErrors()).thenReturn(false); when(inpu...
@Override public void handlerRule(final RuleData ruleData) { Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> { final ModifyResponseRuleHandle modifyResponseRuleHandle = GsonUtils.getInstance().fromJson(s, ModifyResponseRuleHandle.class); CACHED_HANDLE.get().cachedHandle(Cach...
@Test public void handlerSelectorTest() { modifyResponsePluginDataHandler.handlerRule(ruleData); ModifyResponseRuleHandle modifyResponseRuleHandle = ModifyResponsePluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(ruleData)); assertEquals(400, modifyResponseRuleHand...
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testEmptyTopBundlesLoadData() { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); var ctx = getContext(); var brokerLoadDataStore = ctx.brokerLoadDataStore(); brokerLoadDataStore.pushAsync("broker1:...
public static String getSourceIpForHttpRequest(HttpServletRequest httpServletRequest) { String sourceIp = getSourceIp(); // If can't get from request context, get from http request. if (StringUtils.isBlank(sourceIp)) { sourceIp = WebUtils.getRemoteIp(httpServletRequest); } ...
@Test void getSourceIpForHttpRequest() { when(request.getRemoteAddr()).thenReturn("3.3.3.3"); assertEquals("2.2.2.2", NamingRequestUtil.getSourceIpForHttpRequest(request)); RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp(null); assertEquals("1.1.1....
private ScanResult<Object> entryScanIterator(RedisClient client, String startPos, String pattern, int count) { RFuture<ScanResult<Object>> f = entryScanIteratorAsync(client, startPos, pattern, count); return get(f); }
@Test public void testEntryScanIterator() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("test"); set.add(1.1, "v1"); set.add(1.2, "v2"); set.add(1.3, "v3"); Iterator<ScoredEntry<String>> entries = set.entryIterator(); assertThat(entries).toIterable().c...
@Override public <T> Optional<T> valueAs(Class<T> type) { checkNotNull(type); if (type == Object.class || type == double.class || type == Double.class) { @SuppressWarnings("unchecked") T value = (T) Double.valueOf(this.value); return Optional.of(value); }...
@Test public void testValueAsPrimitiveDouble() { ContinuousResource resource = Resources.continuous(D1, P1, Bandwidth.class) .resource(BW1.bps()); Optional<Double> volume = resource.valueAs(double.class); assertThat(volume.get(), is(BW1.bps())); }
public static CustomEnvironmentPluginManager getInstance() { return INSTANCE; }
@Test void testInstance() { CustomEnvironmentPluginManager instance = CustomEnvironmentPluginManager.getInstance(); assertNotNull(instance); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testOrderedListMergePendingAddsAndDeletes() { SettableFuture<Map<Range<Instant>, RangeSet<Long>>> orderedListFuture = SettableFuture.create(); orderedListFuture.set(null); SettableFuture<Map<Range<Instant>, RangeSet<Instant>>> deletionsFuture = SettableFuture.create(); deleti...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { try { if(containerService.isContainer(file)) { final List<B2BucketResponse> buckets = session.getClient().listBuckets(); for(B2BucketResponse bucket : ...
@Test public void testFindCommonPrefix() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path container = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); assertTrue(new B2FindFeature(session, fileid).find(container)...
public static SpanHandler create(SpanHandler[] handlers, AtomicBoolean noop) { if (handlers.length == 0) return SpanHandler.NOOP; if (handlers.length == 1) return new NoopAwareSpanHandler(handlers[0], noop); return new NoopAwareSpanHandler(new CompositeSpanHandler(handlers), noop); }
@Test void create_emptyIsNoop() { assertThat(NoopAwareSpanHandler.create(new SpanHandler[0], noop)) .isEqualTo(SpanHandler.NOOP); }
public void terminateCluster(final List<String> deleteTopicPatterns) { terminatePersistentQueries(); deleteSinkTopics(deleteTopicPatterns); deleteTopics(managedTopics); ksqlEngine.close(); }
@Test public void shouldClosePersistentQueries() { // When: clusterTerminator.terminateCluster(Collections.emptyList()); // Then: verify(persistentQuery0).close(); verify(persistentQuery1).close(); }
static UnixResolverOptions parseEtcResolverOptions() throws IOException { return parseEtcResolverOptions(new File(ETC_RESOLV_CONF_FILE)); }
@Test public void defaultValueReturnedIfAttemptsOptionsIsNotPresent(@TempDir Path tempDir) throws IOException { File f = buildFile(tempDir, "search localdomain\n" + "nameserver 127.0.0.11\n"); assertEquals(16, parseEtcResolverOptions(f).attempts()); }
public static Document readXML(File file) { Assert.notNull(file, "Xml file is null !"); if (false == file.exists()) { throw new UtilException("File [{}] not a exist!", file.getAbsolutePath()); } if (false == file.isFile()) { throw new UtilException("[{}] not a file!", file.getAbsolutePath()); } try {...
@Test public void readTest() { final Document doc = XmlUtil.readXML("test.xml"); assertNotNull(doc); }
public static void main(String[] args) throws Exception { TikaCLI cli = new TikaCLI(); if (cli.testForHelp(args)) { cli.usage(); return; } else if (cli.testForBatch(args)) { String[] batchArgs = BatchCommandLineBuilder.build(args); BatchProcessDri...
@Test public void testExtractInlineImages() throws Exception { String[] params = {"--extract-dir=" + extractDir.toAbsolutePath(), "-z", resourcePrefix + "/testPDF_childAttachments.pdf"}; TikaCLI.main(params); String[] tempFileNames = extractDir .toFile() .li...
public static GMeans fit(double[][] data, int kmax) { return fit(data, kmax, 100, 1E-4); }
@Test public void testUSPS() throws Exception { System.out.println("USPS"); MathEx.setSeed(19650218); // to get repeatable results. double[][] x = USPS.x; int[] y = USPS.y; double[][] testx = USPS.testx; int[] testy = USPS.testy; GMeans model = GMeans.fit(x...
public ChineseDate(Date date) { this(LocalDateTimeUtil.ofDate(date.toInstant())); }
@Test public void chineseDateTest() { ChineseDate date = new ChineseDate(DateUtil.parseDate("2020-01-25")); assertEquals("2020-01-25 00:00:00", date.getGregorianDate().toString()); assertEquals(2020, date.getChineseYear()); assertEquals(1, date.getMonth()); assertEquals("一月", date.getChineseMonth()); asse...
@Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { return getAuthenticatedDevice(call) .map(authenticatedDevice -> Contexts.interceptCall(Context.current() ...
@Test void interceptCall() { final ClientConnectionManager clientConnectionManager = getClientConnectionManager(); when(clientConnectionManager.getAuthenticatedDevice(any())).thenReturn(Optional.empty()); GrpcTestUtils.assertStatusException(Status.UNAUTHENTICATED, this::getAuthenticatedDevice); fin...
static int[] findMinMaxLengthsInSymbols(String[] symbols) { int min = Integer.MAX_VALUE; int max = 0; for (String symbol : symbols) { int len = symbol.length(); // some SENTINEL values can be empty strings, the month at index 12 or the // weekday at index 0 ...
@Test public void findMinMaxLengthsInSymbolsWithTrivialInputs() { String[] symbols = new String[] { "a", "bb" }; int[] results = CharSequenceToRegexMapper.findMinMaxLengthsInSymbols(symbols); assertEquals(1, results[0]); assertEquals(2, results[1]); }
public static void isTrue(boolean expression, String message) { if (expression == false) { throw new IllegalArgumentException(message); } }
@Test public void testIsTrue() { Utils.isTrue(true, "foo"); }
public static String buildFromPartsMap(String partsRule, Map<String, String> partsMap) { if (partsMap != null && !partsMap.isEmpty()) { Multimap<String, String> multimap = partsMap.entrySet().stream().collect(ArrayListMultimap::create, (m, e) -> m.put(e.getKey(), e.getValue()), Multimap::p...
@Test void testBuildFromPartsMap() { Multimap<String, String> partsMap = ArrayListMultimap.create(); partsMap.put("year", "2018"); partsMap.put("month", "05"); partsMap.put("year-summary", "true"); partsMap.put("half-year", "true"); // Dispatch string parts are sorted. Stri...
public boolean isRunning() { try { process.exitValue(); } catch (IllegalThreadStateException e) { return true; } return false; }
@Test void shouldReturnFalseWhenAProcessHasExited() { Process process = getMockedProcess(mock(OutputStream.class)); when(process.exitValue()).thenReturn(1); ProcessWrapper processWrapper = new ProcessWrapper(process, null, "", inMemoryConsumer(), UTF_8, null); assertThat(processWrapp...
@Override public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) { requireNonNull(dataTable, "dataTable may not be null"); requireNonNull(keyType, "keyType may not be null"); requireNonNull(valueType, "valueType may not be null"); if (dataTable.isEmpty()) {...
@Test void to_map_of_object_to_unknown_type__throws_exception__register_table_entry_transformer() { DataTable table = parse("", "| code | lat | lon |", "| KMSY | 29.993333 | -90.258056 |", "| KSFO | 37.618889 | -122.375 |", "| KSEA | 47.44888...
public void writeAndComplete(ProxyContext ctx, ReceiveMessageRequest request, PopResult popResult) { PopStatus status = popResult.getPopStatus(); List<MessageExt> messageFoundList = popResult.getMsgFoundList(); try { switch (status) { case FOUND: i...
@Test public void testWriteMessage() { ArgumentCaptor<String> changeInvisibleTimeMsgIdCaptor = ArgumentCaptor.forClass(String.class); doReturn(CompletableFuture.completedFuture(mock(AckResult.class))).when(this.messagingProcessor) .changeInvisibleTime(any(), any(), changeInvisibleTimeMsg...
protected String getRowKey(String resourceId, String tableName, String pk) { return new StringBuilder().append(resourceId).append(LOCK_SPLIT).append(tableName).append(LOCK_SPLIT).append(pk) .toString(); }
@Test public void testGetRowKey() { AbstractLocker locker = new AbstractLocker() { @Override public boolean acquireLock(List<RowLock> rowLock) { return false; } @Override public boolean acquireLock(List<RowLock> rowLock, boolean au...
@Override public YamlEncryptTableRuleConfiguration swapToYamlConfiguration(final EncryptTableRuleConfiguration data) { YamlEncryptTableRuleConfiguration result = new YamlEncryptTableRuleConfiguration(); for (EncryptColumnRuleConfiguration each : data.getColumns()) { result.getColumns().p...
@Test void assertSwapToYamlConfiguration() { EncryptColumnRuleConfiguration encryptColumnTwoConfig = new EncryptColumnRuleConfiguration("encrypt_column_2", new EncryptColumnItemRuleConfiguration("encrypt_cipher_2", "test_encryptor_2")); EncryptColumnRuleConfiguration encryptColumnThreeConfig = ...
public PrivateKey convertPrivateKey(final String privatePemKey) { StringReader keyReader = new StringReader(privatePemKey); try { PrivateKeyInfo privateKeyInfo = PrivateKeyInfo .getInstance(new PEMParser(keyReader).readObject()); return new JcaPEMKeyConverter...
@Test void givenMalformedPrivateKey_whenConvertPrivateKey_thenThrowRuntimeException() { // Given String malformedPrivatePemKey = "-----BEGIN PRIVATE KEY-----\n" + "malformedkey\n" + "-----END PRIVATE KEY-----"; // When & Then assertThatThrownBy(() -> ...
@Override public String getMessage() { if (!logPhi) { return super.getMessage(); } String answer; if (hasHl7MessageBytes() || hasHl7AcknowledgementBytes()) { String parentMessage = super.getMessage(); StringBuilder messageBuilder = new StringBuil...
@Test public void testEmptyAcknowledgement() { instance = new MllpException(EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, EMPTY_BYTE_ARRAY, LOG_PHI_TRUE); assertEquals(expectedMessage(HL7_MESSAGE, null), instance.getMessage()); }
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException { ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null")); if (null == value) { return convertNullValue(co...
@Test void assertConvertLocalDateTimeValue() throws SQLException { LocalDateTime localDateTime = LocalDateTime.of(2021, Month.DECEMBER, 23, 19, 30); assertThat(ResultSetUtils.convertValue(localDateTime, Timestamp.class), is(Timestamp.valueOf(localDateTime))); }
void validateSnapshotsUpdate( TableMetadata metadata, List<Snapshot> addedSnapshots, List<Snapshot> deletedSnapshots) { if (metadata.currentSnapshot() == null) { // no need to verify attempt to delete current snapshot if it doesn't exist // deletedSnapshots is necessarily empty when original snaps...
@Test void testValidateSnapshotsUpdateWithSnapshotMetadata() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); List<Snapshot> extraTestSnapshots = IcebergTestUtil.getExtraSnapshots(); TableMetadata metadataWithSnapshots = TableMetadata.buildFrom(noSnapshotsMetadat...
@Deprecated public static boolean isEmpty( String val ) { return Utils.isEmpty( val ); }
@Test public void testIsEmptyStringArray() { assertTrue( Const.isEmpty( (String[]) null ) ); assertTrue( Const.isEmpty( new String[] {} ) ); assertFalse( Const.isEmpty( new String[] { "test" } ) ); }
public static void retainMatching(Collection<String> values, String... patterns) { retainMatching(values, Arrays.asList(patterns)); }
@Test public void testRetainMatchingWithNoMatchingPattern() throws Exception { Collection<String> values = stringToList("A"); StringCollectionUtil.retainMatching(values, "B"); assertTrue(values.isEmpty()); }
public static Map<String, Object> merge(Map<String, Object> a, Map<String, Object> b) { if (a == null && b == null) { return null; } if (a == null || a.isEmpty()) { return copyMap(b); } if (b == null || b.isEmpty()) { return copyMap(a); ...
@SuppressWarnings("unchecked") @Test void mergeWithNull() { var mapWithNull = new HashMap<String, String>(); mapWithNull.put("null", null); Map<String, Object> a = Map.of( "map", Map.of( "map_a", Map.of("sub", mapWithNull), "map_c", "c" ...
@CanIgnoreReturnValue public Caffeine<K, V> softValues() { requireState(valueStrength == null, "Value strength was already set to %s", valueStrength); valueStrength = Strength.SOFT; return this; }
@Test public void softValues() { var cache = Caffeine.newBuilder().softValues().build(); assertThat(cache).isNotNull(); }
public TableMetadata readTableMetadata(String metadataLocation) { URI metadataLocationUri = URI.create(metadataLocation); // TODO: cache fileIO FileIO fileIO = fileIOFactory.getFileIO(metadataLocationUri); return CompletableFuture.supplyAsync(() -> TableMetadataParser.read(fileIO, metadataLocation)) ...
@SneakyThrows @Test public void testGetTableMetadataFromLocalFS() { when(mockFileIOFactory.getFileIO(any())).thenReturn(new SimpleLocalFileIO()); String metadataLocation = Objects.requireNonNull(this.getClass().getResource("/iceberg.metadata.json")) .toURI() .toString(); ...
public JobStatsExtended enrich(JobStats jobStats) { JobStats latestJobStats = getLatestJobStats(jobStats, previousJobStats); if (lock.tryLock()) { setFirstRelevantJobStats(latestJobStats); setJobStatsExtended(latestJobStats); setPreviousJobStats(latestJobStats); ...
@Test void estimatedTimeProcessingIsCalculated3() { JobStats firstJobStats = getJobStats(now().minusMillis(10), 100L, 0L, 0L, 100L); JobStats secondJobStats = getJobStats(now(), 99L, 0L, 0L, 101L); JobStatsExtended jobStatsExtended = enrich(firstJobStats, secondJobStats); assertTha...
public static void setFillInOutsideScopeExceptionStacktraces(boolean fillInStacktrace) { if (lockdown) { throw new IllegalStateException("Plugins can't be changed anymore"); } fillInOutsideScopeExceptionStacktraces = fillInStacktrace; }
@Test public void noStacktraceFill_shouldHaveNoStacktrace() { AutoDisposePlugins.setFillInOutsideScopeExceptionStacktraces(false); OutsideScopeException started = new OutsideScopeException("Lifecycle not started"); assertThat(started.getStackTrace()).isEmpty(); }
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } AvroSerial...
@Test void nonValidSchemaEvaluationShouldResultInCompatibleSerializers() { final AvroSerializer<GenericRecord> originalSerializer = new AvroSerializer<>(GenericRecord.class, FIRST_REQUIRED_LAST_OPTIONAL); final AvroSerializer<GenericRecord> newSerializer = new AvroSer...
@Override public PageResult<LoginLogDO> getLoginLogPage(LoginLogPageReqVO pageReqVO) { return loginLogMapper.selectPage(pageReqVO); }
@Test public void testGetLoginLogPage() { // mock 数据 LoginLogDO loginLogDO = randomPojo(LoginLogDO.class, o -> { o.setUserIp("192.168.199.16"); o.setUsername("wang"); o.setResult(SUCCESS.getResult()); o.setCreateTime(buildTime(2021, 3, 6)); });...
@SuppressWarnings("checkstyle:MissingSwitchDefault") @Override protected void doCommit(TableMetadata base, TableMetadata metadata) { int version = currentVersion() + 1; CommitStatus commitStatus = CommitStatus.FAILURE; /* This method adds no fs scheme, and it persists in HTS that way. */ final Stri...
@Test void testDoCommitAppendSnapshotsToNonMainBranch() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); Map<String, String> properties = new HashMap<>(BASE_TABLE_METADATA.properties()); try (MockedStatic<TableMetadataParser> ignoreWriteMock = Mockito.mockStatic(...
@VisibleForTesting int getReturnCode() { int successCode = CommandExecutorCodes.Kitchen.SUCCESS.getCode(); if ( getResult().getNrErrors() != 0 ) { getLog().logError( BaseMessages.getString( getPkgClazz(), "Kitchen.Error.FinishedWithErrors" ) ); return CommandExecutorCodes.Kitchen.ERRORS_DURING_P...
@Test public void testReturnCodeWithErrors() { try ( MockedStatic<BaseMessages> baseMessagesMockedStatic = mockStatic( BaseMessages.class ) ) { baseMessagesMockedStatic.when( () -> BaseMessages.getString( any(), anyString() ) ).thenReturn( "" ); when( result.getNrErrors() ).thenReturn( 1L ); whe...
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 testGetSubtaskProgressWithResponse() throws Exception { TaskDriver taskDriver = mock(TaskDriver.class); JobConfig jobConfig = mock(JobConfig.class); when(taskDriver.getJobConfig(anyString())).thenReturn(jobConfig); JobContext jobContext = mock(JobContext.class); when(taskDr...
@Override protected void watch(final Application application, final Local temporary, final FileWatcherListener listener, final ApplicationQuitCallback quit) throws IOException { if(log.isDebugEnabled()) { log.debug(String.format("Register %s in file watcher %s", temporary, watcher)); } ...
@Test(expected = NoSuchFileException.class) public void testNotfound() throws Exception { final DefaultWatchEditor editor = new DefaultWatchEditor(new Host(new TestProtocol()), new Path("/remote", EnumSet.of(Path.Type.file)), new DisabledListProgressListener()); editor.watch(new Application("com.app...
public static Set<SingleDeprecatedRuleKey> from(RulesDefinition.Rule rule) { rule.deprecatedRuleKeys(); return rule.deprecatedRuleKeys().stream() .map(r -> new SingleDeprecatedRuleKey() .setNewRepositoryKey(rule.repository().key()) .setNewRuleKey(rule.key()) .setOldRepositoryKey(r....
@Test public void test_creation_from_RulesDefinitionRule() { // Creation from RulesDefinition.Rule ImmutableSet<RuleKey> deprecatedRuleKeys = ImmutableSet.of( RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)), RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)), RuleKey.of(ra...
public static <T> T wrap(Callable<T> callable) { try { return callable.call(); } catch (Exception e) { throw new RuntimeException(e); } }
@Test(expected = RuntimeException.class) public void testWrap() { Assert.wrap(() -> { int a = 1 / 0; return true; }); }
public FeatureSet addValue(String value) { Objects.requireNonNull(value, "value"); values.add(value); return this; }
@Test void requireThatValueIsMandatoryInSetter() { FeatureSet node = new FeatureSet("foo", "bar"); try { node.addValue(null); fail(); } catch (NullPointerException e) { assertEquals("value", e.getMessage()); } assertValues(List.of("bar"), n...
@Override public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) { // 默认使用积分为 0 result.setUsePoint(0); // 1.1 校验是否使用积分 if (!BooleanUtil.isTrue(param.getPointStatus())) { result.setUsePoint(0); return; } // 1.2 校...
@Test public void testCalculate_PointStatusFalse() { // 准备参数 TradePriceCalculateReqBO param = new TradePriceCalculateReqBO() .setUserId(233L).setPointStatus(false) // 是否使用积分 .setItems(asList( new TradePriceCalculateReqBO.Item().setSkuId(10L).se...
@Override public List<String> getGroupIdList(int page, int pageSize) { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); int from = (page - 1) * pageSize; MapperResult mapperResult = configInfoMappe...
@Test void testGetGroupIdList() { int page = 10; int pageSize = 100; //mock select config state List<String> groupStrings = Arrays.asList("group1", "group2", "group3"); when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {}), eq(String.class))).thenReturn(gro...
public static Object typeConvert(String tableName ,String columnName, String value, int sqlType, String mysqlType) { if (value == null || (value.equals("") && !(isText(mysqlType) || sqlType == Types.CHAR || sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR))) { return null; ...
@Test public void typeConvertInputNotNullNotNullNotNullPositiveNotNullOutputNotNull() { // Arrange final String tableName = "1"; final String columnName = "Bar"; final String value = "1"; final int sqlType = 12; final String mysqlType = "2"; // Act final Object actual = JdbcT...
@Override public LoadBalancer newLoadBalancer(final LoadBalancer.Helper helper) { return new AbstractLoadBalancer(helper) { @Override protected AbstractReadyPicker newPicker(final List<Subchannel> list) { return new RoundRobinPicker(list); } }; ...
@Test public void testNewLoadBalancer() { LoadBalancer.Helper helper = mock(LoadBalancer.Helper.class); LoadBalancer loadBalancer = roundRobinLoadBalancerProvider.newLoadBalancer(helper); assertNotNull(loadBalancer); }
public void setPreservePathElements(boolean preservePathElements) { this.preservePathElements = preservePathElements; }
@Test public void testZipWithPreservedPathElements() throws Exception { zip.setPreservePathElements(true); getMockEndpoint("mock:zip").expectedBodiesReceived(getZippedTextInFolder("poems/", "poems/poem.txt")); getMockEndpoint("mock:zip").expectedHeaderReceived(FILE_NAME, "poem.txt.zip"); ...
public static TimelineEntity aggregateEntities( TimelineEntities entities, String resultEntityId, String resultEntityType, boolean needsGroupIdInResult) { ConcurrentMap<String, AggregationStatusTable> aggregationGroups = new ConcurrentHashMap<>(); updateAggregateStatus(entities, aggregationG...
@Test void testAggregation() throws Exception { // Test aggregation with multiple groups. int groups = 3; int n = 50; TimelineEntities testEntities = generateTestEntities(groups, n); TimelineEntity resultEntity = TimelineCollector.aggregateEntities( testEntities, "test_result", "TEST_AGGR"...
public static ExecutorConfig build( String type, String address, Integer checkpoint, Integer parallelism, boolean useSqlFragment, boolean useStatementSet, boolean useBatchModel, String savePointPath, String jobNa...
@Test void build() {}
@Override public boolean supportsOpenStatementsAcrossRollback() { return false; }
@Test void assertSupportsOpenStatementsAcrossRollback() { assertFalse(metaData.supportsOpenStatementsAcrossRollback()); }
@Override public Boolean run(final Session<?> session) throws BackgroundException { final Metadata feature = session.getFeature(Metadata.class); if(log.isDebugEnabled()) { log.debug(String.format("Run with feature %s", feature)); } for(Path file : files) { if(...
@Test public void testRunUpdated() throws Exception { final List<Path> files = new ArrayList<>(); final Path p = new Path("a", EnumSet.of(Path.Type.file)); files.add(p); final Map<String, String> previous = new HashMap<>(); previous.put("nullified", "hash"); previous....
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @PostMapping("/users") public void createOrUpdateUser( @RequestParam(value = "isCreate", defaultValue = "false") boolean isCreate, @RequestBody UserPO user) { if (StringUtils.isContainEmpty(user.getUsername(), user.getPassword())) { ...
@Test public void testCreateOrUpdateUser() { UserPO user = new UserPO(); user.setUsername("username"); user.setPassword("password"); Mockito.when(userPasswordChecker.checkWeakPassword(Mockito.anyString())) .thenReturn(new CheckResult(Boolean.TRUE, "")); userInfoController.createOrUpdateU...
@SuppressWarnings("unchecked") @Override public void configure(Map<String, ?> configs) throws KafkaException { try { this.configs = configs; if (connectionMode == ConnectionMode.SERVER) { createServerCallbackHandlers(configs); createConnectionsMaxR...
@Test public void testClientChannelBuilderWithBrokerConfigs() throws Exception { Map<String, Object> configs = new HashMap<>(); CertStores certStores = new CertStores(false, "client", "localhost"); configs.putAll(certStores.getTrustingConfig(certStores)); configs.put(SaslConfigs.SASL...
@Override public SmileResponse<T> handle(Request request, Response response) { byte[] bytes = readResponseBytes(response); String contentType = response.getHeader(CONTENT_TYPE); if ((contentType == null) || !MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) { return new Smil...
@Test public void testInvalidSmile() { byte[] invalidSmileBytes = "test".getBytes(UTF_8); SmileResponse<User> response = handler.handle(null, mockResponse(OK, MEDIA_TYPE_SMILE, invalidSmileBytes)); assertFalse(response.hasValue()); assertEquals(response.getException().getMessage...
public final RequestSender post() { return request(HttpMethod.POST); }
@Test void testIssue777() { disposableServer = createServer() .route(r -> r.post("/empty", (req, res) -> { // Just consume the incoming body req.receive().subscribe(); ...
static S3ResourceId fromUri(String uri) { Matcher m = S3_URI.matcher(uri); checkArgument(m.matches(), "Invalid S3 URI: [%s]", uri); String scheme = m.group("SCHEME"); String bucket = m.group("BUCKET"); String key = Strings.nullToEmpty(m.group("KEY")); if (!key.startsWith("/")) { key = "/" ...
@Test public void testInvalidPathNoBucket() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Invalid S3 URI: [s3://]"); S3ResourceId.fromUri("s3://"); }
@SuppressWarnings("FutureReturnValueIgnored") public static Mono<Channel> bind(TransportConfig config, ChannelInitializer<Channel> channelInitializer, SocketAddress bindAddress, boolean isDomainSocket) { Objects.requireNonNull(config, "config"); Objects.requireNonNull(bindAddress, "bindAddress"); Objects.requ...
@Test @SuppressWarnings("FutureReturnValueIgnored") void bind_whenBindException_thenChannelIsUnregistered() { final TcpClientConfig transportConfig = TcpClient.newConnection().configuration(); final Channel channel1 = TransportConnector.bind( transportConfig, new RecordingChannelInitializer(), new Ine...
@Override public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { // Submit store run to background thread final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttpEntityCallable...
@Test public void testWrite() throws Exception { final TransferStatus status = new TransferStatus(); status.setMime("text/plain"); final byte[] content = "test".getBytes(StandardCharsets.UTF_8); status.setLength(content.length); final Path container = new Path("test.cyberduck...
@Override public void onSuccess(T result) { _future.complete(result); }
@Test public void testSuccess() { CompletableFuture<String> future = new CompletableFuture<>(); CompletableFutureCallbackAdapter<String> adapter = new CompletableFutureCallbackAdapter<>(future); adapter.onSuccess("haha"); assertTrue(future.isDone()); assertFalse(future.isCompletedExceptionally()...
public static MonitoringInfoMetricName named(String urn, Map<String, String> labels) { return new MonitoringInfoMetricName(urn, labels); }
@Test public void testEmptyUrnThrows() { HashMap<String, String> labels = new HashMap<String, String>(); thrown.expect(IllegalArgumentException.class); MonitoringInfoMetricName.named("", labels); }
@Override public ConfigInfo findConfigInfo(long id) { try { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); return this.jt.queryForObject(configInfoMapper.select( A...
@Test void testFindConfigInfoById() { long id = 1234567890876L; ConfigInfo configInfo = new ConfigInfo(); configInfo.setId(id); Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(configInfo); ConfigInfo configR...
public boolean verifyTopicCleanupPolicyOnlyCompact(String topic, String workerTopicConfig, String topicPurpose) { Set<String> cleanupPolicies = topicCleanupPolicy(topic); if (cleanupPolicies.isEmpty()) { log.info("Unable to use admin client to verify the cleanup policy of '{}' " ...
@Test public void verifyingTopicCleanupPolicyShouldFailWhenTopicHasDeletePolicy() { String topicName = "myTopic"; Map<String, String> topicConfigs = Collections.singletonMap("cleanup.policy", "delete"); Cluster cluster = createCluster(1); try (MockAdminClient mockAdminClient = new Mo...
@GetMapping("/rules") public ShenyuAdminResult listPageRuleDataPermissions(@RequestParam("currentPage") final Integer currentPage, @RequestParam("pageSize") final Integer pageSize, @RequestParam("userId...
@Test public void listPageRuleDataPermissions() throws Exception { Integer currentPage = 1; Integer pageSize = 10; String userId = "testUserId"; String selectorId = "testSelectorId"; String name = "testName"; final PageParameter pageParameter = new PageParameter(curr...
@VisibleForTesting static Set<AbsoluteUnixPath> getVolumesSet(RawConfiguration rawConfiguration) throws InvalidContainerVolumeException { Set<AbsoluteUnixPath> volumes = new HashSet<>(); for (String path : rawConfiguration.getVolumes()) { try { AbsoluteUnixPath absoluteUnixPath = AbsoluteU...
@Test public void testGetInvalidVolumesList() { when(rawConfiguration.getVolumes()).thenReturn(Collections.singletonList("`some/root")); InvalidContainerVolumeException exception = assertThrows( InvalidContainerVolumeException.class, () -> PluginConfigurationProcessor.getVolum...
@Override public Optional<Map<String, EncryptionInformation>> getReadEncryptionInformation( ConnectorSession session, Table table, Optional<Set<HiveColumnHandle>> requestedColumns, Map<String, Partition> partitions) { Optional<DwrfTableEncryptionProperties...
@Test public void testGetReadEncryptionInformationForPartitionedTableWithTableLevelEncryptionAndNoRequestedColumns() { Table table = createTable(DWRF, Optional.of(forTable("key1", "algo", "provider")), true); Optional<Map<String, EncryptionInformation>> encryptionInformation = encryptionInformat...
@Override public void preflight(final Path source, final Path target) throws BackgroundException { if(source.isRoot() || new DeepboxPathContainerService(session).isContainer(source) || new DeepboxPathContainerService(session).isInTrash(source)) { throw new AccessDeniedException(MessageFormat.for...
@Test public void testNoMoveRenameDocuments() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path documents = new Path("/ORG 1 - DeepBox Desktop App/ORG1:Box1/Documents", EnumSet.of(Path.Type.directory, Path.Type.volume)); final PathAttributes attri...
public static int compareBsonValue(BsonValue o1, BsonValue o2) { return compareBsonValue(o1, o2, true); }
@Test public void testCompareBsonValue() { // test compare Decimal128 assertTrue( BsonUtils.compareBsonValue( new BsonDecimal128(Decimal128.parse("18")), new BsonDecimal128(Decimal128.parse("17"))) ...
@Override public String toString() { StringBuilder bld = new StringBuilder(); bld.append("Assignment"); bld.append("(topicIdPartition=").append(topicIdPartition); bld.append(", directoryId=").append(directoryId); bld.append(", submissionTimeNs=").append(submissionTimeNs); ...
@Test public void testAssignmentToString() { assertEquals("Assignment(topicIdPartition=rTudty6ITOCcO_ldVyzZYg:1, " + "directoryId=rzRT8XZaSbKsP6j238zogg, " + "submissionTimeNs=123, " + "successCallback=NoOpRunnable)", new Assignment(new TopicIdPartition(Uuid.f...
@Override public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters, final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) { final long now = System.cur...
@Test public void reportsHistograms() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); final Snapshot snapshot = mock(Snapshot.class); when(snapshot.getMax()).thenReturn(2L); when(snapshot.getMean()).thenReturn(...
@Override public Iterable<ConnectorFactory> getConnectorFactories() { return ImmutableList.of(new KuduConnectorFactory()); }
@Test public void testCreateConnector() throws Exception { Plugin plugin = new KuduPlugin(); ConnectorFactory factory = getOnlyElement(plugin.getConnectorFactories()); factory.create("test", ImmutableMap.of("kudu.client.master-addresses", "localhost:7051"), new TestingConnect...
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testWrongTimestampType() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("@Timestamp argument must have type org.joda.time.Instant"); DoFnSignatures.getSignature( new DoFn<String, String>() { @ProcessElement public void p...
@Override public String getLogChannelId() { return log.getLogChannelId(); }
@Ignore @Test public void testLoggingObjectIsNotLeakInTrans() throws Exception { Repository rep = mock( Repository.class ); RepositoryDirectoryInterface repInt = Mockito.mock( RepositoryDirectoryInterface.class ); when( rep.loadTransformation( anyString(), any( RepositoryDirectoryInterface.class )...
@Override public void createIngress(Ingress ingress) { checkNotNull(ingress, ERR_NULL_INGRESS); checkArgument(!Strings.isNullOrEmpty(ingress.getMetadata().getUid()), ERR_NULL_INGRESS_UID); k8sIngressStore.createIngress(ingress); log.info(String.format(MSG_INGRESS, i...
@Test(expected = IllegalArgumentException.class) public void testCreateDuplicateIngress() { target.createIngress(INGRESS); target.createIngress(INGRESS); }
public static String getSBln( boolean... blnA ) { // String Info = ""; // if ( blnA == null ) return "?"; if ( blnA.length == 0 ) return "?"; // for ( int K = 0; K < blnA.length; K ++ ) { // Info += ( blnA[ K ] )? "T" : "F"; } // return Info; }
@Test public void testgetSBln() throws Exception { // assertEquals( "?", BTools.getSBln() ); assertEquals( "?", BTools.getSBln( null ) ); assertEquals( "T", BTools.getSBln( true ) ); assertEquals( "F", BTools.getSBln( false ) ); assertEquals( "TFFT", BTools.getSBln( true, false, false, true ) ); assertEq...
@Override public boolean supports(Job job) { if (jobActivator == null) return false; JobDetails jobDetails = job.getJobDetails(); return !jobDetails.hasStaticFieldName() && jobActivator.activateJob(toClass(jobDetails.getClassName())) != null; }
@Test void supportsJobIfJobClassIsKnownInIoC() { Job job = anEnqueuedJob() .withJobDetails(defaultJobDetails()) .build(); assertThat(backgroundIoCJobWithIocRunner.supports(job)).isTrue(); }
public static Range<Comparable<?>> safeClosed(final Comparable<?> lowerEndpoint, final Comparable<?> upperEndpoint) { try { return Range.closed(lowerEndpoint, upperEndpoint); } catch (final ClassCastException ex) { Optional<Class<?>> clazz = getTargetNumericType(Arrays.asList(low...
@Test void assertSafeClosedForDouble() { Range<Comparable<?>> range = SafeNumberOperationUtils.safeClosed(5.12F, 13.75); assertThat(range.lowerEndpoint(), is(5.12)); assertThat(range.upperEndpoint(), is(13.75)); }
@Override public void deleteAll() { try { this.indexWriter.deleteAll(); this.searcherManager.maybeRefreshBlocking(); this.indexWriter.commit(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test void shouldDeleteAll() throws IOException { this.searchEngine.deleteAll(); verify(this.indexWriter).deleteAll(); verify(this.searcherManager).maybeRefreshBlocking(); verify(this.indexWriter).commit(); }
@Override public AppResponse process(Flow flow, MrzDocumentRequest params) { if(!(params.getDocumentType().equals("PASSPORT") || params.getDocumentType().equals("ID_CARD"))){ return new NokResponse(); } Map<String, String> travelDocument = Map.of( "documentNumber", pa...
@Test public void processValid1() { //given MrzDocumentRequest mrzDocumentRequest = new MrzDocumentRequest(); mrzDocumentRequest.setDocumentType("PASSPORT"); mrzDocumentRequest.setDateOfBirth("test"); mrzDocumentRequest.setDateOfExpiry("test"); mrzDocumentRequest.set...
public static String fullTableName(String catalogName, TableIdentifier identifier) { StringBuilder sb = new StringBuilder(); if (catalogName.contains("/") || catalogName.contains(":")) { // use / for URI-like names: thrift://host:port/db.table sb.append(catalogName); if (!catalogName.endsWith...
@Test public void fullTableNameWithDifferentValues() { String uriTypeCatalogName = "thrift://host:port/db.table"; String namespace = "ns"; String nameSpaceWithTwoLevels = "ns.l2"; String tableName = "tbl"; TableIdentifier tableIdentifier = TableIdentifier.of(namespace, tableName); assertThat(C...
public static FactoryBuilder newFactoryBuilder() { return new FactoryBuilder(); }
@Test void equalsAndHashCode() { // same instance are equivalent Propagation.Factory factory = B3Propagation.newFactoryBuilder() .injectFormat(Span.Kind.CLIENT, Format.SINGLE_NO_PARENT) .injectFormat(Span.Kind.SERVER, Format.SINGLE_NO_PARENT) .build(); assertThat(factory).isEqualTo(f...
@Override public void closeDiscountActivity(Long id) { // 校验存在 DiscountActivityDO activity = validateDiscountActivityExists(id); if (activity.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) { // 已关闭的活动,不能关闭噢 throw exception(DISCOUNT_ACTIVITY_CLOSE_FAIL_STATUS_CLOSED); ...
@Test public void testCloseDiscountActivity() { // mock 数据 DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus())); discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据 ...
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { List<String> basePath = getPathComponents(canonicalBaseFile); List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); //if the roots aren't the same (i.e. different drives on a ...
@Test public void pathUtilTest14() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRelativeFile...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldFetchWithOnlyEndBounds() { // When: table.get(A_KEY, PARTITION, Range.all(), WINDOW_END_BOUNDS); // Then: verify(cacheBypassFetcher).fetch( eq(tableStore), any(), eq(WINDOW_END_BOUNDS.lowerEndpoint().minus(WINDOW_SIZE)), eq(WINDOW_END_BOUNDS.upp...
public static String getType(String fileStreamHexHead) { if(StrUtil.isBlank(fileStreamHexHead)){ return null; } if (MapUtil.isNotEmpty(FILE_TYPE_MAP)) { for (final Entry<String, String> fileTypeEntry : FILE_TYPE_MAP.entrySet()) { if (StrUtil.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())...
@Test @Disabled public void ofdTest() { final File file = FileUtil.file("e:/test.ofd"); final String hex = IoUtil.readHex64Upper(FileUtil.getInputStream(file)); Console.log(hex); final String type = FileTypeUtil.getType(file); Console.log(type); assertEquals("ofd", type); }
@PublicAPI(usage = ACCESS) public JavaClasses importUrl(URL url) { return importUrls(singletonList(url)); }
@Test public void reflect_works() { JavaClasses classes = new ClassFileImporter().importUrl(getClass().getResource("testexamples/innerclassimport")); JavaClass calledClass = classes.get(CalledClass.class); assertThat(calledClass.reflect()).isEqualTo(CalledClass.class); assertThat(ca...
@Override public void put(final Bytes key, final byte[] valueAndTimestamp) { wrapped().put(key, valueAndTimestamp); log(key, rawValue(valueAndTimestamp), valueAndTimestamp == null ? context.timestamp() : timestamp(valueAndTimestamp)); }
@Test public void shouldReturnOldValueOnDelete() { store.put(hi, rawThere); assertThat(store.delete(hi), equalTo(rawThere)); }
public static String convertToString(Object parsedValue, Type type) { if (parsedValue == null) { return null; } if (type == null) { return parsedValue.toString(); } switch (type) { case BOOLEAN: case SHORT: case INT: ...
@Test public void testConvertValueToStringList() { assertEquals("a,bc,d", ConfigDef.convertToString(Arrays.asList("a", "bc", "d"), Type.LIST)); assertNull(ConfigDef.convertToString(null, Type.LIST)); }
@Override public ListenableFuture<BufferResult> get(OutputBufferId outputBufferId, long startingSequenceId, DataSize maxSize) { checkState(!Thread.holdsLock(this), "Can not get pages while holding a lock on this"); requireNonNull(outputBufferId, "outputBufferId is null"); checkArgument(m...
@Test public void testAcknowledgementFreesWriters() { BroadcastOutputBuffer buffer = createBroadcastBuffer( createInitialEmptyOutputBuffers(BROADCAST) .withBuffer(FIRST, BROADCAST_PARTITION_ID) .withBuffer(SECOND, BROADCAST_PARTITION_ID) ...
public static SourceOperationResponse performSplit( SourceSplitRequest request, PipelineOptions options) throws Exception { return performSplitWithApiLimit( request, options, DEFAULT_NUM_BUNDLES_LIMIT, DATAFLOW_SPLIT_RESPONSE_API_SIZE_LIMIT); }
@Test public void testTooLargeSplitResponseFails() throws Exception { com.google.api.services.dataflow.model.Source source = translateIOToCloudSource(CountingSource.upTo(1000), options); expectedException.expectMessage("[0, 1000)"); expectedException.expectMessage("larger than the limit 100"); ...
public void loadUdtfFromClass( final Class<?> theClass, final String path ) { final UdtfDescription udtfDescriptionAnnotation = theClass.getAnnotation(UdtfDescription.class); if (udtfDescriptionAnnotation == null) { throw new KsqlException(String.format("Cannot load class %s. Classes contain...
@Test public void shouldNotLoadUdtfWithWrongReturnValue() { // Given: final MutableFunctionRegistry functionRegistry = new InternalFunctionRegistry(); final SqlTypeParser typeParser = create(EMPTY); final UdtfLoader udtfLoader = new UdtfLoader( functionRegistry, empty(), typeParser, true )...
public boolean addAll(Collection<? extends NODE> c) { throw e; }
@Test void require_that_addAllindex_throws_exception() { assertThrows(NodeVector.ReadOnlyException.class, () -> new TestNodeVector("foo").addAll(0, List.of(barNode()))); }
public void updateConsumerOffsetOneway( final String addr, final UpdateConsumerOffsetRequestHeader requestHeader, final long timeoutMillis ) throws RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException, InterruptedException ...
@Test public void testUpdateConsumerOffsetOneway() throws RemotingException, InterruptedException { UpdateConsumerOffsetRequestHeader requestHeader = mock(UpdateConsumerOffsetRequestHeader.class); mqClientAPI.updateConsumerOffsetOneway(defaultBrokerAddr, requestHeader, defaultTimeout); }
public static <T> T createDelegatingProxy(Class<T> clazz, final Object delegate) { final Class delegateClass = delegate.getClass(); return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[] {clazz}, (proxy, method, args) -> { try { ...
@Test public void createDelegatingProxy_wrongParamType() { DelegatingProxyFixture fixture = ReflectionHelpers.createDelegatingProxy(DelegatingProxyFixture.class, new Delegate()); // verify the mismatched delegate method doesn't get matched assertThat(fixture.delegateMethodWrongParamType("value"))....
public static Field p(String fieldName) { return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName); }
@Test void validate_positive_search_term_of_strings() { Query q = Q.p(Q.p("k1").contains("v1").and("k2").contains("v2").andnot("k3").contains("v3")) .andnot(Q.p("nk1").contains("nv1").and("nk2").contains("nv2").andnot("nk3").contains("nv3")) .and(Q.p("k4").contains("v4") ...
public static FusedPipeline fuse(Pipeline p) { return new GreedyPipelineFuser(p).fusedPipeline; }
@Test public void parDoWithTimerRootsStage() { // (impulse.out) -> parDo -> (parDo.out) // (parDo.out) -> timer -> timer.out // timer has a timer spec which prevents it from fusing with an upstream ParDo PTransform parDoTransform = PTransform.newBuilder() .setUniqueName("ParDo") ...
@Udf public <T extends Comparable<? super T>> List<T> arraySortDefault(@UdfParameter( description = "The array to sort") final List<T> input) { return arraySortWithDirection(input, "ASC"); }
@Test public void shouldSortBigInts() { final List<Long> input = Arrays.asList(1L, 3L, -2L); final List<Long> output = udf.arraySortDefault(input); assertThat(output, contains(-2L, 1L, 3L)); }
@SuppressWarnings("unchecked") public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { return register(MetricName.build(name), metric); }
@Test public void registeringAGaugeTriggersANotification() throws Exception { assertThat(registry.register(THING, gauge)) .isEqualTo(gauge); verify(listener).onGaugeAdded(THING, gauge); }