focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test public void shouldGetTriFunction() throws NoSuchMethodException { final Type type = getClass().getDeclaredMethod("triFunctionType", TriFunction.class) .getGenericParameterTypes()[0]; final ParamType schema = UdfUtil.getSchemaFromType(type); assertThat(schema, instanceOf(LambdaType.class)); ...
public Optional<ComputationState> get(String computationId) { try { return Optional.ofNullable(computationCache.get(computationId)); } catch (UncheckedExecutionException | ExecutionException | ComputationStateNotFoundException e) { if (e.getCause() instanceof ComputationStateNotFound...
@Test public void testGet_computationStateConfigFetcherFailure() { String computationId = "computationId"; when(configFetcher.fetchConfig(eq(computationId))).thenThrow(new RuntimeException()); Optional<ComputationState> computationState = computationStateCache.get(computationId); assertFalse(computati...
public Path getLocalPath(String dirsProp, String path) throws IOException { String[] dirs = getTrimmedStrings(dirsProp); int hashCode = path.hashCode(); FileSystem fs = FileSystem.getLocal(this); for (int i = 0; i < dirs.length; i++) { // try each local dir int index = (hashCode+i & Integer.M...
@Test public void testGetLocalPath() throws IOException { Configuration conf = new Configuration(); String[] dirs = new String[]{"a", "b", "c"}; for (int i = 0; i < dirs.length; i++) { dirs[i] = new Path(GenericTestUtils.getTempPath(dirs[i])).toString(); } conf.set("dirs", StringUtils.join(d...
public static void validate(FilterPredicate predicate, MessageType schema) { Objects.requireNonNull(predicate, "predicate cannot be null"); Objects.requireNonNull(schema, "schema cannot be null"); predicate.accept(new SchemaCompatibilityValidator(schema)); }
@Test public void testRepeatedSupportedForContainsPredicates() { try { validate(contains(eq(lotsOfLongs, 10L)), schema); validate(and(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); validate(or(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); ...
public String toString(JimfsPath path) { Name root = path.root(); String rootString = root == null ? null : root.toString(); Iterable<String> names = Iterables.transform(path.names(), Functions.toStringFunction()); return type.toString(rootString, names); }
@Test public void testToString() { // not much to test for this since it just delegates to PathType anyway JimfsPath path = new JimfsPath(service, null, ImmutableList.of(Name.simple("foo"), Name.simple("bar"))); assertThat(service.toString(path)).isEqualTo("foo/bar"); path = new JimfsPath(ser...
public static CircuitBreakerRegistry of(Configuration configuration, CompositeCustomizer<CircuitBreakerConfigCustomizer> customizer){ CommonCircuitBreakerConfigurationProperties circuitBreakerProperties = CommonsConfigurationCircuitBreakerConfiguration.of(configuration); Map<String, CircuitBreakerConfig...
@Test public void testCircuitBreakerRegistryFromPropertiesFile() throws ConfigurationException { Configuration config = CommonsConfigurationUtil.getConfiguration(PropertiesConfiguration.class, TestConstants.RESILIENCE_CONFIG_PROPERTIES_FILE_NAME); CircuitBreakerRegistry circuitBreakerRegistry = Com...
public HealthCheckResponse checkHealth() { final Map<String, HealthCheckResponseDetail> results = DEFAULT_CHECKS.stream() .collect(Collectors.toMap( Check::getName, check -> check.check(this) )); final boolean allHealthy = results.values().stream() .allMatch(Healt...
@Test public void shouldReturnHealthyIfKafkaCheckFailsWithUnknownTopicOrPartitionException() { // Given: givenDescribeTopicsThrows(new UnknownTopicOrPartitionException()); // When: final HealthCheckResponse response = healthCheckAgent.checkHealth(); // Then: assertThat(response.getDetails()....
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void tooOldJava() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/too_old_java.txt")), CrashReportAnalyzer.Rule.TOO_OLD_JAVA); assertEquals("60", result.getMatcher().group("expected"));...
public static String getRmPrincipal(Configuration conf) throws IOException { String principal = conf.get(YarnConfiguration.RM_PRINCIPAL); String prepared = null; if (principal != null) { prepared = getRmPrincipal(principal, conf); } return prepared; }
@Test public void testGetRMPrincipalStandAlone_Configuration() throws IOException { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_ADDRESS, "myhost"); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, false); String result = YarnClientUtils.getRmPrincipal(conf); assertNu...
@Override public boolean accept(Object object) { return factToCheck.stream() .allMatch(factCheckerHandle -> factCheckerHandle.getClazz().isAssignableFrom(object.getClass()) && factCheckerHandle.getCheckFuction().appl...
@Test public void accept() { ConditionFilter conditionFilter = createConditionFilter(ValueWrapper::of); assertThat(conditionFilter.accept(1)).isFalse(); assertThat(conditionFilter.accept("String")).isTrue(); }
@Override public String getURL( String hostname, String port, String databaseName ) { String url = "jdbc:sqlserver://" + hostname + ":" + port + ";database=" + databaseName + ";encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"; if ( getAttribute( IS_ALWAY...
@Test public void testGetUrlWithAadMfaAuth(){ dbMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE ); dbMeta.addAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "false" ); dbMeta.addAttribute( JDBC_AUTH_METHOD, ACTIVE_DIRECTORY_MFA ); String expectedUrl = "jdbc:sqlserver://abc.database.windows.net:1433;datab...
@Override public com.thoughtworks.go.plugin.domain.artifact.Capabilities getCapabilitiesFromResponseBody(String responseBody) { return Capabilities.fromJSON(responseBody).toCapabilities(); }
@Test public void shouldDeserializeCapabilities() { final Capabilities capabilities = new ArtifactMessageConverterV2().getCapabilitiesFromResponseBody("{}"); assertNotNull(capabilities); }
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof TransMeta ) ) { return feedback; } TransMeta transMeta = (TransMeta) subject; String description = transMe...
@Test public void testVerifyRule_LongDescription_EnabledRule() { TransformationHasDescriptionImportRule importRule = getImportRule( 10, true ); TransMeta transMeta = new TransMeta(); transMeta.setDescription( "A very long description that has more characters than the minimum required to be a valid o...
@Override public Endpoints leaderEndpoints() { return Endpoints.empty(); }
@Test void testLeaderEndpoints() { UnattachedState state = newUnattachedState(Utils.mkSet(1, 2, 3), OptionalInt.empty()); assertEquals(Endpoints.empty(), state.leaderEndpoints()); }
public void writeEncodedLong(int valueType, long value) throws IOException { int index = 0; if (value >= 0) { while (value > 0x7f) { tempBuf[index++] = (byte)value; value >>= 8; } } else { while (value < -0x80) { ...
@Test public void testWriteEncodedLong() throws IOException { testWriteEncodedLongHelper(0x00L, 0x00); testWriteEncodedLongHelper(0x40L, 0x40); testWriteEncodedLongHelper(0x7fL, 0x7f); testWriteEncodedLongHelper(0xffL, 0xff, 0x00); testWriteEncodedLongHelper(0xffffffffffffff8...
Set<Queue> getChildren() { return children; }
@Test (timeout=5000) public void testDefaultConfig() { QueueManager manager = new QueueManager(true); assertThat(manager.getRoot().getChildren().size()).isEqualTo(2); }
static void toJson(ManifestFile manifestFile, JsonGenerator generator) throws IOException { Preconditions.checkArgument(manifestFile != null, "Invalid manifest file: null"); Preconditions.checkArgument(generator != null, "Invalid JSON generator: null"); generator.writeStartObject(); generator.writeStr...
@Test public void testParser() throws Exception { ManifestFile manifest = createManifestFile(); String jsonStr = JsonUtil.generate(gen -> ManifestFileParser.toJson(manifest, gen), false); assertThat(jsonStr).isEqualTo(manifestFileJson()); }
static String toJson(ViewHistoryEntry entry) { return JsonUtil.generate(gen -> toJson(entry, gen), false); }
@Test public void testViewHistoryEntryToJson() { String json = "{\"timestamp-ms\":123,\"version-id\":1}"; ViewHistoryEntry viewHistoryEntry = ImmutableViewHistoryEntry.builder().versionId(1).timestampMillis(123).build(); assertThat(ViewHistoryEntryParser.toJson(viewHistoryEntry)) .as("Shou...
@Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } ObjectRecordWithStats that = (ObjectRecordWithStats) o; return value.equals(that.value); }
@Test public void testEquals() { assertEquals(record, record); assertEquals(record, recordSameAttributes); assertNotEquals(null, record); assertNotEquals(new Object(), record); assertNotEquals(record, dataRecord); assertNotEquals(record, recordOtherLastStoredTime); ...
@CheckForNull public Duration calculate(DefaultIssue issue) { if (issue.isFromExternalRuleEngine()) { return issue.effort(); } Rule rule = ruleRepository.getByKey(issue.ruleKey()); DebtRemediationFunction fn = rule.getRemediationFunction(); if (fn != null) { verifyEffortToFix(issue, fn...
@Test public void linear_function() { double effortToFix = 3.0; int coefficient = 2; issue.setGap(effortToFix); rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, coefficient + "min", null)); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo((int) ...
public static boolean isIPInSubnet(String ip, String subnetCidr) { SubnetUtils subnetUtils = new SubnetUtils(subnetCidr); subnetUtils.setInclusiveHostCount(true); return subnetUtils.getInfo().isInRange(ip); }
@Test public void testIsIPInSubnet() { assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.0.1/32")).isTrue(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.1.1/32")).isFalse(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.0.1/24")).isTrue(); assertThat(N...
static String tryToExtractErrorMessage(Reconciliation reconciliation, Buffer buffer) { try { return buffer.toJsonObject().getString("message"); } catch (DecodeException e) { LOGGER.warnCr(reconciliation, "Failed to decode the error message from the response: " + buffer, e); ...
@Test public void testJsonDecoding() { assertThat(KafkaConnectApiImpl.tryToExtractErrorMessage(Reconciliation.DUMMY_RECONCILIATION, Buffer.buffer("{\"message\": \"This is the error\"}")), is("This is the error")); assertThat(KafkaConnectApiImpl.tryToExtractErrorMessage(Reconciliation.DUMMY_RECONCIL...
@Override protected Endpoint createEndpoint(final String uri, final String path, final Map<String, Object> parameters) throws Exception { if (autoConfiguration != null && autoConfiguration.isAutoConfigurable()) { autoConfiguration.ensureNameSpaceAndTenant(path); } fi...
@Test public void testPulsarEndpointDefaultConfiguration() throws Exception { PulsarComponent component = context.getComponent("pulsar", PulsarComponent.class); PulsarEndpoint endpoint = (PulsarEndpoint) component.createEndpoint("pulsar://persistent/test/foobar/BatchCreated"); assertNotNul...
@Override public void cancel() { context.goToFinished(context.getArchivedExecutionGraph(JobStatus.CANCELED, null)); }
@Test void testCancelTransitionsToFinished() { TestingStateWithoutExecutionGraph state = new TestingStateWithoutExecutionGraph(ctx, LOG); ctx.setExpectFinished( archivedExecutionGraph -> { assertThat(archivedExecutionGraph.getState()).isEqualTo(JobStatus.CANCELED...
public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); }
@Test public void testValidateValueMismatchString() { // CharSequence is a similar type (supertype of String), but we restrict to String. CharBuffer cbuf = CharBuffer.wrap("abc"); assertThrows(DataException.class, () -> ConnectSchema.validateValue(Schema.STRING_SCHEMA, cbuf)); ...
@Override public String getDataSource() { return DataSourceConstant.DERBY; }
@Test void testGetDataSource() { String dataSource = configInfoAggrMapperByDerby.getDataSource(); assertEquals(DataSourceConstant.DERBY, dataSource); }
@ConstantFunction(name = "bitxor", argTypes = {TINYINT, TINYINT}, returnType = TINYINT) public static ConstantOperator bitxorTinyInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createTinyInt((byte) (first.getTinyInt() ^ second.getTinyInt())); }
@Test public void bitxorTinyInt() { assertEquals(0, ScalarOperatorFunctions.bitxorTinyInt(O_TI_10, O_TI_10).getTinyInt()); }
@Override public Point calculatePositionForPreview( Keyboard.Key key, PreviewPopupTheme theme, int[] windowOffset) { Point point = new Point(key.x + windowOffset[0], key.y + windowOffset[1]); Rect padding = new Rect(); theme.getPreviewKeyBackground().getPadding(padding); point.offset((key.widt...
@Test public void testCalculatePositionForPreviewWithNoneExtendAnimation() throws Exception { mTheme.setPreviewAnimationType(PreviewPopupTheme.ANIMATION_STYLE_APPEAR); int[] offsets = new int[] {50, 60}; Point result = mUnderTest.calculatePositionForPreview(mTestKey, mTheme, offsets); Assert.assert...
public LiveMeasureDto toLiveMeasureDto(Measure measure, Metric metric, Component component) { LiveMeasureDto out = new LiveMeasureDto(); out.setMetricUuid(metric.getUuid()); out.setComponentUuid(component.getUuid()); out.setProjectUuid(treeRootHolder.getRoot().getUuid()); out.setValue(valueAsDouble(...
@Test public void toLiveMeasureDto() { treeRootHolder.setRoot(SOME_COMPONENT); LiveMeasureDto liveMeasureDto = underTest.toLiveMeasureDto( Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC, SOME_COMPONENT); assertThat(liveMeasureDto.getTextValue()).isEqualTo(Measu...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatShowConnectorPlugins() { // Given: final ListConnectorPlugins listConnectorPlugins = new ListConnectorPlugins(Optional.empty()); // When: final String formatted = SqlFormatter.formatSql(listConnectorPlugins); // Then: assertThat(formatted, is("SHOW CONNECTOR PLU...
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test(expected = KsqlException.class) public void shouldThrowExceptionForObjClass() { UdfUtil.getSchemaFromType(Object.class); }
@Override protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getChildChannelHandlers(MessageInput input) { final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>(); final CodecAggregator aggregator = getAggregator(); handlers.put("cha...
@Test public void getChildChannelHandlersGeneratesSelfSignedCertificates() { final Configuration configuration = new Configuration(ImmutableMap.of( "bind_address", "localhost", "port", 12345, "tls_enable", true) ); final AbstractTcpTransport transport = n...
@Override @Nullable public byte[] readByteArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray); }
@Test(expected = IncompatibleClassChangeError.class) public void testReadPortableArray_IncompatibleClass() throws Exception { reader.readByteArray("byte"); }
@Override public void write(int b) throws IOException { checkClosed(); if (chunkSize - currentBufferPointer <= 0) { expandBuffer(); } currentBuffer.put((byte) b); currentBufferPointer++; pointer++; if (pointer > size) { ...
@Test void testBufferSeek() throws IOException { try (RandomAccess randomAccessReadWrite = new RandomAccessReadWriteBuffer()) { byte[] bytes = new byte[RandomAccessReadBuffer.DEFAULT_CHUNK_SIZE_4KB]; randomAccessReadWrite.write(bytes); assertThrows(IOException...
public void start() throws IOException { this.start(new ArrayList<>()); }
@Test public void testCuratorFrameworkFactory() throws Exception{ // By not explicitly calling the NewZooKeeper method validate that the Curator override works. ZKClientConfig zkClientConfig = new ZKClientConfig(); Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.ZK_ADDRESS, ...
@Override public ConcurrentJobModificationResolveResult resolve(Job localJob, Job storageProviderJob) { if (localJob.getState() == StateName.SUCCEEDED && storageProviderJob.getState() == StateName.SUCCEEDED) { throw shouldNotHappenException("Should not happen as matches filter should be filterin...
@Test void ifJobSucceededWhileGoingToProcessingButThreadIsAlreadyRemoved() { final Job jobInProgress = aJobInProgress().build(); final Job jobInProgressWithUpdate = aCopyOf(jobInProgress).withMetadata("extra", "metadata").build(); final Job succeededJob = aCopyOf(jobInProgress).withSucceeded...
@Override public synchronized void execute() { boolean debugMode = conf.isLoadBalancerDebugModeEnabled() || log.isDebugEnabled(); if (debugMode) { log.info("Load balancer enabled: {}, Shedding enabled: {}.", conf.isLoadBalancerEnabled(), conf.isLoadBalancerSheddingEna...
@Test(timeOut = 30 * 1000) public void testDisableLoadBalancer() { AtomicReference<List<Metrics>> reference = new AtomicReference<>(); UnloadCounter counter = new UnloadCounter(); LoadManagerContext context = setupContext(); context.brokerConfiguration().setLoadBalancerEnabled(false)...
@PostConstruct public void init() { if (!environment.getAgentStatusEnabled()) { LOG.info("Agent status HTTP API server has been disabled."); return; } InetSocketAddress address = new InetSocketAddress(environment.getAgentStatusHostname(), environment.getAgentStatusPor...
@Test void shouldInitializeServerIfSettingIsTurnedOn() { try (MockedStatic<HttpServer> mockedStaticHttpServer = mockStatic(HttpServer.class)) { var serverSocket = setupAgentStatusParameters(); var spiedHttpServer = spy(HttpServer.class); when(spiedHttpServer.getAddress())...
public UiTopoLayout scale(double scale) { checkArgument(scaleWithinBounds(scale), E_SCALE_OOB); this.scale = scale; return this; }
@Test(expected = IllegalArgumentException.class) public void scaleTooSmall() { mkRootLayout(); layout.scale(0.0099); }
@Override public void doPush(String clientId, Subscriber subscriber, PushDataWrapper data) { pushService.pushWithoutAck(clientId, NotifySubscriberRequest.buildNotifySubscriberRequest(getServiceInfo(data, subscriber))); }
@Test void testDoPush() { pushExecutor.doPush(rpcClientId, subscriber, pushData); verify(pushService).pushWithoutAck(eq(rpcClientId), any(NotifySubscriberRequest.class)); }
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) { verifyAssigneesByUuid(assigneesByUuid); return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid)); }
@Test public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_shortName_of_dir_and_file_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root") .addChildren(ReportComponent.builder(DIRECTORY, 2).setUuid("dir1Uuid").setN...
@VisibleForTesting public ResultStore getResultStore() { return resultStore; }
@Test void testFetchResultInParallel() throws Exception { ResultFetcher fetcher = buildResultFetcher(Collections.singletonList(data.iterator()), data.size() / 2); CommonTestUtils.waitUtil( () -> fetcher.getResultStore().getBufferedRecordSize() > 0, Dur...
@Override public void run() { if (runnable != null) { runnable.run(); } else { try { callable.call(); } catch (Exception ex) { throw new RuntimeException(ex); } } }
@Test(expected = RuntimeException.class) public void callableExRun() throws Exception { CEx c = new CEx(); RunnableCallable rc = new RunnableCallable(c); rc.run(); }
@Override public boolean isOnSameNodeGroup(Node node1, Node node2) { if (node1 == null || node2 == null) { return false; } netlock.readLock().lock(); try { return isSameParents(node1, node2); } finally { netlock.readLock().unlock(); } }
@Test public void testNodeGroups() throws Exception { assertEquals(3, cluster.getNumOfRacks()); assertTrue(cluster.isOnSameNodeGroup(dataNodes[0], dataNodes[1])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[1], dataNodes[2])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[2], dataNodes[3])); ...
public static List<Event> computeEventDiff(final Params params) { final List<Event> events = new ArrayList<>(); emitPerNodeDiffEvents(createBaselineParams(params), events); emitWholeClusterDiffEvent(createBaselineParams(params), events); emitDerivedBucketSpaceStatesDiffEvents(params, ev...
@Test void enabling_distribution_config_in_state_bundle_emits_cluster_level_event() { var fixture = EventFixture.createForNodes(3) .clusterStateBefore("distributor:3 storage:3") .clusterStateAfter("distributor:3 storage:3") .distributionConfigBefore(null) ...
@Override public boolean register(final Application application) { try { if(finder.isInstalled(application)) { service.add(new FinderLocal(workspace.absolutePathForAppBundleWithIdentifier(application.getIdentifier()))); return true; } retur...
@Test @Ignore public void testRegister() { final SharedFileListApplicationLoginRegistry registry = new SharedFileListApplicationLoginRegistry(new LaunchServicesApplicationFinder()); final Application application = new Application("ch.sudo.cyberduck"); assertTrue(registry.register(applica...
public static Map<String, Task> getUserDefinedRealTaskMap(Workflow workflow) { return workflow.getTasks().stream() .filter(TaskHelper::isUserDefinedRealTask) .collect( Collectors.toMap( Task::getReferenceTaskName, Function.identity(), // it...
@Test public void testGetUserDefinedRealTaskMap() { when(workflow.getTasks()).thenReturn(Collections.singletonList(task)); when(task.getTaskType()).thenReturn(Constants.MAESTRO_TASK_NAME); when(task.getReferenceTaskName()).thenReturn("test-job"); Assert.assertEquals( Collections.singletonMap("...
@GetMapping("/switches") public SwitchDomain switches(HttpServletRequest request) { return switchDomain; }
@Test void testSwitchDomain() { SwitchDomain switchDomain = operatorController.switches(new MockHttpServletRequest()); assertEquals(this.switchDomain, switchDomain); }
@Override public Map<String, List<String>> getRequestTag(String path, String methodName, Map<String, List<String>> headers, Map<String, String[]> parameters, Keys keys) { Set<String> injectTags = keys.getInjectTags(); if (CollectionUtils.isEmpty(injectTags)) { // The staining...
@Test public void testGetRequestTag() { // Test matchTags as null Map<String, List<String>> requestTag = handler.getRequestTag("", "", null, null, new Keys(null, null)); Assert.assertEquals(requestTag, Collections.emptyMap()); // Test getLane returns null laneService.setRetu...
List<AlternativeInfo> calcAlternatives(final int s, final int t) { // First, do a regular bidirectional route search checkAlreadyRun(); init(s, 0, t, 0); runAlgo(); final Path bestPath = extractPath(); if (!bestPath.isFound()) { return Collections.emptyList();...
@Test public void testCalcOtherAlternatives() { BaseGraph g = createTestGraph(em); PMap hints = new PMap(); hints.putObject("alternative_route.max_weight_factor", 4); hints.putObject("alternative_route.local_optimality_factor", 0.5); hints.putObject("alternative_route.max_pat...
boolean isContainerizable() { String moduleSpecification = getProperty(PropertyNames.CONTAINERIZE); if (project == null || Strings.isNullOrEmpty(moduleSpecification)) { return true; } // modules can be specified in one of three ways: // 1) a `groupId:artifactId` // 2) an `:artifactId` ...
@Test public void testIsContainerizable_directory() { project.setGroupId("group"); project.setArtifactId("artifact"); Properties projectProperties = project.getProperties(); projectProperties.setProperty("jib.containerize", "project"); assertThat(testPluginConfiguration.isContainerizable()).isTru...
public double monitoredPercentage(Cluster cluster) { AggregationOptions<String, PartitionEntity> options = new AggregationOptions<>(0.0, 0.0, 1, ...
@Test public void testMonitoredPercentage() { TestContext ctx = setupScenario1(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals(1.0, aggregator.monitoredPercentage(clusterAndGener...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void setWebhook() throws IOException { String url = "https://google.com"; Integer maxConnections = 100; String[] allowedUpdates = {"message", "callback_query"}; String ipAddress = "1.1.1.1"; BaseResponse response = bot.execute(new SetWebhook() .ur...
public synchronized long calculateObjectSize(Object obj) { // Breadth-first traversal instead of naive depth-first with recursive // implementation, so we don't blow the stack traversing long linked lists. boolean init = true; try { for (;;) { visit(obj, init); init = false; ...
@Test public void testCircular() { Circular c1 = new Circular(); long size = mObjectSizeCalculator.calculateObjectSize(c1); c1.mCircular = c1; assertEquals(size, mObjectSizeCalculator.calculateObjectSize(c1)); }
@Override public ConfigOperateResult insertOrUpdateTagCas(final ConfigInfo configInfo, final String tag, final String srcIp, final String srcUser) { if (findConfigInfo4TagState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), tag) == null) { retu...
@Test void testInsertOrUpdateTagCasOfUpdate() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; String appName = "appname1234"; String content = "c12345"; ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName,...
@Override public OptionRule optionRule() { return OptionRule.builder() .required(SUBSCRIPTION_NAME, CLIENT_SERVICE_URL, ADMIN_SERVICE_URL) .optional( CURSOR_STARTUP_MODE, CURSOR_STOP_MODE, TOPIC_DISCOVERY...
@Test void optionRule() { PulsarSourceFactory pulsarSourceFactory = new PulsarSourceFactory(); OptionRule optionRule = pulsarSourceFactory.optionRule(); Assertions.assertNotNull(optionRule); }
public String computeFor(String serverId) { String jdbcUrl = config.get(JDBC_URL.getKey()).orElseThrow(() -> new IllegalStateException("Missing JDBC URL")); return DigestUtils.sha256Hex(serverId + "|" + jdbcUrlSanitizer.sanitize(jdbcUrl)); }
@Test public void test_checksum() { assertThat(computeFor("id1", "url1")) .isNotEmpty() .isEqualTo(computeFor("id1", "url1")) .isNotEqualTo(computeFor("id1", "url2")) .isNotEqualTo(computeFor("id2", "url1")) .isNotEqualTo(computeFor("id2", "url2")); }
public ConfigDef define(ConfigKey key) { if (configKeys.containsKey(key.name)) { throw new ConfigException("Configuration " + key.name + " is defined twice."); } if (key.group != null && !groups.contains(key.group)) { groups.add(key.group); } configKeys.pu...
@Test public void testDefinedTwice() { assertThrows(ConfigException.class, () -> new ConfigDef().define("a", Type.STRING, Importance.HIGH, "docs").define("a", Type.INT, Importance.HIGH, "docs")); }
public static boolean isMirrorServerSetAssignment(TableConfig tableConfig, InstancePartitionsType instancePartitionsType) { // If the instance assignment config is not null and the partition selector is // MIRROR_SERVER_SET_PARTITION_SELECTOR, return tableConfig.getInstanceAssignmentConfigMap() != nul...
@Test public void testIsMirrorServerSetAssignment() { Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = new HashMap<>(); instanceAssignmentConfigMap.put(InstancePartitionsType.OFFLINE.name(), getInstanceAssignmentConfig(InstanceAssignmentConfig.PartitionSelector.MIRROR_SERVER_SET_PAR...
public void execute() { Optional<String> login = configuration.get(CoreProperties.LOGIN); Optional<String> password = configuration.get(CoreProperties.PASSWORD); String warningMessage = null; if (password.isPresent()) { warningMessage = PASSWORD_WARN_MESSAGE; } else if (login.isPresent()) { ...
@Test public void execute_whenNotUsingLoginOrPassword_shouldNotAddWarning() { underTest.execute(); verifyNoInteractions(analysisWarnings); Assertions.assertThat(logger.logs(Level.WARN)).isEmpty(); }
public static Point<AriaCsvHit> parsePointFromAriaCsv(String rawCsvText) { AriaCsvHit ariaHit = AriaCsvHit.from(rawCsvText); Position pos = new Position(ariaHit.time(), ariaHit.latLong(), ariaHit.altitude()); return new Point<>(pos, null, ariaHit.linkId(), ariaHit); }
@Test public void exampleParsing_noExtraData() { String rawCsv = ",,2018-03-24T14:41:09.371Z,vehicleIdNumber,42.9525,-83.7056,2700"; Point<AriaCsvHit> pt = AriaCsvHits.parsePointFromAriaCsv(rawCsv); assertThat(pt.time(), is(Instant.parse("2018-03-24T14:41:09.371Z"))); assertThat(p...
@Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList()); response.remov...
@Test public void testInterceptorMultipleHeaderFilteredWarningAndMultipleTriggers() throws IOException, HttpException { ElasticsearchFilterDeprecationWarningsInterceptor interceptor = new ElasticsearchFilterDeprecationWarningsInterceptor(); HttpResponse response = new BasicHttpResponse(new BasicSta...
public static InputStream getResourceAsStream(String resource) throws IOException { ClassLoader loader = ResourceUtils.class.getClassLoader(); return getResourceAsStream(loader, resource); }
@Test void testGetResourceAsStreamForClasspath() throws IOException { try (InputStream inputStream = ResourceUtils.getResourceAsStream("test-tls-cert.pem")) { assertNotNull(inputStream); } }
public int boundedControlledPoll( final ControlledFragmentHandler handler, final long limitPosition, final int fragmentLimit) { if (isClosed) { return 0; } long initialPosition = subscriberPosition.get(); if (initialPosition >= limitPosition) { ...
@Test void shouldPollFragmentsToBoundedControlledFragmentHandlerWithMaxPositionBeforeNextMessage() { final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID); final long maxPosition = initialPosition + ALIGNED_FRAME_LENGTH; position.setOrd...
public static void assignFieldParams(Object bean, Map<String, Param> params) throws TikaConfigException { Class<?> beanClass = bean.getClass(); if (!PARAM_INFO.containsKey(beanClass)) { synchronized (TikaConfig.class) { if (!PARAM_INFO.containsKey(beanClass)) { ...
@Test public void testParamValueInheritance() { class Bean { @Field(required = true) CharSequence field; } Bean parser = new Bean(); Map<String, Param> params = new HashMap<>(); try { String val = "someval"; params.put("field"...
@Override public Collection<DatabasePacket> execute() { failedIfContainsMultiStatements(); MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts(); SQLParserRule sqlParserRule = metaDataContexts.getMetaData().getGlobalRuleMetaData().getSingleR...
@Test void assertPrepareMultiStatements() { when(packet.getSQL()).thenReturn("update t set v=v+1 where id=1;update t set v=v+1 where id=2;update t set v=v+1 where id=3"); when(connectionSession.getAttributeMap().hasAttr(MySQLConstants.OPTION_MULTI_STATEMENTS_ATTRIBUTE_KEY)).thenReturn(true); ...
public static void updateFinalModifierField(Field field) { final Field modifiersField = getField(Field.class, "modifiers"); if (modifiersField != null) { try { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } catch (IllegalAccessException ex...
@Test public void updateFinalModifierField() throws NoSuchFieldException { final Field finalField = TestReflect.class.getDeclaredField("finalField"); Assert.assertTrue(Modifier.isFinal(finalField.getModifiers())); ReflectUtils.updateFinalModifierField(finalField); }
public static boolean isNumber(String str) { return isNotEmpty(str) && NUM_PATTERN.matcher(str).matches(); }
@Test void testIsInteger() throws Exception { assertFalse(StringUtils.isNumber(null)); assertFalse(StringUtils.isNumber("")); assertTrue(StringUtils.isNumber("123")); }
@Override protected Result[] run(String value) { final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly); // the extractor instance is rebuilt every second anyway final Match match = grok.match(value); final Map<String, Object> matches = matc...
@Test public void testNamedCapturesOnly() { final Map<String, Object> config = new HashMap<>(); final GrokPattern mynumber = GrokPattern.create("MYNUMBER", "(?:%{BASE10NUM})"); patternSet.add(mynumber); config.put("named_captures_only", true); final GrokExtractor extractor...
@Override public void event(IntentEvent event) { // this is the fast path for CORRUPT intents, retry on event notification. //TODO we might consider using the timer to back off for subsequent retries if (enabled && event.type() == IntentEvent.Type.CORRUPT) { Key key = event.subje...
@Test public void corruptEventThreshold() { IntentStoreDelegate mockDelegate = new IntentStoreDelegate() { @Override public void process(IntentData intentData) { intentData.setState(CORRUPT); intentData.setErrorCount(cleanup.retryThreshold); ...
void fetchAndRunCommands() { lastPollTime.set(clock.instant()); final List<QueuedCommand> commands = commandStore.getNewCommands(NEW_CMDS_TIMEOUT); if (commands.isEmpty()) { if (!commandTopicExists.get()) { commandTopicDeleted = true; } return; } final List<QueuedCommand> ...
@Test public void shouldPullAndRunStatements() { // Given: givenQueuedCommands(queuedCommand1, queuedCommand2, queuedCommand3); // When: commandRunner.fetchAndRunCommands(); // Then: final InOrder inOrder = inOrder(statementExecutor); inOrder.verify(statementExecutor).handleStatement(que...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final String msg = new String(rawMessage.getPayload(), charset); try (Timer.Context ignored = this.decodeTime.time()) { final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress(); f...
@Test public void testFortiGateFirewall() { final RawMessage rawMessage = buildRawMessage("<45>date=2017-03-06 time=12:53:10 devname=DEVICENAME devid=DEVICEID logid=0000000013 type=traffic subtype=forward level=notice vd=ALIAS srcip=IP srcport=45748 srcintf=\"IF\" dstip=IP dstport=443 dstintf=\"IF\" session...
@Deprecated public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) { return Task.callable(name, () -> callable.call()); }
@Test public void testTimeoutTaskWithoutTimeout() throws InterruptedException { final String value = "value"; final Task<String> task = Task.callable("task", () -> value); final Task<String> timeoutTask = task.withTimeout(200, TimeUnit.MILLISECONDS); runAndWait("TestTasks.testTimeoutTaskWithoutTimeo...
public void setName(String name) throws IllegalStateException { if (name != null && name.equals(this.name)) { return; // idempotent naming } if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { this.name = name; } else { throw new IllegalStateExc...
@Test public void idempotentNameTest() { context.setName("hello"); context.setName("hello"); }
public static int getDigit(final int index, final byte value) { if (value < 0x30 || value > 0x39) { throw new AsciiNumberFormatException("'" + ((char)value) + "' is not a valid digit @ " + index); } return value - 0x30; }
@Test void shouldThrowExceptionWhenDecodingByteNonNumericValue() { assertThrows(AsciiNumberFormatException.class, () -> AsciiEncoding.getDigit(0, (byte)'a')); }
@Override public CloudConfiguration getCloudConfiguration() { return hdfsEnvironment.getCloudConfiguration(); }
@Test public void testGetCloudConfiguration() { CloudConfiguration cc = metadata.getCloudConfiguration(); Assert.assertEquals(cc.getCloudType(), CloudType.DEFAULT); }
public void addOrReplaceSlaveServer( SlaveServer slaveServer ) { int index = slaveServers.indexOf( slaveServer ); if ( index < 0 ) { slaveServers.add( slaveServer ); } else { SlaveServer previous = slaveServers.get( index ); previous.replaceMeta( slaveServer ); } setChanged(); }
@Test public void testAddOrReplaceSlaveServer() { // meta.addOrReplaceSlaveServer() right now will fail with an NPE assertNull( meta.getSlaveServers() ); List<SlaveServer> slaveServers = new ArrayList<>(); meta.setSlaveServers( slaveServers ); assertNotNull( meta.getSlaveServers() ); SlaveServ...
@Override @Transactional(rollbackFor = Exception.class) public void deleteCodegen(Long tableId) { // 校验是否已经存在 if (codegenTableMapper.selectById(tableId) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 删除 table 表定义 codegenTableMapper.deleteById(tabl...
@Test public void testDeleteCodegen_success() { // mock 数据 CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(table); CodegenColumnDO column = randomPojo(CodegenColumnDO.class, o -> o....
@Override public Long getLong(final int columnIndex) { return values.getLong(columnIndex - 1); }
@Test public void shouldGetLong() { assertThat(row.getLong("f_long"), is(1234L)); assertThat(row.getLong("f_int"), is(2L)); }
@VisibleForTesting void validateCaptcha(AuthLoginReqVO reqVO) { // 如果验证码关闭,则不进行校验 if (!captchaEnable) { return; } // 校验验证码 ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class); CaptchaVO captchaVO = new CaptchaVO(); capt...
@Test public void testValidateCaptcha_successWithEnable() { // 准备参数 AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); // mock 验证码打开 ReflectUtil.setFieldValue(authService, "captchaEnable", true); // mock 验证通过 when(captchaService.verification(argThat(captchaVO -...
public ParResponse requestPushedUri( URI pushedAuthorizationRequestUri, ParBodyBuilder parBodyBuilder) { var headers = List.of( new Header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON), new Header(HttpHeaders.CONTENT_TYPE, UrlFormBodyBuilder.MEDIA_TYPE)); var req = new ...
@Test void requestPushedUri(WireMockRuntimeInfo wm) { var body = """ { "request_uri":"https://example.com/auth/login", "expires_in": 600 } """ .getBytes(StandardCharsets.UTF_8); var path = "/auth/par"; stubFor(post(path).willReturn(created(...
@Override public Set<MappedFieldTypeDTO> fieldTypesByStreamIds(Collection<String> streamIds, TimeRange timeRange) { final Set<String> indexSets = streamService.indexSetIdsByIds(streamIds); final Set<String> indexNames = this.indexLookup.indexNamesForStreamsInTimeRange(ImmutableSet.copyOf(streamIds),...
@Test public void requestsFieldTypesForRequestedTimeRange() throws Exception { this.mappedFieldTypesService.fieldTypesByStreamIds(Collections.singleton("stream1"), AbsoluteRange.create("2010-05-17T23:28:14.000+02:00", "2021-05-05T12:09:23.213+02:00")); verify(this.indexLookup, times(1)).indexNamesF...
@Override @Transactional(rollbackFor = Exception.class) public void updateCodegen(CodegenUpdateReqVO updateReqVO) { // 校验是否已经存在 if (codegenTableMapper.selectById(updateReqVO.getTable().getId()) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 校验主表字段存在 ...
@Test public void testUpdateCodegen_success() { // mock 数据 CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setTemplateType(CodegenTemplateTypeEnum.ONE.getType()) .setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(ta...
@Override public ShardingAlgorithm getShardingAlgorithm() { return null; }
@Test void assertDoSharding() { assertNull(noneShardingStrategy.getShardingAlgorithm()); }
@Override public void processElement(StreamRecord<E> element) throws Exception { final E externalRecord = element.getValue(); final Object internalRecord; try { internalRecord = converter.toInternal(externalRecord); } catch (Exception e) { throw new FlinkRunt...
@Test public void testInvalidRecords() { final InputConversionOperator<Row> operator = new InputConversionOperator<>( createConverter(DataTypes.ROW(DataTypes.FIELD("f", DataTypes.INT()))), false, false, ...
public PrimitiveValue minValue() { return minValue; }
@Test void shouldReturnDefaultMinValueWhenSpecified() throws Exception { final String testXmlString = "<types>" + " <type name=\"testTypeDefaultCharMinValue\" primitiveType=\"char\"/>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types...
public static <T> RestResult<T> failedWithMsg(int code, String errMsg) { return RestResult.<T>builder().withCode(code).withMsg(errMsg).build(); }
@Test void testFailedWithMsg() { RestResult<String> restResult = RestResultUtils.failed("test"); assertRestResult(restResult, 500, "test", null, false); }
public EventDefinitionDto update(EventDefinitionDto updatedEventDefinition, boolean schedule) { // Grab the old record so we can revert to it if something goes wrong final Optional<EventDefinitionDto> oldEventDefinition = eventDefinitionService.get(updatedEventDefinition.id()); final EventDefin...
@Test @MongoDBFixtures("event-processors.json") public void updateWithErrors() { final String newTitle = "A NEW TITLE " + DateTime.now(DateTimeZone.UTC).toString(); final String newDescription = "A NEW DESCRIPTION " + DateTime.now(DateTimeZone.UTC).toString(); final EventDefinitionDto e...
@Override public Client getClient(String clientId) { return getClientManagerById(clientId).getClient(clientId); }
@Test void testChooseConnectionClientForV6() { delegate.getClient(connectionIdForV6); verify(connectionBasedClientManager).getClient(connectionIdForV6); verify(ephemeralIpPortClientManager, never()).getClient(connectionIdForV6); verify(persistentIpPortClientManager, never()).getClien...
public static SimpleImputer fit(DataFrame data, String... columns) { return fit(data, 0.5, 0.5, columns); }
@Test public void testLongley() throws Exception { System.out.println(Longley.data); SimpleImputer imputer = SimpleImputer.fit(Longley.data); System.out.println(imputer); }
@Override public void preflight(final Path source, final Path target) throws BackgroundException { // defaults to Acl.EMPTY (disabling role checking) if target does not exist assumeRole(target, WRITEPERMISSION); // no createfilespermission required for now if(source.isDirectory()) { ...
@Test public void testPreflightFileAccessDeniedTargetExistsNotWritableCustomProps() throws Exception { final Path source = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); source.setAttributes(source.attributes().with...
@Override public Num calculate(BarSeries series, Position position) { final Num maxDrawdown = maxDrawdownCriterion.calculate(series, position); if (maxDrawdown.isZero()) { return NaN.NaN; } else { final Num totalProfit = grossReturnCriterion.calculate(series, position...
@Test public void testNoDrawDownForPosition() { final MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 95, 100, 90, 95, 80, 120); final Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(1, series)); final Num result = rrc.calculate(series, position); ...
@Override public Object decrypt(final Object cipherValue, final AlgorithmSQLContext algorithmSQLContext) { return cryptographicAlgorithm.decrypt(cipherValue); }
@Test void assertDecrypt() { Object actual = encryptAlgorithm.decrypt("dSpPiyENQGDUXMKFMJPGWA==", mock(AlgorithmSQLContext.class)); assertThat(actual.toString(), is("test")); }
public static String filenameOnly( String sFullPath ) { if ( Utils.isEmpty( sFullPath ) ) { return sFullPath; } int idx = sFullPath.lastIndexOf( FILE_SEPARATOR ); if ( idx != -1 ) { return sFullPath.substring( idx + 1 ); } else { idx = sFullPath.lastIndexOf( '/' ); // URL, VFS/**/...
@Test public void testFilenameOnly() { assertNull( Const.filenameOnly( null ) ); assertTrue( Const.filenameOnly( "" ).isEmpty() ); assertEquals( "file.txt", Const.filenameOnly( "dir" + Const.FILE_SEPARATOR + "file.txt" ) ); assertEquals( "file.txt", Const.filenameOnly( "file.txt" ) ); }
@Override public int offer(E e) { @SuppressWarnings("deprecation") long z = mix64(Thread.currentThread().getId()); int increment = ((int) (z >>> 32)) | 1; int h = (int) z; int mask; int result; Buffer<E> buffer; boolean uncontended = true; Buffer<E>[] buffers = table; if ((buf...
@Test @SuppressWarnings("ThreadPriorityCheck") public void expand_concurrent() { var buffer = new FakeBuffer<Boolean>(Buffer.FAILED); ConcurrentTestHarness.timeTasks(10 * NCPU, () -> { for (int i = 0; i < 1000; i++) { assertThat(buffer.offer(Boolean.TRUE)).isAnyOf(Buffer.SUCCESS, Buffer.FULL, ...
public Set<String> errorLogDirs() { return errorLogDirs; }
@Test public void testErrorLogDirsForFoo() { assertEquals(new HashSet<>(Collections.singletonList("/tmp/error3")), FOO.errorLogDirs()); }
@ConstantFunction(name = "int_divide", argTypes = {INT, INT}, returnType = INT) public static ConstantOperator intDivideInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createInt(first.getInt() / second.getInt()); }
@Test public void intDivideInt() { assertEquals(1, ScalarOperatorFunctions.intDivideInt(O_INT_10, O_INT_10).getInt()); }
static void closeSilently( final ServerWebSocket webSocket, final int code, final String message) { try { final ImmutableMap<String, String> finalMessage = ImmutableMap.of( "error", message != null ? message : "" ); final String json = ApiJsonMapper.INSTANCE.g...
@Test public void shouldNotTruncateShortReasons() throws Exception { // Given: final String reason = "some short reason"; // When: SessionUtil.closeSilently(websocket, INVALID_MESSAGE_TYPE.code(), reason); // Then: verify(websocket).writeFinalTextFrame(any(String.class), any(Handler.class));...
public static <T> Window<T> into(WindowFn<? super T, ?> fn) { try { fn.windowCoder().verifyDeterministic(); } catch (NonDeterministicException e) { throw new IllegalArgumentException("Window coders must be deterministic.", e); } return Window.<T>configure().withWindowFn(fn); }
@Test public void testNonDeterministicWindowCoder() throws NonDeterministicException { FixedWindows mockWindowFn = Mockito.mock(FixedWindows.class); @SuppressWarnings({"unchecked", "rawtypes"}) Class<Coder<IntervalWindow>> coderClazz = (Class) Coder.class; Coder<IntervalWindow> mockCoder = Mockito.moc...
public void registerOnline(final ComputeNodeInstance computeNodeInstance) { String instanceId = computeNodeInstance.getMetaData().getId(); repository.persistEphemeral(ComputeNode.getOnlineInstanceNodePath(instanceId, computeNodeInstance.getMetaData().getType()), YamlEngine.marshal( new Y...
@Test void assertRegisterOnline() { ComputeNodeInstance computeNodeInstance = new ComputeNodeInstance(new ProxyInstanceMetaData("foo_instance_id", 3307)); computeNodeInstance.getLabels().add("test"); new ComputeNodePersistService(repository).registerOnline(computeNodeInstance); verif...