focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Opt<T> peek(Consumer<T> action) throws NullPointerException { Objects.requireNonNull(action); if (isEmpty()) { return Opt.empty(); } action.accept(value); return this; }
@Test public void peekTest() { User user = new User(); // 相当于ifPresent的链式调用 Opt.ofNullable("hutool").peek(user::setUsername).peek(user::setNickname); assertEquals("hutool", user.getNickname()); assertEquals("hutool", user.getUsername()); // 注意,传入的lambda中,对包裹内的元素执行赋值操作并不会影响到原来的元素 String name = Opt.ofNull...
@Override public void storeChanged(Store store) { var contentStore = (ContentStore) store; content = contentStore.getContent(); render(); }
@Test void testStoreChanged() { final var store = mock(ContentStore.class); when(store.getContent()).thenReturn(Content.PRODUCTS); final var view = new ContentView(); view.storeChanged(store); verify(store, times(1)).getContent(); verifyNoMoreInteractions(store); }
@Override public RFuture<Boolean> tryLockAsync(long threadId) { RFuture<Long> longRFuture = tryAcquireAsync(-1, null, threadId); CompletionStage<Boolean> f = longRFuture.thenApply(res -> res == null); return new CompletableFutureWrapper<>(f); }
@Test public void testTryLockAsync() throws InterruptedException { RLock lock = redisson.getSpinLock("lock"); lock.lock(); AtomicBoolean lockAsyncSucceed = new AtomicBoolean(); Thread thread = new Thread(() -> { RFuture<Void> booleanRFuture = lock.lockAsync(); ...
@Override public CompletionStage<Set<String>> getAllUsers() { LOGGER.debugOp("Searching for Users with any ACL rules"); Set<String> users = new HashSet<>(); Set<String> ignored = new HashSet<>(IGNORED_USERS.size()); Enumeration<String> keys = cache.keys(); while (keys.hasMo...
@Test public void testGetAllUsers() throws ExecutionException, InterruptedException { Admin mockAdminClient = mock(AdminClient.class); ResourcePattern res1 = new ResourcePattern(ResourceType.TOPIC, "my-topic", PatternType.LITERAL); ResourcePattern res2 = new ResourcePattern(ResourceType.GRO...
@Override @Nonnull public <T extends DataConnection> T getAndRetainDataConnection(String name, Class<T> clazz) { DataConnectionEntry dataConnection = dataConnections.computeIfPresent(name, (k, v) -> { if (!clazz.isInstance(v.instance)) { throw new HazelcastException("Data con...
@Test public void should_throw_when_data_connection_does_not_exist() { assertThatThrownBy(() -> dataConnectionService.getAndRetainDataConnection("does-not-exist", JdbcDataConnection.class)) .isInstanceOf(HazelcastException.class) .hasMessageContaining("Data connection 'does-n...
@Bean public TimerRegistry timerRegistry( TimerConfigurationProperties timerConfigurationProperties, EventConsumerRegistry<TimerEvent> timerEventConsumerRegistry, RegistryEventConsumer<Timer> timerRegistryEventConsumer, @Qualifier("compositeTimerCustomizer") Composite...
@Test public void shouldConfigureInstancesUsingCustomDefaultConfig() { InstanceProperties defaultProperties = new InstanceProperties() .setMetricNames("resilience4j.timer.default") .setOnFailureTagResolver(FixedOnFailureTagResolver.class); InstanceProperties instanceP...
@Override public DataflowPipelineJob run(Pipeline pipeline) { // Multi-language pipelines and pipelines that include upgrades should automatically be upgraded // to Runner v2. if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) { List<String> experiments = fi...
@Test public void testSettingAnyFnApiExperimentEnablesUnifiedWorker() throws Exception { for (String experiment : ImmutableList.of( "beam_fn_api", "use_runner_v2", "use_unified_worker", "use_portable_job_submission")) { DataflowPipelineOptions options = buildPipelineOptions(); Expe...
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void query_without_any_parameter() { SearchRequest request = new SearchRequest(); IssueQuery query = underTest.create(request); assertThat(query.componentUuids()).isEmpty(); assertThat(query.projectUuids()).isEmpty(); assertThat(query.directories()).isEmpty(); assertThat(query.f...
@Override public ResultSet executeQuery(String sql) throws SQLException { validateState(); try { if (!DriverUtils.queryContainsLimitStatement(sql)) { sql += " " + LIMIT_STATEMENT + " " + _maxRows; } String enabledSql = DriverUtils.enableQueryOptions(sql, _connection.getQueryOpt...
@Test public void testExecuteQuery() throws Exception { PinotConnection connection = new PinotConnection("dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTransport); Statement statement = new PinotStatement(connection); ResultSet resultSet = statement.executeQuery(BASIC_TES...
@Override public ResultSet getFunctions(final String catalog, final String schemaPattern, final String functionNamePattern) throws SQLException { return createDatabaseMetaDataResultSet(getDatabaseMetaData().getFunctions(getActualCatalog(catalog), getActualSchema(schemaPattern), functionNamePattern)); }
@Test void assertGetFunctions() throws SQLException { when(databaseMetaData.getFunctions("test", null, null)).thenReturn(resultSet); assertThat(shardingSphereDatabaseMetaData.getFunctions("test", null, null), instanceOf(DatabaseMetaDataResultSet.class)); }
@Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (chain.length == 0 || this.trustedFingerprints.isEmpty()) { return false; } final MessageDigest sha256Digest = sha256(); // traverse up the chain until we find one whose fingerprin...
@Test public void testIsTrustedWhenNoMatchingCertificateIsOnTheChain() throws CertificateException { final CATrustedFingerprintTrustStrategy trustStrategy = new CATrustedFingerprintTrustStrategy("abad1deaabad1deaabad1deaabad1deaabad1deaabad1deaabad1deaabad1dea", ()-> DATE_CERTS_VALID); final X509Cer...
@ManagedOperation(description = "Subscribe for dynamic routing with a predicate expression") public String subscribeWithPredicateExpression( String subscribeChannel, String subscriptionId, String destinationUri, int priority, String predicate, ...
@Test void subscribeWithPredicateExpression() { service.subscribeWithPredicateExpression(subscribeChannel, subscriptionId, destinationUri, priority, predicateExpression, expressionLanguage, false); Mockito.verify(filterService, Mockito.times(1)) .addFilterForChannel( ...
public static ErrorResponse fromJson(int code, String json) { return JsonUtil.parse(json, node -> OAuthErrorResponseParser.fromJson(code, node)); }
@Test public void testOAuthErrorResponseFromJsonWithNulls() { String error = OAuth2Properties.INVALID_CLIENT_ERROR; String json = String.format("{\"error\":\"%s\"}", error); ErrorResponse expected = ErrorResponse.builder().responseCode(400).withType(error).build(); assertEquals(expected, OAuthErrorRes...
public CompletableFuture<QueryAssignmentResponse> queryAssignment(ProxyContext ctx, QueryAssignmentRequest request) { CompletableFuture<QueryAssignmentResponse> future = new CompletableFuture<>(); try { validateTopicAndConsumerGroup(request.getTopic(), request.getGroup()); ...
@Test public void testQueryAssignment() throws Throwable { when(this.messagingProcessor.getTopicRouteDataForProxy(any(), any(), anyString())) .thenReturn(createProxyTopicRouteData(2, 2, 6)); QueryAssignmentResponse response = this.routeActivity.queryAssignment( createContext...
public BigDecimal calculateProductGramsForRequiredFiller(Filler filler, BigDecimal fillerGrams) { if (filler == null || fillerGrams == null || fillerGrams.doubleValue() <= 0) { return BigDecimal.valueOf(0); } if (filler.equals(Filler.PROTEIN)) { return calculateProductGr...
@Test void calculateProductGramsForRequiredFiller_zeroValue() { BigDecimal result = product.calculateProductGramsForRequiredFiller(Filler.CARBOHYDRATE, BigDecimal.valueOf(0)); assertEquals(BigDecimal.valueOf(0), result); }
public static Permission getPermission(String name, String serviceName, String... actions) { PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName); if (permissionFactory == null) { throw new IllegalArgumentException("No permissions found for service: " + serviceName);...
@Test public void getPermission_Set() { Permission permission = ActionConstants.getPermission("foo", SetService.SERVICE_NAME); assertNotNull(permission); assertTrue(permission instanceof SetPermission); }
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) { IClientConfig clientConfig = getRequestClientConfig(request); Long originTimeout = getOriginReadTimeout(); Long requestTimeout = getRequestReadTimeout(clientConfig); long computedTimeout; if (origin...
@Test void computeReadTimeout_originOnly() { originConfig.set(CommonClientConfigKey.ReadTimeout, 1000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(1000, timeout.toMillis()); }
public static String fix(final String raw) { if ( raw == null || "".equals( raw.trim() )) { return raw; } MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( raw ); }
@Test public void testAssertLogical() { final String raw = "some code; insertLogical(new String(\"foo\"));\n More();"; final String result = "some code; drools.insertLogical(new String(\"foo\"));\n More();"; assertEqualsIgnoreWhitespace( result, Knowledg...
protected String decrypt(String encryptedStr) throws Exception { String[] split = encryptedStr.split(":"); checkTrue(split.length == 3, "Wrong format of the encrypted variable (" + encryptedStr + ")"); byte[] salt = Base64.getDecoder().decode(split[0].getBytes(StandardCharsets.UTF_8)); c...
@Test(expected = IllegalArgumentException.class) public void testDecryptionFailWithNullPassword() throws Exception { assumeDefaultAlgorithmsSupported(); AbstractPbeReplacer replacer = createAndInitReplacer(null, new Properties()); replacer.decrypt("aSalt1xx:1:test"); }
@Override public void onResignation( int groupMetadataPartitionIndex, OptionalInt groupMetadataPartitionLeaderEpoch ) { throwIfNotActive(); runtime.scheduleUnloadOperation( new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupMetadataPartitionIndex), g...
@Test public void testOnResignation() { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, new GroupCoordinator...
@Override public boolean isSingleton() { return true; }
@Test public final void isSingletonShouldAlwaysReturnTrue() { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); assertTrue( "isSingleton() should always return true since each AbstractRemoteCacheManagerFactory will always produce "...
@VisibleForTesting void removeDisableUsers(Set<Long> assigneeUserIds) { if (CollUtil.isEmpty(assigneeUserIds)) { return; } Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(assigneeUserIds); assigneeUserIds.removeIf(id -> { AdminUserRespDTO user = ...
@Test public void testRemoveDisableUsers() { // 准备参数. 1L 可以找到;2L 是禁用的;3L 找不到 Set<Long> assigneeUserIds = asSet(1L, 2L, 3L); // mock 方法 AdminUserRespDTO user1 = randomPojo(AdminUserRespDTO.class, o -> o.setId(1L) .setStatus(CommonStatusEnum.ENABLE.getStatus())); ...
@Override protected int command() { if (!validateConfigFilePresent()) { return 1; } final MigrationConfig config; try { config = MigrationConfig.load(getConfigFile()); } catch (KsqlException | MigrationException e) { LOGGER.error(e.getMessage()); return 1; } retur...
@Test public void shouldApplySecondMigration() throws Exception { // Given: command = PARSER.parse("-n"); createMigrationFile(1, NAME, migrationsDir, COMMAND); createMigrationFile(3, NAME, migrationsDir, COMMAND); givenCurrentMigrationVersion("1"); givenAppliedMigration(1, NAME, MigrationState...
@Override public Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) { val webContext = ctx.webContext(); var computeLoginUrl = configuration.computeFinalLoginUrl(webContext); val computedCallbackUrl = client.computeFinalCallbackUrl(webContext); val renew = conf...
@Test public void testRedirectForSAMLProtocol() { val config = new CasConfiguration(); config.setProtocol(CasProtocol.SAML); val builder = newBuilder(config); val action = builder.getRedirectionAction(new CallContext(MockWebContext.create(), new MockSessionStore())).get(); as...
static void setConstructor(final MiningModelCompilationDTO compilationDTO, final ClassOrInterfaceDeclaration modelTemplate) { KiePMMLModelFactoryUtils.init(compilationDTO, modelTemplate); final ConstructorDeclaration constructorDeclaration = modelTemplate.g...
@Test void setConstructor() { PMML_MODEL pmmlModel = PMML_MODEL.byName(MINING_MODEL.getClass().getSimpleName()); final ClassOrInterfaceDeclaration modelTemplate = MODEL_TEMPLATE.clone(); MINING_FUNCTION miningFunction = MINING_FUNCTION.byName(MINING_MODEL.getMiningFunction().value()); ...
@Override public String generateSqlType(Dialect dialect) { return switch (dialect.getId()) { case PostgreSql.ID, H2.ID -> "INTEGER"; case MsSql.ID -> "INT"; case Oracle.ID -> "NUMBER(38,0)"; default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId()); }; ...
@Test public void generateSqlType_for_Oracle() { assertThat(underTest.generateSqlType(new Oracle())).isEqualTo("NUMBER(38,0)"); }
@SuppressWarnings("unchecked") public static int compare(Comparable lhs, Comparable rhs) { Class lhsClass = lhs.getClass(); Class rhsClass = rhs.getClass(); assert lhsClass != rhsClass; assert lhs instanceof Number; assert rhs instanceof Number; Number lhsNumber = (N...
@SuppressWarnings("ConstantConditions") @Test(expected = Throwable.class) public void testNullLhsInCompareThrows() { compare(null, 1); }
@Override public int hashCode() { return new HashCodeBuilder(5, 71) .append(versionParts) .toHashCode(); }
@Test public void testHashCode() { DependencyVersion instance = new DependencyVersion("3.2.1"); int expResult = 80756; int result = instance.hashCode(); assertEquals(expResult, result); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Optional handling") public void testTicket3624() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Service.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /example/model:\n" + " get:\...
public boolean evaluateIfActiveVersion(UpdateCenter updateCenter) { Version installedVersion = Version.create(sonarQubeVersion.get().toString()); if (compareWithoutPatchVersion(installedVersion, updateCenter.getSonar().getLtaVersion().getVersion()) == 0) { return true; } SortedSet<Release> allRel...
@Test void evaluateIfActiveVersion_whenNoPreviousReleasesFound_shouldThrowIllegalStateException() { when(sonarQubeVersion.get()).thenReturn(parse("10.4.1")); TreeSet<Release> releases = new TreeSet<>(); releases.add(new Release(sonar, Version.create("10.4.1"))); when(sonar.getAllReleases()).thenRetur...
@Override public Optional<CompletableFuture<TaskManagerLocation>> getTaskManagerLocation( ExecutionVertexID executionVertexId) { ExecutionVertex ev = getExecutionVertex(executionVertexId); if (ev.getExecutionState() != ExecutionState.CREATED) { return Optional.of(ev.getCurre...
@Test void testGetEmptyTaskManagerLocationIfVertexNotScheduled() throws Exception { final JobVertex jobVertex = ExecutionGraphTestUtils.createNoOpVertex(1); final ExecutionGraph eg = ExecutionGraphTestUtils.createExecutionGraph( EXECUTOR_EXTENSION.getExecutor...
public static List<TraceContext> decoderFromTraceDataString(String traceData) { List<TraceContext> resList = new ArrayList<>(); if (traceData == null || traceData.length() <= 0) { return resList; } String[] contextList = traceData.split(String.valueOf(TraceConstants.FIELD_SPL...
@Test public void testDecoderFromTraceDataString() { List<TraceContext> contexts = TraceDataEncoder.decoderFromTraceDataString(traceData); Assert.assertEquals(contexts.size(), 1); Assert.assertEquals(contexts.get(0).getTraceType(), TraceType.Pub); }
public static List<TargetInfo> parseOptTarget(CommandLine cmd, AlluxioConfiguration conf) throws IOException { String[] targets; if (cmd.hasOption(TARGET_OPTION_NAME)) { String argTarget = cmd.getOptionValue(TARGET_OPTION_NAME); if (StringUtils.isBlank(argTarget)) { throw new IOExcepti...
@Test public void parseZooKeeperHAJobMasterTarget() throws Exception { mConf.set(PropertyKey.ZOOKEEPER_ENABLED, true); mConf.set(PropertyKey.ZOOKEEPER_ADDRESS, "masters-1:2181"); CommandLine mockCommandLine = mock(CommandLine.class); String[] mockArgs = new String[]{"--target", "job_master"}; whe...
public static String getGroupKey(ThreadPoolParameter parameter) { return StringUtil.createBuilder() .append(parameter.getTpId()) .append(Constants.GROUP_KEY_DELIMITER) .append(parameter.getItemId()) .append(Constants.GROUP_KEY_DELIMITER) ...
@Test public void assertGetGroupKeys() { String testText = "message-consume+dynamic-threadpool-example+prescription"; String groupKey = ContentUtil.getGroupKey("message-consume", "dynamic-threadpool-example", "prescription"); Assert.isTrue(testText.equals(groupKey)); }
public static String getExactlyExpression(final String value) { return Strings.isNullOrEmpty(value) ? value : CharMatcher.anyOf(" ").removeFrom(value); }
@Test void assertGetExactlyExpression() { assertThat(SQLUtils.getExactlyExpression("((a + b*c))"), is("((a+b*c))")); }
@Override protected void write(final MySQLPacketPayload payload) { payload.writeInt4(timestamp); payload.writeInt1(eventType); payload.writeInt4(serverId); payload.writeInt4(eventSize); payload.writeInt4(logPos); payload.writeInt2(flags); }
@Test void assertWrite() { new MySQLBinlogEventHeader(1234567890, MySQLBinlogEventType.UNKNOWN_EVENT.getValue(), 123456, 19, 4, MySQLBinlogEventFlag.LOG_EVENT_BINLOG_IN_USE_F.getValue(), 4).write(payload); verify(payload).writeInt4(1234567890); verify(payload).writeInt1(MySQLBinlogEventType....
public void convert(FSConfigToCSConfigConverterParams params) throws Exception { validateParams(params); this.clusterResource = getClusterResource(params); this.convertPlacementRules = params.isConvertPlacementRules(); this.outputDirectory = params.getOutputDirectory(); this.rulesToFile = para...
@Test public void testConversionWithInvalidPlacementRules() throws Exception { config = new Configuration(false); config.set(FairSchedulerConfiguration.ALLOCATION_FILE, FS_INVALID_PLACEMENT_RULES_XML); config.setBoolean(FairSchedulerConfiguration.MIGRATION_MODE, true); expectedException.expect...
@Override public Mono<Authentication> convert(ServerWebExchange exchange) { return super.convert(exchange) // validate the password .<Authentication>flatMap(token -> { var credentials = (String) token.getCredentials(); byte[] credentialsBytes; ...
@Test void applyUsernameAndPasswordThenCreatesTokenSuccess() { var username = "username"; var password = "password"; var decryptedPassword = "decrypted password"; formData.add("username", username); formData.add("password", Base64.getEncoder().encodeToString(password.getByte...
public static List<PKafkaOffsetProxyResult> getBatchOffsets(List<PKafkaOffsetProxyRequest> requests) throws UserException { return PROXY_API.getBatchOffsets(requests); }
@Test public void testGetInfoInterruptedException() throws UserException, RpcException { Backend backend = new Backend(1L, "127.0.0.1", 9050); backend.setBeRpcPort(8060); backend.setAlive(true); new Expectations() { { service.getBackendOrComputeNode(anyLo...
@Override public BuiltInPreparedQuery prepareQuery(AnalyzerOptions analyzerOptions, String query, Map<String, String> preparedStatements, WarningCollector warningCollector) { Statement wrappedStatement = sqlParser.createStatement(query, createParsingOptions(analyzerOptions)); if (warningCollecto...
@Test public void testTooFewParameters() { try { Map<String, String> preparedStatements = ImmutableMap.of("my_query", "SELECT ? FROM foo where col1 = ?"); QUERY_PREPARER.prepareQuery(testAnalyzerOptions, "EXECUTE my_query USING 1", preparedStatements, WarningCollector.NOOP); ...
@Override public PushTelemetryResponse getErrorResponse(int throttleTimeMs, Throwable e) { return errorResponse(throttleTimeMs, Errors.forException(e)); }
@Test public void testGetErrorResponse() { PushTelemetryRequest req = new PushTelemetryRequest(new PushTelemetryRequestData(), (short) 0); PushTelemetryResponse response = req.getErrorResponse(0, Errors.CLUSTER_AUTHORIZATION_FAILED.exception()); assertEquals(Collections.singletonMap(Errors.C...
@Nonnull @Override public List<DataConnectionResource> listResources() { try { try (Connection connection = getConnection()) { DatabaseMetaData databaseMetaData = connection.getMetaData(); ResourceReader reader = new ResourceReader(); switch (...
@Test public void list_resources_should_return_view() throws Exception { jdbcDataConnection = new JdbcDataConnection(SHARED_DATA_CONNECTION_CONFIG); executeJdbc(JDBC_URL_SHARED, "CREATE TABLE MY_TABLE (ID INT, NAME VARCHAR)"); executeJdbc(JDBC_URL_SHARED, "CREATE VIEW MY_TABLE_VIEW AS SELEC...
public Integer doCall() throws Exception { // Operator id must be set if (ObjectHelper.isEmpty(operatorId)) { printer().println("Operator id must be set"); return -1; } List<String> integrationSources = Stream.concat(Arrays.stream(Optional.ofNulla...
@Test public void shouldUpdateIntegration() throws Exception { Integration integration = createIntegration("route"); kubernetesClient.resources(Integration.class).resource(integration).create(); IntegrationRun command = createCommand(); command.filePaths = new String[] { "classpath:...
public static SimpleTransform threshold(double min, double max) { return new SimpleTransform(Operation.threshold,min,max); }
@Test public void testThresholdBelow() { double min = 0.0; double max = Double.POSITIVE_INFINITY; TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.threshold(min, max)),new HashMap<>()); testThresholding(t,min,max); }
public void tryMergeIssuesFromSourceBranchOfPullRequest(Component component, Collection<DefaultIssue> newIssues, Input<DefaultIssue> rawInput) { if (sourceBranchInputFactory.hasSourceBranchAnalysis()) { Input<DefaultIssue> sourceBranchInput = sourceBranchInputFactory.createForSourceBranch(component); De...
@Test public void tryMergeIssuesFromSourceBranchOfPullRequest_merges_issue_state_from_source_branch_into_pull_request() { DefaultIssue sourceBranchIssue = createIssue("issue2", rule.getKey(), Issue.STATUS_CONFIRMED, new Date()); Input<DefaultIssue> sourceBranchInput = new DefaultTrackingInput(singletonList(so...
@Override public void register(String qpKey, Status status) { checkNotNull(qpKey, "qpKey can't be null"); checkNotNull(status, "status can't be null"); checkState(statuses.put(qpKey, status) == null, "Quality Profile '%s' is already registered", qpKey); }
@Test @UseDataProvider("qualityProfileStatuses") public void register_fails_with_ISE_if_qp_is_already_registered(QProfileStatusRepository.Status status) { underTest.register("key", status); assertThatThrownBy(() -> underTest.register("key", status)) .isInstanceOf(IllegalStateException.class) .h...
@Override public void storeAll(long firstItemSequence, T[] items) { long startNanos = Timer.nanos(); try { delegate.storeAll(firstItemSequence, items); } finally { storeAllProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void storeAll() { String[] items = new String[]{"1", "2"}; ringbufferStore.storeAll(100, items); verify(delegate).storeAll(100, items); assertProbeCalledOnce("storeAll"); }
public static LookupResult multi(final CharSequence singleValue, final Map<Object, Object> multiValue) { return withoutTTL().single(singleValue).multiValue(multiValue).build(); }
@Test public void serializeMultiString() { final LookupResult lookupResult = LookupResult.multi("Foobar", MULTI_VALUE); final JsonNode node = objectMapper.convertValue(lookupResult, JsonNode.class); assertThat(node.isNull()).isFalse(); assertThat(node.path("single_value").asText())....
@Override public int configInfoCount() { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); String sql = configInfoMapper.count(null); Integer result = databaseOperate.queryOne(sql, Integer.class); ...
@Test void testConfigInfoCount() { //mock total count when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(new Integer(9)); int count = embeddedConfigInfoPersistService.configInfoCount(); assertEquals(9, count); when(databaseOperate.quer...
@Override public boolean isAbsentSince(AlluxioURI path, long absentSince) { MountInfo mountInfo = getMountInfo(path); if (mountInfo == null) { return false; } AlluxioURI mountBaseUri = mountInfo.getAlluxioUri(); while (path != null && !path.equals(mountBaseUri)) { Pair<Long, Long> cac...
@Test public void isAbsent() throws Exception { AlluxioURI absentPath = new AlluxioURI("/mnt/absent"); // Existence of absentPath is not known yet assertFalse(mUfsAbsentPathCache.isAbsentSince(absentPath, UfsAbsentPathCache.ALWAYS)); process(absentPath); // absentPath is known to be absent ass...
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) { return containsAtLeastEntriesIn(accumulateMap("containsAtLeast", k0, v0, rest)); }
@Test public void containsAtLeastWrongValue_sameToStringForKeys() { expectFailureWhenTestingThat(ImmutableMap.of(1L, "jan", 1, "feb")) .containsAtLeast(1, "jan", 1L, "feb"); assertFailureKeys( "keys with wrong values", "for key", "expected value", "but got value", ...
public static FixedWindows of(Duration size) { return new FixedWindows(size, Duration.ZERO); }
@Test public void testDefaultWindowMappingFn() { PartitioningWindowFn<?, ?> windowFn = FixedWindows.of(Duration.standardMinutes(20L)); WindowMappingFn<?> mapping = windowFn.getDefaultWindowMappingFn(); assertThat( mapping.getSideInputWindow( new BoundedWindow() { @Overri...
@Override public MaskRuleConfiguration buildToBeAlteredRuleConfiguration(final AlterMaskRuleStatement sqlStatement) { return MaskRuleStatementConverter.convert(sqlStatement.getRules()); }
@Test void assertUpdate() { MaskRuleConfiguration currentRuleConfig = createCurrentRuleConfiguration(); MaskColumnSegment columnSegment = new MaskColumnSegment("order_id", new AlgorithmSegment("MD5", new Properties())); MaskRuleSegment ruleSegment = new MaskRuleSegment("t_ord...
public int read(ByteBuffer buffer, long offset, int size) throws IOException { Validate.checkNotNull(buffer, "buffer"); Validate.checkWithinRange(offset, "offset", 0, this.remoteObject.size()); Validate.checkPositiveInteger(size, "size"); if (this.closed) { return -1; } int reqSize = (in...
@Test public void testArgChecks() throws Exception { // Should not throw. S3ARemoteObjectReader reader = new S3ARemoteObjectReader(remoteObject); // Verify it throws correctly. intercept( IllegalArgumentException.class, "'remoteObject' must not be null", () -> new S3ARemoteOb...
@Override protected Response filter(Request request, RequestMeta meta, Class handlerClazz) { Method method; try { method = getHandleMethod(handlerClazz); } catch (NacosException e) { return null; } if (method.isAnnotationPresent(TpsCo...
@Test void testTpsCheckException() { HealthCheckRequest healthCheckRequest = new HealthCheckRequest(); RequestMeta requestMeta = new RequestMeta(); Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class))).thenThrow(new NacosRuntimeException(12345)); Response filterResponse =...
@Override public String getResourceOutputNodeType() { return null; }
@Test public void testGetResourceOutputNodeType() throws Exception { assertNull( analyzer.getResourceOutputNodeType() ); }
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = originalGlyphIds; for (String feature : FEATURES_IN_ORDER) { if (!gsubData.isFeatureSupported(feature)) { LOG.debug("the fe...
@Test void testApplyTransforms_khanda_ta() { // given List<Integer> glyphsAfterGsub = Arrays.asList(98, 78, 101, 113); // when List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("হঠাৎ")); // then assertEquals(glyphsAfterGsub, result); }
public void add(T value) { UUID uuid = value.getUUID(); if (_map.containsKey(uuid)) { throw new AssertionError(String.format("Existing value found with UUID: %s", uuid)); } _map.put(uuid, value); }
@Test public void addValue() { // try adding a new value UUIDMap<Value> map = new UUIDMap<>(); Value value = addNewValue(map); // try re-adding the value assertThrows(AssertionError.class, () -> map.add(value)); // try adding a clone of the value assertThrow...
long residentMemorySizeEstimate() { return (priorValue == null ? 0 : priorValue.length) + (oldValue == null || priorValue == oldValue ? 0 : oldValue.length) + (newValue == null ? 0 : newValue.length) + recordContext.residentMemorySizeEstimate(); }
@Test public void shouldAccountForDeduplicationInSizeEstimate() { final ProcessorRecordContext context = new ProcessorRecordContext(0L, 0L, 0, "topic", new RecordHeaders()); assertEquals(25L, new BufferValue(null, null, null, context).residentMemorySizeEstimate()); assertEquals(26L, new Buff...
@Override public String requestMessageForPluginSettingsValidation(PluginSettingsConfiguration configuration) { Map<String, Map<String, Object>> configuredValues = new LinkedHashMap<>(); configuredValues.put("plugin-settings", jsonResultMessageHandler.configurationToMap(configuration)); retur...
@Test public void shouldBuildRequestBodyForCheckSCMConfigurationValidRequest() throws Exception { PluginSettingsConfiguration configuration = new PluginSettingsConfiguration(); configuration.add(new PluginSettingsProperty("key-one", "value-one")); configuration.add(new PluginSettingsProperty...
@Override public Response write(WriteRequest request) throws Exception { CompletableFuture<Response> future = writeAsync(request); // Here you wait for 10 seconds, as long as possible, for the request to complete return future.get(10_000L, TimeUnit.MILLISECONDS); }
@Test void testWrite() throws Exception { raftProtocol.write(writeRequest); verify(serverMock).commit(any(String.class), eq(writeRequest), any(CompletableFuture.class)); }
public Method getMainMethod() { return mainMethod; }
@Test public void testGetMainMethod() { MainMethodFinder mainMethodFinder = new MainMethodFinder(); mainMethodFinder.getMainMethodOfClass(MainMethodFinderTest.class); assertNotNull(mainMethodFinder.mainMethod); }
@Nullable public static Method findPropertySetter( @Nonnull Class<?> clazz, @Nonnull String propertyName, @Nonnull Class<?> propertyType ) { String setterName = "set" + toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); Method method; tr...
@Test public void when_findPropertySetter_protected_then_returnsNull() { assertNull(findPropertySetter(JavaProperties.class, "protectedField", int.class)); }
@Override public Collection<DatabasePacket> execute() throws SQLException { switch (packet.getType()) { case 'S': return describePreparedStatement(); case 'P': return Collections.singleton(portalContext.get(packet.getName()).describe()); de...
@Test void assertDescribePreparedStatementInsertWithColumns() throws SQLException { when(packet.getType()).thenReturn('S'); final String statementId = "S_2"; when(packet.getName()).thenReturn(statementId); String sql = "insert into t_order (id, k, c, pad) values (1, ?, ?, ?), (?, 2, ...
@Override public boolean equals(@Nullable Object object) { if (object instanceof MetricsMap) { MetricsMap<?, ?> metricsMap = (MetricsMap<?, ?>) object; return Objects.equals(metrics, metricsMap.metrics); } return false; }
@Test public void testEquals() { MetricsMap<String, AtomicLong> metricsMap = new MetricsMap<>(unusedKey -> new AtomicLong()); MetricsMap<String, AtomicLong> equal = new MetricsMap<>(unusedKey -> new AtomicLong()); Assert.assertEquals(metricsMap, equal); Assert.assertEquals(metricsMap.hashCode(), equal...
public void indexDocument(int docId, Predicate predicate) { if (documentIdCounter == Integer.MAX_VALUE) { throw new IllegalStateException("Index is full, max number of documents is: " + Integer.MAX_VALUE); } else if (seenIds.contains(docId)) { throw new IllegalArgumentException("...
@Test void requireThatIndexingMultiDocumentsWithSameIdThrowsException() { assertThrows(IllegalArgumentException.class, () -> { PredicateIndexBuilder builder = new PredicateIndexBuilder(2); builder.indexDocument(1, Predicate.fromString("a in ['b']")); builder.indexDocument...
@Override public Object apply(Object input) { return PropertyOrFieldSupport.EXTRACTION.getValueOf(propertyOrFieldName, input); }
@Test void should_throw_error_when_no_property_nor_public_field_match_given_name() { // GIVEN ByNameSingleExtractor underTest = new ByNameSingleExtractor("unknown"); // WHEN Throwable thrown = catchThrowable(() -> underTest.apply(YODA)); // THEN then(thrown).isInstanceOf(IntrospectionError.cla...
public void bookRoom(int roomNumber) throws Exception { var room = hotelDao.getById(roomNumber); if (room.isEmpty()) { throw new Exception("Room number: " + roomNumber + " does not exist"); } else { if (room.get().isBooked()) { throw new Exception("Room already booked!"); } else ...
@Test void bookingRoomWithInvalidIdShouldRaiseException() { assertThrows(Exception.class, () -> hotel.bookRoom(getNonExistingRoomId())); }
public static List<FieldSchema> convert(Schema schema) { return schema.columns().stream() .map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc())) .collect(Collectors.toList()); }
@Test public void testConversionWithoutLastComment() { Schema expected = new Schema( optional(1, "customer_id", Types.LongType.get(), "customer comment"), optional(2, "first_name", Types.StringType.get(), null) ); Schema schema = HiveSchemaUtil.convert( Arrays.asList("customer_id"...
Queue<String> prepareRollingOrder(List<String> podNamesToConsider, List<Pod> pods) { Deque<String> rollingOrder = new ArrayDeque<>(); for (String podName : podNamesToConsider) { Pod matchingPod = pods.stream().filter(pod -> podName.equals(pod.getMetadata().getName())).findFirst().orElse...
@Test public void testRollingOrderWithMissingPod() { List<Pod> pods = List.of( renamePod(READY_POD, "my-connect-connect-0"), renamePod(READY_POD, "my-connect-connect-2") ); KafkaConnectRoller roller = new KafkaConnectRoller(RECONCILIATION, CLUSTER, 1_000L, n...
public static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0xFFFF, data, offset, length, true, true, 0x0000); }
@Test // See: http://ww1.microchip.com/downloads/en/AppNotes/00752a.pdf public void MCRF4XX_8552F189() { final byte[] data = new byte[] {(byte) 0x58, (byte) 0x25, (byte) 0x1F, (byte) 0x98}; assertEquals(0x07F1, CRC16.MCRF4XX(data, 0, 4)); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Target target = getTarget(request); if (target == Target.Other) { chain.doFilter(request, response); return; } HttpServl...
@Test public void testStandardClientsThrottlingEnforceable() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.throttleStandardClients", true); // Custom clients will go up to the window limit whenRequest(FULL_FETCH, EurekaClientIdentity.DEFAULT_CLI...
public void validateFilterExpression(final Expression exp) { final SqlType type = getExpressionReturnType(exp); if (!SqlTypes.BOOLEAN.equals(type)) { throw new KsqlStatementException( "Type error in " + filterType.name() + " expression: " + "Should evaluate to boolean but is" ...
@Test public void shouldThrowOnBadTypeComparison() { // Given: final Expression left = new UnqualifiedColumnReferenceExp(COLUMN1); final Expression right = new IntegerLiteral(10); final Expression comparision = new ComparisonExpression(Type.EQUAL, left, right); when(schema.findValueColumn(any())...
public QueryConfiguration applyOverrides(QueryConfigurationOverrides overrides) { Map<String, String> sessionProperties; if (overrides.getSessionPropertiesOverrideStrategy() == OVERRIDE) { sessionProperties = new HashMap<>(overrides.getSessionPropertiesOverride()); } else...
@Test public void testSessionPropertyOverride() { overrides.setSessionPropertiesOverrideStrategy(OVERRIDE); assertEquals(CONFIGURATION_1.applyOverrides(overrides), CONFIGURATION_FULL_OVERRIDE); QueryConfiguration overridden = new QueryConfiguration( CATALOG_OVERRIDE, ...
public static InetAddress fixScopeIdAndGetInetAddress(final InetAddress inetAddress) throws SocketException { if (!(inetAddress instanceof Inet6Address inet6Address)) { return inetAddress; } if (!inetAddress.isLinkLocalAddress() && !inetAddress.isSiteLocalAddress()) { re...
@Test public void testFixScopeIdAndGetInetAddress_whenNotLinkLocalAddress() throws SocketException, UnknownHostException { InetAddress inetAddress = InetAddress.getByName("2001:db8:85a3:0:0:8a2e:370:7334"); InetAddress actual = AddressUtil.fixScopeIdAndGetInetAddress(inetAddress); assertEqua...
public static ConnectedComponents findComponentsForStartEdges(Graph graph, EdgeTransitionFilter edgeTransitionFilter, IntContainer edges) { return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, true).findComponentsForStartEdges(edges); }
@Test public void withStartEdges_simple() { // 0 - 1 4 - 5 - 6 - 7 // | | // 3 - 2 8 - 9 g.edge(0, 1).setDistance(10).set(speedEnc, 10, 10); g.edge(1, 2).setDistance(10).set(speedEnc, 10, 10); g.edge(2, 3).setDistance(10).set(speedEnc, 10, 10); g.edge(3,...
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testCallFromJs() { run( "def res = karate.call('called1.feature')" ); matchVar("res", "{ a: 1, foo: { hello: 'world' } }"); }
public static boolean isNotEmpty(CharSequence str) { return !isEmpty(str); }
@Test public void assertIsNotEmpty() { String string = "string"; Assert.assertTrue(StringUtil.isNotEmpty(string)); }
@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_unknown_type_to_object__throws_exception__register_table_cell_transformer() { DataTable table = parse("", "| | lat | lon |", "| KMSY | 29.993333 | -90.258056 |", "| KSFO | 37.618889 | -122.375 |", "| KSEA | 47.448889...
public Rule<ProjectNode> projectNodeRule() { return new PullUpExpressionInLambdaProjectNodeRule(); }
@Test public void testLikeExpression() { tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).projectNodeRule()) .setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true") .on(p -> { p.variable("expr", new Ar...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> children = new AttributedList<Path>(); final IRODSFileSystemAO fs = session.getClient(); final IRODSFile f =...
@Test @Ignore public void testList() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/iRODS (iPlan...
public static String toJson(MetadataUpdate metadataUpdate) { return toJson(metadataUpdate, false); }
@Test public void testRemoveSnapshotsToJson() { String action = MetadataUpdateParser.REMOVE_SNAPSHOTS; long snapshotId = 2L; String expected = String.format("{\"action\":\"%s\",\"snapshot-ids\":[2]}", action); MetadataUpdate update = new MetadataUpdate.RemoveSnapshot(snapshotId); String actual = M...
protected void scheduleRefresh() { FrameworkExecutorRepository repository = frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class); refreshFuture = repository .getSharedScheduledExecutor() .scheduleAtFixedRate( t...
@Test void testRefresh() { FrameworkModel frameworkModel = new FrameworkModel(); AtomicInteger count = new AtomicInteger(0); DubboCertManager certManager = new DubboCertManager(frameworkModel) { @Override protected CertPair generateCert() { count.incre...
@ConstantFunction(name = "multiply", argTypes = {DOUBLE, DOUBLE}, returnType = DOUBLE) public static ConstantOperator multiplyDouble(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createDouble(first.getDouble() * second.getDouble()); }
@Test public void multiplyDouble() { assertEquals(10000.0, ScalarOperatorFunctions.multiplyDouble(O_DOUBLE_100, O_DOUBLE_100).getDouble(), 1); }
@SuppressWarnings("unchecked") static Object extractFromRecordValue(Object recordValue, String fieldName) { List<String> fields = Splitter.on('.').splitToList(fieldName); if (recordValue instanceof Struct) { return valueFromStruct((Struct) recordValue, fields); } else if (recordValue instanceof Map)...
@Test public void testExtractFromRecordValueStruct() { Schema valSchema = SchemaBuilder.struct().field("key", Schema.INT64_SCHEMA).build(); Struct val = new Struct(valSchema).put("key", 123L); Object result = RecordUtils.extractFromRecordValue(val, "key"); assertThat(result).isEqualTo(123L); }
@Override public void dump(OutputStream output) { try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { for (long value : values) { out.printf("%d%n", value); } } }
@Test public void dumpsToAStream() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); snapshot.dump(output); assertThat(output.toString()) .isEqualTo(String.format("1%n2%n3%n4%n5%n")); }
public Optional<Long> getCommandSequenceNumber() { return commandSequenceNumber; }
@Test public void shouldHandleNullCommandNumber() { assertThat( new KsqlRequest("sql", SOME_PROPS, Collections.emptyMap(), null).getCommandSequenceNumber(), is(Optional.empty())); }
@Override public void put(K key, V value) { checkState(!destroyed, destroyedMessage); checkNotNull(key, ERROR_NULL_KEY); checkNotNull(value, ERROR_NULL_VALUE); MapValue<V> newValue = new MapValue<>(value, timestampProvider.apply(key, value)); if (putInternal(key, newValue)) ...
@Test public void testPut() throws Exception { // Set up expectations of external events to be sent to listeners during // the test. These don't use timestamps so we can set them all up at once. EventuallyConsistentMapListener<String, String> listener = getListener(); ...
public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ...
@Test public void testRemoteExceptionFromHistoryServer() throws Exception { MRClientProtocol historyServerProxy = mock(MRClientProtocol.class); when(historyServerProxy.getJobReport(getJobReportRequest())).thenThrow( new IOException("Job ID doesnot Exist")); ResourceMgrDelegate rm = mock(Resource...
@Override public void update(V newValue) { throw MODIFICATION_ATTEMPT_ERROR; }
@Test void testUpdate() throws IOException { long value = valueState.value(); assertThat(value).isEqualTo(42L); assertThatThrownBy(() -> valueState.update(54L)) .isInstanceOf(UnsupportedOperationException.class); }
public static String toStringAddress(SocketAddress address) { if (address == null) { return StringUtils.EMPTY; } return toStringAddress((InetSocketAddress) address); }
@Test public void testToStringAddress1() { assertThat(NetUtil.toStringAddress((SocketAddress)ipv4)) .isEqualTo(ipv4.getAddress().getHostAddress() + ":" + ipv4.getPort()); assertThat(NetUtil.toStringAddress((SocketAddress)ipv6)).isEqualTo( ipv6.getAddress().getHostAddress() + ...
@ApiOperation(value = "Save Or update User (saveUser)", notes = "Create or update the User. When creating user, platform generates User Id as " + UUID_WIKI_LINK + "The newly created User Id will be present in the response. " + "Specify existing User Id to update the d...
@Test public void testSaveUser() throws Exception { loginSysAdmin(); User user = createTenantAdminUser(); String email = user.getEmail(); Mockito.reset(tbClusterService, auditLogService); User savedUser = doPost("/api/user", user, User.class); Assert.assertNotNull(s...
@Override public void apply(final Path file, final Local local, final TransferStatus status, final ProgressListener listener) throws BackgroundException { // Rename existing file before putting new file in place if(status.isExists()) { Path rename; do { ...
@Test public void testPrepare() throws Exception { final AtomicBoolean c = new AtomicBoolean(); final RenameExistingFilter f = new RenameExistingFilter(new DisabledUploadSymlinkResolver(), new NullSession(new Host(new TestProtocol())) { @Override @SuppressWarnings("unchecked"...
@Override public long get(long key1, int key2) { return super.get0(key1, key2); }
@Test public void testClear() { final long key1 = randomKey(); final int key2 = randomKey(); insert(key1, key2); hsa.clear(); assertEquals(NULL_ADDRESS, hsa.get(key1, key2)); assertEquals(0, hsa.size()); }
@Operation(summary = "Get single connection") @GetMapping(value = "{id}", produces = "application/json") @ResponseBody public Connection getById(@PathVariable("id") Long id) { return connectionService.getConnectionById(id); }
@Test public void getConnectionById() { when(connectionServiceMock.getConnectionById(anyLong())).thenReturn(getNewConnection()); Connection result = controllerMock.getById(anyLong()); verify(connectionServiceMock, times(1)).getConnectionById(anyLong()); assertEquals("connection", r...
@Override public void deleteTag(Long id) { // 校验存在 validateTagExists(id); // 校验标签下是否有用户 validateTagHasUser(id); // 删除 memberTagMapper.deleteById(id); }
@Test public void testDeleteTag_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> tagService.deleteTag(id), TAG_NOT_EXISTS); }
public void succeededGetQueueInfoRetrieved(long duration) { totalSucceededGetQueueInfoRetrieved.add(duration); getQueueInfoLatency.add(duration); }
@Test public void testSucceededGetQueueInfoRetrieved() { long totalGoodBefore = metrics.getNumSucceededGetQueueInfoRetrieved(); goodSubCluster.getQueueInfoRetrieved(150); Assert.assertEquals(totalGoodBefore + 1, metrics.getNumSucceededGetQueueInfoRetrieved()); Assert.assertEquals(150, ...
@Override public Optional<Endpoint> getRestEndpoint(String clusterId) { Optional<KubernetesService> restService = getService(ExternalServiceDecorator.getExternalServiceName(clusterId)); if (!restService.isPresent()) { return Optional.empty(); } final Servi...
@Test void testServiceLoadBalancerEmptyHostAndIP() { mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer("", "")); final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID); assertThat(resultEndpoint).isNotPresent(); }
@Override public void onTaskFinished(TaskAttachment attachment) { if (attachment instanceof BrokerPendingTaskAttachment) { onPendingTaskFinished((BrokerPendingTaskAttachment) attachment); } else if (attachment instanceof BrokerLoadingTaskAttachment) { onLoadingTaskFinished((B...
@Test public void testLoadingTaskOnFinishedWithUnfinishedTask(@Injectable BrokerLoadingTaskAttachment attachment, @Injectable LoadTask loadTask1, @Injectable LoadTask loadTask2) { BrokerLo...
@VisibleForTesting public boolean getSizeBasedWeight() { return sizeBasedWeight; }
@Test public void testSizeBasedWeightNotAffectAppActivation() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); // Define top-level queues String defaultPath = CapacitySchedulerConfiguration.ROOT + ".default"; QueuePath queuePath = new QueuePath(...