focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public byte[] serialize(PendingSplitsCheckpoint<T> checkpoint) throws IOException { checkArgument( checkpoint.getClass() == PendingSplitsCheckpoint.class, "Cannot serialize subclasses of PendingSplitsCheckpoint"); // optimization: the splits lazily cache th...
@Test void repeatedSerializationCaches() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( Collections.singletonList(testSplit2())); final byte[] ser1 = new PendingSp...
public boolean isMultiThreadingEnabled() { return multiThreadingEnabled; }
@Test public void testIsMultiThreadingEnabled() { TopicConfig topicConfig = new TopicConfig(); assertFalse(topicConfig.isMultiThreadingEnabled()); }
public boolean isCompleteOncePreferredResolved() { return completeOncePreferredResolved; }
@Test void completeOncePreferredResolved() { assertThat(builder.build().isCompleteOncePreferredResolved()).isTrue(); builder.completeOncePreferredResolved(false); assertThat(builder.build().isCompleteOncePreferredResolved()).isFalse(); }
@Override protected Pair<Option<Dataset<Row>>, String> fetchNextBatch(Option<String> lastCkptStr, long sourceLimit) { LOG.info("fetchNextBatch(): Input checkpoint: " + lastCkptStr); MessageBatch messageBatch; try { messageBatch = fetchFileMetadata(); } catch (HoodieException e) { throw e; ...
@Test public void shouldReturnEmptyOnNoMessages() { when(pubsubMessagesFetcher.fetchMessages()).thenReturn(Collections.emptyList()); GcsEventsSource source = new GcsEventsSource(props, jsc, sparkSession, null, pubsubMessagesFetcher); Pair<Option<Dataset<Row>>, String> expected = Pair.of(Opti...
@Override public OAuth2AccessTokenDO getAccessToken(String accessToken) { // 优先从 Redis 中获取 OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken); if (accessTokenDO != null) { return accessTokenDO; } // 获取不到,从 MySQL 中获取 accessToken...
@Test public void testGetAccessToken() { // mock 数据(访问令牌) OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class) .setExpiresTime(LocalDateTime.now().plusDays(1)); oauth2AccessTokenMapper.insert(accessTokenDO); // 准备参数 String accessToken = ac...
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 { thr...
@Test public void renameDefault() { context.setName(CoreConstants.DEFAULT_CONTEXT_NAME); context.setName("hello"); }
public B version(String version) { this.version = version; return getThis(); }
@Test void version() { ReferenceBuilder builder = new ReferenceBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); }
static boolean isValidComparison( final SqlType left, final ComparisonExpression.Type operator, final SqlType right ) { if (left == null || right == null) { throw nullSchemaException(left, operator, right); } return HANDLERS.stream() .filter(h -> h.handles.test(left.baseType())) ...
@Test public void shouldAssertTrueForValidComparisons() { // When: int i = 0; int j = 0; for (final SqlType leftType: typesTable) { for (final SqlType rightType: typesTable) { if (expectedResults.get(i).get(j)) { assertThat(ComparisonUtil.isValidComparison(leftType, ComparisonE...
public static <T extends Serializable> T ensureSerializable(T value) { return clone(value); }
@Test public void testTranscode() { String stringValue = "hi bob"; int intValue = 42; SerializableByJava testObject = new SerializableByJava(stringValue, intValue); SerializableByJava testCopy = SerializableUtils.ensureSerializable(testObject); assertEquals(stringValue, testCopy.stringValue); ...
static String getAbbreviation(Exception ex, Integer statusCode, String storageErrorMessage) { String result = null; for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) { final String abbreviation = retryReasonCategory.captureAndGetAbbreviation(ex, statusC...
@Test public void testEgressLimitRetryReason() { Assertions.assertThat(RetryReason.getAbbreviation(null, HTTP_UNAVAILABLE, EGRESS_OVER_ACCOUNT_LIMIT.getErrorMessage())).isEqualTo( EGRESS_LIMIT_BREACH_ABBREVIATION ); }
@Override public MapSettings setProperty(String key, String value) { return (MapSettings) super.setProperty(key, value); }
@Test public void setStringArrayEscapeCommas() { Settings settings = new MapSettings(definitions); settings.setProperty("multi_values", new String[]{"A,B", "C,D"}); String[] array = settings.getStringArray("multi_values"); assertThat(array).isEqualTo(new String[]{"A,B", "C,D"}); }
public boolean createDataConnection(DataConnectionCatalogEntry dl, boolean replace, boolean ifNotExists) { if (replace) { dataConnectionStorage.put(dl.name(), dl); listeners.forEach(TableListener::onTableChanged); return true; } else { boolean added = data...
@Test public void when_createDataConnection_then_succeeds() { // given DataConnectionCatalogEntry dataConnectionCatalogEntry = dataConnection(); given(relationsStorage.putIfAbsent(dataConnectionCatalogEntry.name(), dataConnectionCatalogEntry)).willReturn(true); // when dataC...
public static <F extends Future<Void>> Mono<Void> from(F future) { Objects.requireNonNull(future, "future"); if (future.isDone()) { if (!future.isSuccess()) { return Mono.error(FutureSubscription.wrapError(future.cause())); } return Mono.empty(); } return new ImmediateFutureMono<>(future); }
@Test void testImmediateFutureMonoImmediate() { ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE; Future<Void> promise = eventExecutor.newFailedFuture(new ClosedChannelException()); StepVerifier.create(FutureMono.from(promise)) .expectError(AbortedException.class) ...
@ApiOperation(value = "Delete a user", tags = { "Users" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the user was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested user was...
@Test public void testDeleteUser() throws Exception { User savedUser = null; try { User newUser = identityService.newUser("testuser"); newUser.setFirstName("Fred"); newUser.setLastName("McDonald"); newUser.setEmail("no-reply@flowable.org"); ...
@Override public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object item : c) { changed = items.remove(serializer.encode(item)) || changed; } return changed; }
@Test public void testRemoveAll() throws Exception { //Test for mass removal and change checking Set<Integer> removeSet = Sets.newHashSet(); fillSet(10, set); Set<Integer> duplicateSet = Sets.newHashSet(set); assertFalse("No elements should change.", set.removeAll(removeSet))...
public static InternetAddress fromIgnoringZoneId(String address) { return from(address, true); }
@Test public void testFromIgnoringZoneId() { assertInternetAddressEqualsIgnoringZoneId("fe80::641a:cdff:febd:d665", "fe80::641a:cdff:febd:d665%dummy0"); }
@Override public List<ServiceDTO> getServiceInstances(String serviceId) { String configName = SERVICE_ID_TO_CONFIG_NAME.get(serviceId); if (configName == null) { return Collections.emptyList(); } return assembleServiceDTO(serviceId, bizConfig.getValue(configName)); }
@Test public void testGetConfigServiceInstances() { String someUrl = "http://some-host/some-path"; when(bizConfig.getValue(configServiceConfigName)).thenReturn(someUrl); List<ServiceDTO> serviceDTOList = kubernetesDiscoveryService .getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE); ...
@Override public void setDefaultValue(Object defaultValue) { if (defaultValue instanceof List) { final List<?> defaultValueList = (List<?>) defaultValue; this.defaultValue = defaultValueList.stream() .filter(o -> o instanceof String) .map(Strin...
@Test public void testSetDefaultValue() throws Exception { final ListField list = new ListField("list", "The List", Collections.emptyList(), "Hello, this is a list", ConfigurationField.Optional.NOT_OPTIONAL); final Object defaultValue1 = list.getDefaultValue(); assertThat(defaultValue1 insta...
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); EmbeddedDo...
@Test public void testEncryptedRar() throws Exception { Parser parser = new RarParser(); try (InputStream input = getResourceAsStream("/test-documents/test-documents-enc.rar")) { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); ...
@Override public final void isEqualTo(@Nullable Object other) { @SuppressWarnings("UndefinedEquals") // the contract of this method is to follow Multimap.equals boolean isEqual = Objects.equal(actual, other); if (isEqual) { return; } // Fail but with a more descriptive message: if ((act...
@Test public void setMultimapIsEqualTo_fails() { ImmutableSetMultimap<String, String> multimapA = ImmutableSetMultimap.<String, String>builder() .putAll("kurt", "kluever", "russell", "cobain") .build(); ImmutableSetMultimap<String, String> multimapB = ImmutableSetMultim...
@Override public URI rewriteURI(URI d2Uri) { String path = d2Uri.getRawPath(); UriBuilder builder = UriBuilder.fromUri(_httpURI); if (path != null) { builder.path(path); } builder.replaceQuery(d2Uri.getRawQuery()); builder.fragment(d2Uri.getRawFragment()); URI rewrittenUri = b...
@Test public void testSimpleD2Rewrite() throws URISyntaxException { final URI httpURI = new URIBuilder("http://www.linkedin.com:1234/test").build(); final URI d2URI = new URIBuilder("d2://serviceName/request/query?q=5678").build(); final String expectURL = "http://www.linkedin.com:1234/test/request/quer...
@Override public Mono<Void> apply(final ServerWebExchange exchange, final ShenyuPluginChain shenyuPluginChain, final ParamMappingRuleHandle paramMappingRuleHandle) { return shenyuPluginChain.execute(exchange); }
@Test public void testApply() { when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(defaultOperator.apply(this.exchange, this.chain, new ParamMappingRuleHandle())).expectSubscription().verifyComplete(); }
@GetMapping( path = "/admin/extension/{namespaceName}/{extensionName}", produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<ExtensionJson> getExtension(@PathVariable String namespaceName, @PathVariable String extensionName) { ...
@Test public void testGetInactiveExtension() throws Exception { mockAdminUser(); mockExtension(2, 0, 0).forEach(ev -> { ev.setActive(false); ev.getExtension().setActive(false); }); mockMvc.perform(get("/admin/extension/{namespace}/{extension}", "foobar", "baz...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); for (final GarbageCollectorMXBean gc : garbageCollectors) { final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); gauges.put(name(name, "count"), (Gauge<Lon...
@Test public void hasAGaugeForGcTimes() { final Gauge<Long> gauge = (Gauge<Long>) metrics.getMetrics().get("PS-OldGen.time"); assertThat(gauge.getValue()) .isEqualTo(2L); }
public static Optional<KsqlAuthorizationValidator> create( final KsqlConfig ksqlConfig, final ServiceContext serviceContext, final Optional<KsqlAuthorizationProvider> externalAuthorizationProvider ) { final Optional<KsqlAccessValidator> accessValidator = getAccessValidator( ksqlConfig, ...
@Test public void shouldReturnEmptyAuthorizationValidatorWhenNoAuthorizationProviderIsFound() { // Given: givenKafkaAuthorizer("", Collections.emptySet()); // When: final Optional<KsqlAuthorizationValidator> validator = KsqlAuthorizationValidatorFactory.create( ksqlConfig, serviceCont...
public FEELFnResult<Boolean> invoke(@ParameterName( "range" ) Range range, @ParameterName( "point" ) Comparable point) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { ret...
@Test void invokeParamRangeAndRange() { FunctionTestUtil.assertResult( startedByFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ), ...
public String namespace(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns)); }
@Test public void testNamespace() { Namespace ns = Namespace.of("ns"); assertThat(withPrefix.namespace(ns)).isEqualTo("v1/ws/catalog/namespaces/ns"); assertThat(withoutPrefix.namespace(ns)).isEqualTo("v1/namespaces/ns"); }
public static Set<String> getTableNameVariations(String tableName) { String rawTableName = extractRawTableName(tableName); String offlineTableName = OFFLINE.tableNameWithType(rawTableName); String realtimeTableName = REALTIME.tableNameWithType(rawTableName); return ImmutableSet.of(rawTableName, offlineT...
@Test public void testGetTableNameVariations() { assertEquals(TableNameBuilder.getTableNameVariations("tableAbc"), ImmutableSet.of("tableAbc", "tableAbc_REALTIME", "tableAbc_OFFLINE")); assertEquals(TableNameBuilder.getTableNameVariations("tableAbc_REALTIME"), ImmutableSet.of("tableAbc", "ta...
@Override public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) { log.debug( "sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}", catalogueTree, sortTypeEnum); return recursionSortCatalogues...
@Test public void sortAscTest() { SortTypeEnum sortTypeEnum = SortTypeEnum.ASC; List<Catalogue> catalogueTree = Lists.newArrayList(); Catalogue catalogue = new Catalogue(); catalogue.setId(1); catalogue.setCreateTime(LocalDateTime.of(2024, 4, 28, 19, 22, 0)); Catalog...
@Override public void resetLocal() { this.min = Double.POSITIVE_INFINITY; }
@Test void testResetLocal() { DoubleMinimum min = new DoubleMinimum(); double value = 13.57902468; min.add(value); assertThat(min.getLocalValue()).isCloseTo(value, within(0.0)); min.resetLocal(); assertThat(min.getLocalValue()).isCloseTo(Double.POSITIVE_INFINITY, wi...
public static BackendExecutorContext getInstance() { return INSTANCE; }
@Test void assertGetInstance() { ContextManager contextManager = mockContextManager(); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); assertThat(BackendExecutorContext.getInstance().getExecutorEngine(), is(BackendExecutorContext.getInstance().getExecutorEngi...
@UdafFactory(description = "collect distinct values of a Bigint field into a single Array") public static <T> Udaf<T, List<T>, List<T>> createCollectSetT() { return new Collect<>(); }
@Test public void shouldCollectDistinctTimes() { final Udaf<Time, List<Time>, List<Time>> udaf = CollectSetUdaf.createCollectSetT(); final Time[] values = new Time[] {new Time(1), new Time(2)}; List<Time> runningList = udaf.initialize(); for (final Time i : values) { runningList = udaf.aggregate...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldCastDoubleRoundDown() { // When: final BigDecimal decimal = DecimalUtil.cast(1.11, 2, 1); // Then: assertThat(decimal, is(new BigDecimal("1.1"))); }
@Override public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter, String methodName) throws Throwable { Object returnValue = proceedingJoinPoint.proceed(); if (Flux.class.isAssignableFrom(returnValue.getClass())) { Flux<?> fluxReturnValue = (Flux<?>...
@Test public void testReactorTypes() throws Throwable { RateLimiter rateLimiter = RateLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn(Mono.just("Test")); assertThat( reactorRateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) ...
@Override public void onClose(final int i, final String s, final boolean b) { this.close(); }
@Test public void testOnClose() { shenyuWebsocketClient = spy(shenyuWebsocketClient); doNothing().when(shenyuWebsocketClient).close(); shenyuWebsocketClient.onClose(1, "shenyu-plugin-grpc", true); verify(shenyuWebsocketClient).close(); }
public Version(long version) { this.version = version; }
@Test public void testVersion() { Version version1 = new Version(1); Version version2 = new Version(1); assertTrue(version1.equals(version2)); assertTrue(version1.hashCode() == version2.hashCode()); assertTrue(version1.value() == version2.value()); Version version3 =...
public String prometheusName(String recordName, String metricName) { String baseName = StringUtils.capitalize(recordName) + StringUtils.capitalize(metricName); String[] parts = SPLIT_PATTERN.split(baseName); String joined = String.join("_", parts).toLowerCase(); r...
@Test public void testNamingWhitespaces() { PrometheusMetricsSink sink = new PrometheusMetricsSink(); String recordName = "JvmMetrics"; String metricName = "GcCount" + "G1 Old Generation"; Assert.assertEquals( "jvm_metrics_gc_count_g1_old_generation", sink.prometheusName(recordName, m...
public static String sha3_224Hex(String input) { SHA3.DigestSHA3 sha3Digest = new SHA3.Digest224(); byte[] hashBytes = sha3Digest.digest(input.getBytes(StandardCharsets.UTF_8)); return Hex.toHexString(hashBytes); }
@Test void whenCalledOnTheSameInput_sha3_224Hex_returnsTheSameValueAsDigestUtils() { String input = "String to be hashed"; //Apache Commons DigestUtils digest for the string "String to be hashed" String apacheCommonsDigest = "57ead8c5fc5c15ed7bde0550648d06a6aed3cba443ed100a6f5e64f3"; assertEquals(ap...
public final void isAtMost(int other) { isAtMost((double) other); }
@Test public void isAtMost_int() { expectFailureWhenTestingThat(2.0).isAtMost(1); assertThat(2.0).isAtMost(2); assertThat(2.0).isAtMost(3); }
public HikariDataSource getDataSource() { return ds; }
@Test @Ignore public void testGetSqlServerDataSource() { DataSource ds = SingletonServiceFactory.getBean(SqlServerDataSource.class).getDataSource(); assertNotNull(ds); try(Connection connection = ds.getConnection()){ assertNotNull(connection); } catch (SQLException e...
public static <T> ZstdCoder<T> of(Coder<T> innerCoder, byte[] dict, int level) { return new ZstdCoder<>(innerCoder, dict, level); }
@Test public void testCoderEquals() throws Exception { // True if coder, dict and level are equal. assertEquals( ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0), ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0)); assertEquals( ZstdCoder.of(ListCoder.of(ByteArrayC...
public static void addTopologyDescriptionMetric(final StreamsMetricsImpl streamsMetrics, final Gauge<String> topologyDescription) { streamsMetrics.addClientLevelMutableMetric( TOPOLOGY_DESCRIPTION, TOPOLOGY_DESCRIPTION_DESCRIPTION, ...
@Test public void shouldAddTopologyDescriptionMetric() { final String name = "topology-description"; final String description = "The description of the topology executed in the Kafka Streams client"; final String topologyDescription = "thisIsATopologyDescription"; final Gauge<String>...
public static int[] computePhysicalIndices( List<TableColumn> logicalColumns, DataType physicalType, Function<String, String> nameRemapping) { Map<TableColumn, Integer> physicalIndexLookup = computePhysicalIndices(logicalColumns.stream(), physicalType, nameRe...
@Test void testFieldMappingRowTypeNotMatchingNamesInNestedType() { int[] indices = TypeMappingUtils.computePhysicalIndices( TableSchema.builder() .field("f0", DECIMAL(38, 18)) .field( ...
public abstract Task<Map<K, Try<T>>> taskForBatch(G group, Set<K> keys);
@Test public void testEntriesMissingInReturnedMap() { RecordingTaskStrategy<Integer, Integer, String> strategy = new RecordingTaskStrategy<Integer, Integer, String>(key -> Success.of(String.valueOf(key)), key -> key % 2) { @Override public Task<Map<Integer, Try<String>>> taskForBatch(Inte...
static Set<PipelineOptionSpec> getOptionSpecs( Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) { Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods); ImmutableSe...
@Test public void testExcludesNonPipelineOptionsMethods() { Set<PipelineOptionSpec> properties = PipelineOptionsReflector.getOptionSpecs(ExtendsNonPipelineOptions.class, true); assertThat(properties, not(hasItem(hasName("foo")))); }
@Override public void callback(CallbackContext context) { try { onCallback(context); } catch (IOException | ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } ...
@Test public void callback_whenOrganizationsAreNotDefinedAndUserBelongsToInstallationOrganization_shouldAuthenticateAndRedirect() throws IOException, ExecutionException, InterruptedException { UserIdentity userIdentity = mock(UserIdentity.class); CallbackContext context = mockUserBelongingToOrganization(u...
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingDeleteStructRowToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "transactionId", false, "1", "tableName", ...
@Override public void handlerPlugin(final PluginData pluginData) { if (Objects.nonNull(pluginData) && Boolean.TRUE.equals(pluginData.getEnabled())) { MotanRegisterConfig motanRegisterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), MotanRegisterConfig.class); MotanRe...
@Test public void testHandlerPlugin() { pluginData.setEnabled(true); pluginData.setConfig("{\"registerAddress\" : \"127.0.0.1:2181\"}"); motanPluginDataHandler.handlerPlugin(pluginData); Assertions.assertEquals(Singleton.INST.get(MotanRegisterConfig.class).getRegisterAddress(), "127....
private AlarmId(DeviceId id, String uniqueIdentifier) { super(id.toString() + ":" + uniqueIdentifier); checkNotNull(id, "device id must not be null"); checkNotNull(uniqueIdentifier, "unique identifier must not be null"); checkArgument(!uniqueIdentifier.isEmpty(), "unique identifier must ...
@Test public void testConstruction() { final AlarmId id1 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_3); assertEquals(id1.toString(), ID_Z.toString()); final AlarmId idString = AlarmId.alarmId(ID_STRING); assertEquals(id1, idString); }
@Override public DeleteConsumerGroupsResult deleteConsumerGroups(Collection<String> groupIds, DeleteConsumerGroupsOptions options) { SimpleAdminApiFuture<CoordinatorKey, Void> future = DeleteConsumerGroupsHandler.newFuture(groupIds); DeleteConsumerGroupsHandler handler = new DeleteCo...
@Test public void testDeleteConsumerGroupsNumRetries() throws Exception { final Cluster cluster = mockCluster(3, 0); final Time time = new MockTime(); final List<String> groupIds = singletonList("groupId"); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster, ...
protected boolean databaseForBothDbInterfacesIsTheSame( DatabaseInterface primary, DatabaseInterface secondary ) { if ( primary == null || secondary == null ) { throw new IllegalArgumentException( "DatabaseInterface shouldn't be null!" ); } if ( primary.getPluginId() == null || secondary.getPluginId(...
@Test public void databases_WithSameDbConnTypes_AreTheSame() { DatabaseInterface mssqlServerDatabaseMeta = new MSSQLServerDatabaseMeta(); mssqlServerDatabaseMeta.setPluginId( "MSSQL" ); assertTrue( databaseMeta.databaseForBothDbInterfacesIsTheSame( mssqlServerDatabaseMeta, mssqlServerDatabaseMeta ) ); }
@Override public StringBuffer format( Date timestamp, StringBuffer toAppendTo, FieldPosition pos ) { if ( compatibleToSuperPattern ) { return super.format( timestamp, toAppendTo, pos ); } SimpleDateFormat defaultMillisecondDateFormat = new SimpleDateFormat( DEFAULT_MILLISECOND_DATE_FORMAT, Locale....
@Test public void testFormat() { for ( Locale locale : locales ) { Locale.setDefault( Locale.Category.FORMAT, locale ); tdb = ResourceBundle.getBundle( "org/pentaho/di/core/row/value/timestamp/messages/testdates", locale ); checkFormat( "KETTLE.LONG" ); checkFormat( "LOCALE.DATE", new Simp...
@Override public Object convert(String value) { if (isNullOrEmpty(value)) { return value; } if (value.contains("=")) { final Map<String, String> fields = new HashMap<>(); Matcher m = PATTERN.matcher(value); while (m.find()) { ...
@Test public void testFilterWithKeysIncludingDashOrUnderscore() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("otters in k-1=v1 k_2=v2 _k3=v3 more otters"); ...
public void draw(List<? extends Pair<Integer, Integer>> coordinateList) { LOGGER.info("Start drawing next frame"); LOGGER.info("Current buffer: " + current + " Next buffer: " + next); frameBuffers[next].clearAll(); coordinateList.forEach(coordinate -> { var x = coordinate.getKey(); var y = c...
@Test void testDraw() { try { var scene = new Scene(); var field1 = Scene.class.getDeclaredField("current"); var field2 = Scene.class.getDeclaredField("next"); field1.setAccessible(true); field1.set(scene, 0); field2.setAccessible(true); field2.set(scene, 1); scene....
@Override public void deleteState(String key) { ensureStateEnabled(); defaultStateStore.delete(key); }
@Test(expectedExceptions = IllegalStateException.class) public void testDeleteStateStateDisabled() { context.deleteState("test-key"); }
@Override public String operation() { return "send"; }
@Test void operation() { assertThat(request.operation()).isEqualTo("send"); }
public boolean doesPluginSupportPasswordBasedAuthentication(String pluginId) { if (!pluginInfos.containsKey(pluginId)) { return false; } return pluginInfos.get(pluginId).getCapabilities().getSupportedAuthType() == SupportedAuthType.Password; }
@Test public void shouldBeAbleToAnswerIfPluginSupportsPasswordBasedAuthentication() throws Exception { assertTrue(store.doesPluginSupportPasswordBasedAuthentication("password.plugin-2")); assertFalse(store.doesPluginSupportPasswordBasedAuthentication("web.plugin-1")); }
public Collection<EvaluatedCondition> getEvaluatedConditions() { return evaluatedConditions; }
@Test public void getEvaluatedConditions_returns_empty_with_no_condition_added_to_builder() { assertThat(builder.getEvaluatedConditions()).isEmpty(); }
public static boolean needOpenTransaction(final SQLStatement sqlStatement) { if (sqlStatement instanceof SelectStatement && !((SelectStatement) sqlStatement).getFrom().isPresent()) { return false; } return sqlStatement instanceof DDLStatement || sqlStatement instanceof DMLStatement; ...
@Test void assertNeedOpenTransactionForDDLOrDMLStatement() { assertTrue(AutoCommitUtils.needOpenTransaction(new MySQLCreateTableStatement(true))); assertTrue(AutoCommitUtils.needOpenTransaction(new MySQLInsertStatement())); }
public void submit(E item) throws ConcurrentConveyorException { submit(queue, item); }
@Test public void when_submit_then_poll() { // when conveyorSingleQueue.submit(item2); // then assertSame(item2, defaultQ.poll()); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void createNewWebmStickerSetAndAddSticker() { String setName = "test" + System.currentTimeMillis() + "_by_pengrad_test_bot"; String[] emojis = new String[]{"\uD83D\uDE00"}; InputSticker[] stickers = new InputSticker[]{new InputSticker(stickerFileVid, Sticker.Format.video, emojis...
@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 testTryLockAsyncSucceed() throws InterruptedException, ExecutionException { RLock lock = redisson.getSpinLock("lock"); Boolean result = lock.tryLockAsync().get(); assertThat(result).isTrue(); lock.unlock(); }
@VisibleForTesting CompleteMultipartUploadResult multipartCopy( S3ResourceId sourcePath, S3ResourceId destinationPath, ObjectMetadata sourceObjectMetadata) throws AmazonClientException { InitiateMultipartUploadRequest initiateUploadRequest = new InitiateMultipartUploadRequest(destinationPath.g...
@Test public void testMultipartCopy() { testMultipartCopy(s3Config("s3")); testMultipartCopy(s3Config("other")); testMultipartCopy(s3ConfigWithSSECustomerKey("s3")); testMultipartCopy(s3ConfigWithSSECustomerKey("other")); }
public Invoker<?> getInvoker() { return invoker; }
@Test void testListenUnExport() throws NoSuchFieldException, IllegalAccessException { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, "loca...
@Override public boolean isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType eventType) { return true; }
@Test public void isAutoTrackEventTypeIgnored() { Assert.assertTrue(mSensorsAPI.isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType.APP_CLICK)); }
public static <T extends Comparable<? super T>> T min(T[] numberArray) { return min(numberArray, null); }
@Test public void minTest() { int min = ArrayUtil.min(1, 2, 13, 4, 5); assertEquals(1, min); long minLong = ArrayUtil.min(1L, 2L, 13L, 4L, 5L); assertEquals(1, minLong); double minDouble = ArrayUtil.min(1D, 2.4D, 13.0D, 4.55D, 5D); assertEquals(1.0, minDouble, 0); }
@Override public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) { AbstractConfig parsedConfig = new AbstractConfig(CONFIG_DEF, props); String filename = parsedConfig.getString(FILE_CONFIG); // We can provide exactly-once semantics if reading from a "real" file // (a...
@Test public void testExactlyOnceSupport() { sourceProperties.put(FileStreamSourceConnector.FILE_CONFIG, FILENAME); assertEquals(ExactlyOnceSupport.SUPPORTED, connector.exactlyOnceSupport(sourceProperties)); sourceProperties.put(FileStreamSourceConnector.FILE_CONFIG, " "); assertEqu...
public static <T> Collection<T> newServiceInstances(final Class<T> service) { return SERVICES.containsKey(service) ? newServiceInstancesFromCache(service) : Collections.<T>emptyList(); }
@Test void newServiceInstances() { SpiTestInterface loadInstance = NacosServiceLoader.load(SpiTestInterface.class).iterator().next(); Collection<SpiTestInterface> actual = NacosServiceLoader.newServiceInstances(SpiTestInterface.class); assertEquals(1, actual.size()); assertEquals(Spi...
public static String removeCR( String in ) { return removeChar( in, '\r' ); }
@Test public void testRemoveCR() { assertEquals( "foo\n\tbar", Const.removeCR( "foo\r\n\tbar" ) ); assertEquals( "", Const.removeCR( "" ) ); assertEquals( "", Const.removeCR( null ) ); assertEquals( "", Const.removeCR( "\r" ) ); assertEquals( "\n\n", Const.removeCR( "\n\r\n" ) ); assertEquals(...
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) { return drlxParse(patternType, bindingId, expression, false); }
@Test public void testMultiplyStringIntWithBindVariableCompareToBigDecimal() { SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "money == likes * 10"); // assuming likes contains number String assertThat(result.getExpr().toString()).isEqualTo(EvaluationU...
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException | JMException e) { return null; } }
@Test public void returnsNullIfAttributeDoesNotExist() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); assertThat(gauge.getValue()).isNull(); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final QueryContext.Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); final SchemaKStream<?> schemaKStream = getSource().buildStream(buildContext); if (!(schemaKStream instanceof SchemaKTable)) {...
@Test @SuppressWarnings("unchecked") public void shouldSuppressOnSchemaKTable() { // Given: when(sourceNode.buildStream(any())).thenReturn(schemaKTable); when(sourceNode.getNodeOutputType()).thenReturn(DataSourceType.KTABLE); node = new SuppressNode(NODE_ID, sourceNode, refinementInfo); // Whe...
@Override public Reader getCharacterStream(final int columnIndex) throws SQLException { return mergedResult.getCharacterStream(columnIndex); }
@Test void assertGetCharacterStream() throws SQLException { Reader reader = mock(Reader.class); when(mergedResult.getCharacterStream(1)).thenReturn(reader); assertThat(new EncryptMergedResult(database, encryptRule, selectStatementContext, mergedResult).getCharacterStream(1), is(reader)); ...
@Override public void publish(ScannerReportWriter writer) { AbstractProjectOrModule rootProject = moduleHierarchy.root(); ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder() .setAnalysisDate(projectInfo.getAnalysisDate().getTime()) // Here we want key without branch ...
@Test @UseDataProvider("projectVersions") public void write_project_version(@Nullable String projectVersion, String expected) { when(projectInfo.getProjectVersion()).thenReturn(Optional.ofNullable(projectVersion)); underTest.publish(writer); ScannerReport.Metadata metadata = reader.readMetadata(); ...
@Override public CompletableFuture<Acknowledge> disconnectTaskManager( final ResourceID resourceID, final Exception cause) { taskManagerHeartbeatManager.unmonitorTarget(resourceID); slotPoolService.releaseTaskManager(resourceID, cause); partitionTracker.stopTrackingPartitionsFor...
@Test void testJobFailureWhenGracefulTaskExecutorTermination() throws Exception { runJobFailureWhenTaskExecutorTerminatesTest( heartbeatServices, (localTaskManagerLocation, jobMasterGateway) -> jobMasterGateway.disconnectTaskManager( ...
public static <K, V> Reshuffle<K, V> of() { return new Reshuffle<>(); }
@Test @Category(ValidatesRunner.class) public void testReshufflePreservesMetadata() { PCollection<KV<String, ValueInSingleWindow<String>>> input = pipeline .apply( Create.windowedValues( WindowedValue.of( "foo", ...
@Override public void updatePort(K8sPort port) { checkNotNull(port, ERR_NULL_PORT); checkArgument(!Strings.isNullOrEmpty(port.portId()), ERR_NULL_PORT_ID); checkArgument(!Strings.isNullOrEmpty(port.networkId()), ERR_NULL_PORT_NET_ID); k8sNetworkStore.updatePort(port); log.in...
@Test(expected = IllegalArgumentException.class) public void testUpdateUnregisteredPort() { target.updatePort(PORT); }
public void init(String keyId, String applicationKey, String exportService) throws BackblazeCredentialsException, IOException { // Fetch all the available buckets and use that to find which region the user is in ListBucketsResponse listBucketsResponse = null; String userRegion = null; // The Key ...
@Test public void testInitBucketNameExists() throws BackblazeCredentialsException, IOException { createEmptyBucketList(); when(s3Client.createBucket(any(CreateBucketRequest.class))) .thenThrow(BucketAlreadyExistsException.builder().build()); BackblazeDataTransferClient client = createDefaultClient...
public long getPathHash() { return pathHash; }
@Test public void test() { RootPathLoadStatistic usageLow = new RootPathLoadStatistic(0L, "/home/disk1", 12345L, TStorageMedium.HDD, 4096L, 1024L, DiskState.ONLINE); RootPathLoadStatistic usageHigh = new RootPathLoadStatistic(0L, "/home/disk2", 67890L, TStorageMedium.HDD, ...
static void activateHttpAndHttpsProxies(Settings settings, SettingsDecrypter decrypter) throws MojoExecutionException { List<Proxy> proxies = new ArrayList<>(2); for (String protocol : ImmutableList.of("http", "https")) { if (areProxyPropertiesSet(protocol)) { continue; } setting...
@Test public void testActivateHttpAndHttpsProxies_noActiveProxy() throws MojoExecutionException { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( noActiveProxiesSettings, settingsDecrypter); Assert.assertNull(System.getProperty("http.proxyHost")); Assert.assertNull(System.getProperty("ht...
@Override public String toString() { return data.toString(); }
@Test public void testToString() { for (short version : LEADER_AND_ISR.allVersions()) { LeaderAndIsrResponse response; if (version < 5) { List<LeaderAndIsrPartitionError> partitions = createPartitions("foo", asList(Errors.NONE, Errors.CLUSTER_A...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMultimapGet() { final String tag = "multimap"; StateTag<MultimapState<byte[], Integer>> addr = StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of()); MultimapState<byte[], Integer> multimapState = underTest.state(NAMESPACE, addr); final byte[] key = "key".getByt...
@Override public int rename(String oldPath, String newPath, int flags) { return AlluxioFuseUtils.call(LOG, () -> renameInternal(oldPath, newPath, flags), FuseConstants.FUSE_RENAME, "oldPath=%s,newPath=%s,", oldPath, newPath); }
@Test public void renameWithLengthLimit() throws Exception { String c256 = String.join("", Collections.nCopies(16, "0123456789ABCDEF")); AlluxioURI oldPath = BASE_EXPECTED_URI.join("/old"); AlluxioURI newPath = BASE_EXPECTED_URI.join("/" + c256); doNothing().when(mFileSystem).rename(oldPath, newPath);...
@VisibleForTesting static DBCollection prepareCollection(final MongoConnection mongoConnection) { DBCollection coll = mongoConnection.getDatabase().getCollection(COLLECTION_NAME); coll.createIndex(DBSort.asc("type"), "unique_type", true); coll.setWriteConcern(WriteConcern.JOURNALED); ...
@Test public void prepareCollectionCreatesCollectionIfItDoesNotExist() throws Exception { @SuppressWarnings("deprecation") final DB database = mongoConnection.getDatabase(); database.getCollection(COLLECTION_NAME).drop(); assertThat(database.collectionExists(COLLECTION_NAME)).isFalse...
public V2 v2() { return v2; }
@Test public void testZeroOthers() { QueryQueueOptions opts = new QueryQueueOptions(true, new QueryQueueOptions.V2(2, 0, 0, 0, 0, 0)); assertThat(opts.v2().getNumWorkers()).isOne(); assertThat(opts.v2().getNumRowsPerSlot()).isOne(); assertThat(opts.v2().getTotalSlots()).isEqualTo(2);...
@Override public void invoke(NamingEvent event) { logInvoke(event); if (listener instanceof AbstractEventListener && ((AbstractEventListener) listener).getExecutor() != null) { ((AbstractEventListener) listener).getExecutor().execute(() -> listener.onEvent(event)); } else { ...
@Test public void testAbstractNamingChaneEventListener() { AbstractNamingChangeListener listener = spy(AbstractNamingChangeListener.class); NamingListenerInvoker listenerInvoker = new NamingListenerInvoker(listener); NamingChangeEvent event = new NamingChangeEvent("serviceName", Collections....
public abstract Map<String, String> renderMap(Map<String, String> inline) throws IllegalVariableEvaluationException;
@Test void renderMap() throws IllegalVariableEvaluationException { RunContext runContext = runContextFactory.of(Map.of( "key", "default", "value", "default" )); Map<String, String> rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}")); assertThat(re...
@Override public CommitWorkStream commitWorkStream() { return windmillStreamFactory.createCommitWorkStream( dispatcherClient.getWindmillServiceStub(), throttleTimers.commitWorkThrottleTimer()); }
@Test // Tests stream retries on server errors before and after `close()` public void testStreamingCommitClosedStream() throws Exception { List<WorkItemCommitRequest> commitRequestList = new ArrayList<>(); List<CountDownLatch> latches = new ArrayList<>(); Map<Long, WorkItemCommitRequest> commitRequests ...
public static JsonObject serialize(RegisteredClient c) { if (c.getSource() != null) { // if we have the original object, just use that return c.getSource(); } else { JsonObject o = new JsonObject(); o.addProperty(CLIENT_ID, c.getClientId()); if (c.getClientSecret() != null) { o.addProperty(CLI...
@Test public void testSerialize() { RegisteredClient c = new RegisteredClient(); c.setClientId("s6BhdRkqt3"); c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk"); c.setClientSecretExpiresAt(new Date(1577858400L * 1000L)); c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83"); c....
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Struct other = (Struct) obj; if (schema != other.schema) return false; ...
@Test public void testEquals() { Struct struct1 = new Struct(FLAT_STRUCT_SCHEMA) .set("int8", (byte) 12) .set("int16", (short) 12) .set("int32", 12) .set("int64", (long) 12) .set("boolean", true) .set("float64", ...
@VisibleForTesting public List<ProjectionContext> planRemoteAssignments(Assignments assignments, VariableAllocator variableAllocator) { ImmutableList.Builder<List<ProjectionContext>> assignmentProjections = ImmutableList.builder(); for (Map.Entry<VariableReferenceExpression, RowExpression> entry...
@Test void testLocalOnly() { PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata()); planBuilder.variable("x", INTEGER); planBuilder.variable("y", INTEGER); PlanRemoteProjections rule = new PlanRemoteProjections(getFunctionAndTypeManage...
public void recycle(MemorySegment segment) { checkArgument(segment != null, "Buffer must be not null."); recycle(Collections.singletonList(segment)); }
@Test void testRecycle() throws Exception { BatchShuffleReadBufferPool bufferPool = createBufferPool(); List<MemorySegment> buffers = bufferPool.requestBuffers(); bufferPool.recycle(buffers); assertThat(bufferPool.getAvailableBuffers()).isEqualTo(bufferPool.getNumTotalBuffers()); ...
public void createCatalog(CreateCatalogStmt stmt) throws DdlException { createCatalog(stmt.getCatalogType(), stmt.getCatalogName(), stmt.getComment(), stmt.getProperties()); }
@Test public void testCreateExceptionMsg() { CatalogMgr catalogMgr = GlobalStateMgr.getCurrentState().getCatalogMgr(); Map<String, String> config = new HashMap<>(); config.put("type", "jdbc"); try { catalogMgr.createCatalog("jdbc", "a", "", config); Assert.f...
@Override public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException { final AttributedList<Path> list = new AttributedList<>(); // avo...
@Test public void testSearchSameDirectory() throws Exception { Assume.assumeTrue(session.getClient().existsAndIsAccessible(testPathPrefix.getAbsolute())); final String newDirectoryName = new AlphanumericRandomStringService().random(); final Path newDirectory = new Path(testPathPrefix, newDi...
@Override public Set<K8sApiConfig> apiConfigs() { return configStore.apiConfigs(); }
@Test public void testGetAllNodes() { assertEquals(ERR_SIZE, 2, target.apiConfigs().size()); assertTrue(ERR_NOT_FOUND, target.apiConfigs().contains(apiConfig2)); assertTrue(ERR_NOT_FOUND, target.apiConfigs().contains(apiConfig3)); }
private void withdraw(ResolvedRoute route) { synchronized (this) { IpPrefix prefix = route.prefix(); MultiPointToSinglePointIntent intent = routeIntents.remove(prefix); if (intent == null) { log.trace("No intent in routeIntents to delete for prefix: {}", ...
@Test public void testRouteDelete() { // Add a route first testRouteAddToNoVlan(); // Construct the existing route entry ResolvedRoute route = createRoute(PREFIX1, IP3, MAC3); // Create existing intent MultiPointToSinglePointIntent removedIntent = cr...
@Override public FileMergingCheckpointStateOutputStream createCheckpointStateOutputStream( CheckpointedStateScope scope) throws IOException { return fileMergingSnapshotManager.createCheckpointStateOutputStream( subtaskKey, checkpointId, scope); }
@Test public void testWritingToClosedStream() { FileMergingSnapshotManager snapshotManager = createFileMergingSnapshotManager(); FsMergingCheckpointStorageLocation storageLocation = createFsMergingCheckpointStorageLocation(1, snapshotManager); try (FileMergingCheckpointStateO...
public void schedule(Node<K, V> node) { Node<K, V> sentinel = findBucket(node.getVariableTime()); link(sentinel, node); }
@Test(dataProvider = "schedule") public void schedule(long clock, long duration, int expired) { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; for (int timeout : new int[] { 25, 90, 240 }) { timerWheel.schedule(new Timer(clock + TimeUnit.SECON...
public Object runScript(String src) throws PropertyException { try { JexlScript script = JEXL.createScript(src); ObjectContext<PropertyManager> context = new ObjectContext<>(JEXL, this); return script.execute(context); } catch(JexlException je) { throw new PropertyException("script faile...
@Test public void testSerDerScript() { runSerDer(() -> { return (boolean) manager.runScript( "setProperty('framework', 'llap');" + "setProperty('ser.store', 'Parquet');" + "setProperty('ser.der.id', 42);" + "setProperty('ser.der.name', 'serder');" + ...
@Override protected Result[] run(String value) { final Map<String, Object> extractedJson; try { extractedJson = extractJson(value); } catch (IOException e) { throw new ExtractorException(e); } final List<Result> results = new ArrayList<>(extractedJson....
@Test public void testRunWithScalarValues() throws Exception { final String value = "{\"text\": \"foobar\", \"number\": 1234.5678, \"bool\": true, \"null\": null}"; final Extractor.Result[] results = jsonExtractor.run(value); assertThat(results).contains( new Extractor.Resul...