focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static boolean shouldLoadInIsolation(String name) { return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches()); }
@Test public void testConnectApiClasses() { List<String> apiClasses = Arrays.asList( // Enumerate all packages and classes "org.apache.kafka.connect.", "org.apache.kafka.connect.components.", "org.apache.kafka.connect.components.Versioned", //"org....
public Span nextSpan(Message message) { TraceContextOrSamplingFlags extracted = extractAndClearTraceIdProperties(processorExtractor, message, message); Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler. // When an upstream context was not present, lookup keys are unl...
@Test void nextSpan_should_tag_queue_when_no_incoming_context() { message.setDestination(createDestination("foo", QUEUE_TYPE)); jmsTracing.nextSpan(message).start().finish(); assertThat(testSpanHandler.takeLocalSpan().tags()) .containsOnly(entry("jms.queue", "foo")); }
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { TikaInputStream tis = TikaInputStream.get(stream); Database db = null; XHTMLContentHandler xhtml = new XHTM...
@Test public void testBasic() throws Exception { RecursiveParserWrapper w = new RecursiveParserWrapper(AUTO_DETECT_PARSER); for (String fName : new String[]{"testAccess2.accdb", "testAccess2_2000.mdb", "testAccess2_2002-2003.mdb"}) { InputStream is = null; R...
private static Row selectRow( Row input, FieldAccessDescriptor fieldAccessDescriptor, Schema inputSchema, Schema outputSchema) { if (fieldAccessDescriptor.getAllFields()) { return input; } Row.Builder output = Row.withSchema(outputSchema); selectIntoRow(inputSchema, input,...
@Test public void testSelectNullableNestedRow() { FieldAccessDescriptor fieldAccessDescriptor1 = FieldAccessDescriptor.withFieldNames("nested.field1").resolve(NESTED_NULLABLE_SCHEMA); Row out1 = selectRow( NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1, Row.nullRow(NESTED_NULLABLE_...
public static String[] splitToSteps(String path, boolean preserveRootAsStep) { if (path == null) { return null; } if (preserveRootAsStep && path.equals(SHARE_ROOT)) { return new String[] { SHARE_ROOT }; } var includeRoot = preserveRootAsStep && path.star...
@Test void splitRootPreservingRootShouldReturnRoot() { assertArrayEquals(new String[] { "/" }, FilesPath.splitToSteps("/", true)); }
@Override public Catalog createCatalog(Context context) { final FactoryUtil.CatalogFactoryHelper helper = FactoryUtil.createCatalogFactoryHelper(this, context); helper.validate(); return new HiveCatalog( context.getName(), helper.getOptions()....
@Test public void testCreateHiveCatalogWithHadoopConfDir() throws IOException { final String catalogName = "mycatalog"; final String hadoopConfDir = tempFolder.newFolder().getAbsolutePath(); final File mapredSiteFile = new File(hadoopConfDir, "mapred-site.xml"); final String mapredK...
@Override public List<ResourceReference> getResourceDependencies( TransMeta transMeta, StepMeta stepInfo ) { List<ResourceReference> references = new ArrayList<ResourceReference>( 5 ); String realFilename = transMeta.environmentSubstitute( fileName ); String realTransname = transMeta.environmentSubstitute...
@Test public void getResourceDependencies() { TransMeta transMeta = mock( TransMeta.class ); StepMeta stepMeta = mock( StepMeta.class ); List<ResourceReference> actualResult = metaInjectMeta.getResourceDependencies( transMeta, stepMeta ); assertEquals( 1, actualResult.size() ); ResourceReference ...
@Override public void visit(Entry entry) { if(Boolean.FALSE.equals(entry.getAttribute("allowed"))) return; if (containsSubmenu(entry)) addSubmenu(entry); else addActionItem(entry); }
@Test public void createsGroupWithAction() { Entry parentMenuEntry = new Entry(); final JMenu parentMenu = new JMenu(); new EntryAccessor().setComponent(parentMenuEntry, parentMenu); parentMenuEntry.addChild(groupEntry); groupEntry.addChild(actionEntry); new EntryAccessor().setAction(groupEntry, action); ...
@Override public UnregisterBrokerResult unregisterBroker(int brokerId, UnregisterBrokerOptions options) { final KafkaFutureImpl<Void> future = new KafkaFutureImpl<>(); final long now = time.milliseconds(); final Call call = new Call("unregisterBroker", calcDeadlineMs(now, options.timeoutMs()...
@Test public void testUnregisterBrokerTimeoutMaxRetry() { int nodeId = 1; try (final AdminClientUnitTestEnv env = mockClientEnv(Time.SYSTEM, AdminClientConfig.RETRIES_CONFIG, "1")) { env.kafkaClient().setNodeApiVersions( NodeApiVersions.create(ApiKeys.UNREGISTER_BROKE...
@Override public Status check() { if (applicationContext == null) { SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel); applicationContext = springExtensionInjector.getContext(); } if (applicationContext == null) { ...
@Test void testWithoutApplicationContext() { Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); }
public void add(short metricId, MetricValues metricValuesToAdd) { validateNotNull(metricValuesToAdd, "The metric values to be added cannot be null"); if (!_metricValues.isEmpty() && metricValuesToAdd.length() != length()) { throw new IllegalArgumentException("The existing metric length is " + length() + "...
@Test public void testAdd() { Map<Short, MetricValues> valuesByMetricId = getValuesByMetricId(); AggregatedMetricValues aggregatedMetricValues = new AggregatedMetricValues(valuesByMetricId); aggregatedMetricValues.add(aggregatedMetricValues); for (Map.Entry<Short, MetricValues> entry : valuesByMetri...
public Optional<String> validate(MonitoringInfo monitoringInfo) { if (monitoringInfo.getUrn().isEmpty() || monitoringInfo.getType().isEmpty()) { return Optional.of( String.format( "MonitoringInfo requires both urn %s and type %s to be specified.", monitoringInfo.getUrn()...
@Test public void validateReturnsNoErrorOnValidMonitoringInfo() { MonitoringInfo testInput = MonitoringInfo.newBuilder() .setUrn(Urns.USER_SUM_INT64) .putLabels(MonitoringInfoConstants.Labels.NAME, "anyCounter") .putLabels(MonitoringInfoConstants.Labels.NAMESPACE, "") ...
@VisibleForTesting public Optional<ProcessContinuation> run( PartitionMetadata partition, HeartbeatRecord record, RestrictionTracker<TimestampRange, Timestamp> tracker, ManualWatermarkEstimator<Instant> watermarkEstimator) { final String token = partition.getPartitionToken(); LOG.debu...
@Test public void testRestrictionClaimed() { final String partitionToken = "partitionToken"; final Timestamp timestamp = Timestamp.ofTimeMicroseconds(10L); when(tracker.tryClaim(timestamp)).thenReturn(true); when(partition.getPartitionToken()).thenReturn(partitionToken); final Optional<ProcessCo...
@Override public int run() throws IOException { Preconditions.checkArgument(sourceFiles != null && !sourceFiles.isEmpty(), "Missing file name"); // Ensure all source files have the columns specified first Map<String, Schema> schemas = new HashMap<>(); for (String sourceFile : sourceFiles) { Sch...
@Test public void testScanCommandWithMultipleSourceFiles() throws IOException { File file = parquetFile(); ScanCommand command = new ScanCommand(createLogger()); command.sourceFiles = Arrays.asList(file.getAbsolutePath(), file.getAbsolutePath()); command.setConf(new Configuration()); Assert.assert...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { if(!session.getClient().changeWorkingDirectory(directory.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.g...
@Test public void testListEmpty() throws Exception { final ListService list = new FTPMlsdListService(session); final Path directory = new FTPWorkdirService(session).find(); assertTrue(list.list(directory, new DisabledListProgressListener()).isEmpty()); }
public <T> SideInput<T> fetchSideInput( PCollectionView<T> view, BoundedWindow sideWindow, String stateFamily, SideInputState state, Supplier<Closeable> scopedReadStateSupplier) { Callable<SideInput<T>> loadSideInputFromWindmill = () -> loadSideInputFromWindmill(view, sideWindo...
@Test public void testFetchGlobalDataBasic() throws Exception { SideInputStateFetcherFactory factory = SideInputStateFetcherFactory.fromOptions( PipelineOptionsFactory.as(DataflowStreamingPipelineOptions.class)); SideInputStateFetcher fetcher = factory.createSideInputStateFetcher(server::g...
@Override protected ExecuteContext doBefore(ExecuteContext context) { LogUtils.printHttpRequestBeforePoint(context); Request request = (Request) context.getObject(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Request''s classloader is {0}, jettyClientWrapper''s ...
@Test public void test() { // Test for normal conditions JettyClientWrapper wrapper = Mockito.spy(new JettyClientWrapper(Mockito.mock(HttpClient.class), new HttpConversation(), HELLO_URI)); ReflectUtils.setFieldValue(wrapper, HttpConstants.HTTP_URI_HOST, "www.domain.com"); ...
@SuppressWarnings("ConstantConditions") private Queue<Comment> getComments() { LOG.debug("Start: Jira NewCommentsConsumer: retrieving issue comments. Last comment id: {}", lastCommentId); IssueRestClient client = getEndpoint().getClient().getIssueClient(); LinkedList<Comment> newComments = ...
@Test public void singleIssueCommentsTest() throws Exception { Issue issueWithComments = createIssueWithComments(11L, 3000); Issue issueWithNoComments = createIssue(51L); List<Issue> newIssues = List.of(issueWithComments, issueWithNoComments); SearchResult result = new SearchResult(...
public static Class<?> getGenericClass(Class<?> cls) { return getGenericClass(cls, 0); }
@Test void testGetGenericClass() { assertThat(ReflectUtils.getGenericClass(Foo1.class), sameInstance(String.class)); }
public static void format(Mode mode, AlluxioConfiguration alluxioConf) throws IOException { NoopUfsManager noopUfsManager = new NoopUfsManager(); switch (mode) { case MASTER: URI journalLocation = JournalUtils.getJournalLocation(); LOG.info("Formatting master journal: {}", journalLocation)...
@Test public void formatWorker() throws Exception { final int storageLevels = 1; final String perms = "rwx------"; String workerDataFolder; final File[] dirs = new File[] { mTemporaryFolder.newFolder("level0") }; for (File dir : dirs) { workerDataFolder = CommonUtils.getWorkerDat...
public FEELFnResult<Range> invoke(@ParameterName("from") String from) { if (from == null || from.isEmpty() || from.isBlank()) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "from", "cannot be null")); } Range.RangeBoundary startBoundary; if...
@Test void invokeDifferentTypes() { List<String> from = Arrays.asList("[1..\"cheese\"]", "[1..date(\"1978-09-12\")]", "[1..date(\"1978-09-12\")]", "[1..\"upper case(\"aBc4\")\"]"); ...
public static String getSonarqubeVersion() { if (sonarqubeVersion == null) { loadVersion(); } return sonarqubeVersion; }
@Test public void getSonarQubeVersion_must_not_return_an_empty_string() { assertThat(SonarQubeVersionHelper.getSonarqubeVersion()).isNotEmpty(); }
private static void instanceTrackingConfig(XmlGenerator gen, Config config) { InstanceTrackingConfig trackingConfig = config.getInstanceTrackingConfig(); gen.open("instance-tracking", "enabled", trackingConfig.isEnabled()) .node("file-name", trackingConfig.getFileName()) ...
@Test public void testInstanceTrackingConfig() { Config config = new Config(); config.getInstanceTrackingConfig() .setEnabled(true) .setFileName("/dummy/file") .setFormatPattern("dummy-pattern with $HZ_INSTANCE_TRACKING{placeholder} and $RND{placehold...
static TaskExecutorResourceSpec resourceSpecFromConfig(Configuration config) { try { checkTaskExecutorResourceConfigSet(config); } catch (IllegalConfigurationException e) { throw new IllegalConfigurationException("Failed to create TaskExecutorResourceSpec", e); } ...
@Test void testResourceSpecFromConfigFailsIfRequiredOptionIsNotSet() { TaskExecutorResourceUtils.CONFIG_OPTIONS.stream() .filter(option -> !option.hasDefaultValue()) .forEach( option -> { assertThatThrownBy( ...
@Override void execute() throws HiveMetaException { // Need to confirm unless it's a dry run or specified -yes if (!schemaTool.isDryRun() && !this.yes) { boolean confirmed = promptToConfirm(); if (!confirmed) { System.out.println("Operation cancelled, exiting."); return; } ...
@Test public void testExecutePromptYes() throws Exception { setUpTwoDatabases(); mockPromptWith("y"); uut.execute(); Mockito.verify(stmtMock).execute("DROP DATABASE `mydb` CASCADE"); Mockito.verify(stmtMock).execute(String.format("DROP TABLE `%s`.`table1`", Warehouse.DEFAULT_DATABASE_NAME)); ...
@Override public void setUpperRightX(float value) { throw new UnsupportedOperationException("Immutable class"); }
@Test void testSetUpperRightX() { Assertions.assertThrows(UnsupportedOperationException.class, () -> rect.setUpperRightX(0)); }
public StringSubject factValue(String key) { return doFactValue(key, null); }
@Test public void factValueIntFailNoValue() { Object unused = expectFailureWhenTestingThat(simpleFact("foo")).factValue("foo", 0); assertFailureKeys( "expected to have a value", "for key", "and index", "but the key was present with no value", HOW_TO_TEST_KEYS_WITHOUT_VA...
@Override public void onMetaDataChanged(final List<MetaData> metaDataList, final DataEventTypeEnum eventType) { WebsocketData<MetaData> configData = new WebsocketData<>(ConfigGroupEnum.META_DATA.name(), eventType.name(), metaDataList); WebsocketCollector.send(GsonUtils.getInstance()....
@Test public void testOnMetaDataChanged() { String message = "{\"groupType\":\"META_DATA\",\"eventType\":\"CREATE\",\"data\":[{\"appName\":\"axiba\"," + "\"path\":\"/test/execute\",\"rpcType\":\"http\",\"serviceName\":\"execute\",\"methodName\":" + "\"execute\",\"parameterTyp...
@Override public RestResponse<List<StreamedRow>> makeQueryRequest( final URI serverEndPoint, final String sql, final Map<String, ?> configOverrides, final Map<String, ?> requestProperties ) { final KsqlTarget target = sharedClient .target(serverEndPoint) .properties(conf...
@Test public void shouldSetQueryTimeout() { // Given: when(ksqlConfig.getLong(KsqlConfig.KSQL_QUERY_PULL_FORWARDING_TIMEOUT_MS_CONFIG)) .thenReturn(300L); // When: final RestResponse<List<StreamedRow>> result = client.makeQueryRequest(SERVER_ENDPOINT, "Sql", ImmutableMap.of(), Immutab...
static Optional<SearchPath> fromString(String path) { if (path == null || path.isEmpty()) { return Optional.empty(); } if (path.indexOf(';') >= 0) { return Optional.empty(); // multi-level not supported at this time } try { SearchPath sp = pars...
@Test void requreThatWildcardsAreDetected() { assertFalse(SearchPath.fromString("").isPresent()); assertFalse(SearchPath.fromString("*/*").isPresent()); assertFalse(SearchPath.fromString("/").isPresent()); assertFalse(SearchPath.fromString("/*").isPresent()); assertFalse(Sear...
public void update(State state, String summary) { if (canTransferToState(state)) { _state = state; _summary = Utils.validateNotNull(summary, "ProvisionerState summary cannot be null."); _updatedMs = System.currentTimeMillis(); } else { throw new IllegalStateException("Cannot set the prov...
@Test public void testProvisionerStateInvalidUpdateThrowsException() { ProvisionerState.State originalState = ProvisionerState.State.IN_PROGRESS; String originalSummary = "Test summary."; ProvisionerState provisionerState = new ProvisionerState(originalState, originalSummary); ProvisionerState.State u...
public static void checkValidProjectId(String idToCheck) { if (idToCheck.length() < MIN_PROJECT_ID_LENGTH) { throw new IllegalArgumentException("Project ID " + idToCheck + " cannot be empty."); } if (idToCheck.length() > MAX_PROJECT_ID_LENGTH) { throw new IllegalArgumentException( "Pro...
@Test public void testCheckValidProjectIdWhenIdIsEmpty() { assertThrows(IllegalArgumentException.class, () -> checkValidProjectId("")); }
public String storeName() { if (storeSupplier != null) { return storeSupplier.name(); } return storeName; }
@Test public void shouldUseProvidedStoreNameWhenSet() { final String storeName = "store-name"; final MaterializedInternal<Object, Object, StateStore> materialized = new MaterializedInternal<>(Materialized.as(storeName), nameProvider, prefix); assertThat(materialized.storeName(), ...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaimonTable that = (PaimonTable) o; return catalogName.equals(that.catalogName) && databa...
@Test public void testEquals(@Mocked FileStoreTable paimonNativeTable) { String dbName = "testDB"; String tableName = "testTable"; PaimonTable table = new PaimonTable("testCatalog", dbName, tableName, null, paimonNativeTable, 100L); PaimonTable table2 = new PaimonTabl...
public Set<MapperConfig> load(InputStream inputStream) throws IOException { final PrometheusMappingConfig config = ymlMapper.readValue(inputStream, PrometheusMappingConfig.class); return config.metricMappingConfigs() .stream() .flatMap(this::mapMetric) .c...
@Test void defaultType() throws Exception { final Map<String, ImmutableList<Serializable>> config = Collections.singletonMap("metric_mappings", ImmutableList.of( ImmutableMap.of("metric_name", "test1", "match_pattern", "foo.bar"))); assertThat(configLoader.l...
@Description("Returns the closure of the combinatorial boundary of this Geometry") @ScalarFunction("ST_Boundary") @SqlType(GEOMETRY_TYPE_NAME) public static Slice stBoundary(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { return serialize(deserialize(input).getBoundary()); }
@Test public void testSTBoundary() { assertFunction("ST_AsText(ST_Boundary(ST_GeometryFromText('POINT (1 2)')))", VARCHAR, "GEOMETRYCOLLECTION EMPTY"); assertFunction("ST_AsText(ST_Boundary(ST_GeometryFromText('MULTIPOINT (1 2, 2 4, 3 6, 4 8)')))", VARCHAR, "GEOMETRYCOLLECTION EMPTY"); a...
@Override public void update(double sampleValue) { double oldMean = onlineMeanCalculator.getValue(); onlineMeanCalculator.update(sampleValue); numSamples++; double newMean = onlineMeanCalculator.getValue(); m2 += (sampleValue - oldMean) * (sampleValue - newMean); }
@Test void insufficientSamples() { WelfordVarianceCalculator calculator = new WelfordVarianceCalculator(); calculator.update(1.23d); assertThrows(NotEnoughSampleException.class, calculator::getValue); }
protected double getOsnr(JsonNode connectivityReply, String name) { double osnr = -1; if (connectivityReply.has("result") && connectivityReply.get("result").has("response")) { Iterator<JsonNode> paths = connectivityReply.get("result").get("response") .elem...
@Test public void testGetOsnr() throws IOException { double osnr = manager.getOsnr(reply, "second"); assertEquals(23.47, osnr); }
@Override public void load() throws AccessDeniedException { final Local file = this.getFile(); if(file.exists()) { if(log.isInfoEnabled()) { log.info(String.format("Found bookmarks file at %s", file)); } Checksum current = Checksum.NONE; ...
@Test public void testLoad() throws Exception { final Local source = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random()); LocalTouchFactory.get().touch(source); IOUtils.write(RandomUtils.nextBytes(1000), source.getOutputStream(false)); fina...
@Override public SeekableByteChannel getChannel() { return new RedissonByteChannel(); }
@Test public void testChannelPosition() throws IOException { RBinaryStream stream = redisson.getBinaryStream("test"); SeekableByteChannel c = stream.getChannel(); c.write(ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7})); c.position(3); ByteBuffer b = ByteBuffer.allocate(3); ...
public Meter getBrokerMeter() { return brokerMeter; }
@Test public void testCreateMetricsManagerLogType() throws CloneNotSupportedException { BrokerConfig brokerConfig = new BrokerConfig(); brokerConfig.setMetricsExporterType(MetricsExporterType.LOG); brokerConfig.setMetricsLabel("label1:value1;label2:value2"); brokerConfig.setMetricsOt...
@Override public ExecuteContext onThrow(ExecuteContext context) { ThreadLocalUtils.removeRequestData(); LogUtils.printHttpRequestOnThrowPoint(context); return context; }
@Test public void testOnThrow() { ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", "")); interceptor.onThrow(context); Assert.assertNull(ThreadLocalUtils.getRequestData()); }
public static boolean isJsonValid(String schemaText, String jsonText) throws IOException { return isJsonValid(schemaText, jsonText, null); }
@Test void testValidateJsonSchemaWithReferenceSuccess() { boolean valid = true; String schemaText = null; String jsonText = "[{\"name\": \"307\", \"model\": \"Peugeot 307\", \"year\": 2003}," + "{\"name\": \"jean-pierre\", \"model\": \"Peugeot Traveler\", \"year\": 2017}]"; try {...
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) { if (null == source) { return null; } T target = ReflectUtil.newInstanceIfPossible(tClass); copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); return target; }
@Test public void copyBeanTest() { final Food info = new Food(); info.setBookID("0"); info.setCode("123"); final Food newFood = BeanUtil.copyProperties(info, Food.class, "code"); assertEquals(info.getBookID(), newFood.getBookID()); assertNull(newFood.getCode()); }
@InvokeOnHeader(Web3jConstants.ETH_GET_TRANSACTION_BY_HASH) void ethGetTransactionByHash(Message message) throws IOException { String transactionHash = message.getHeader(Web3jConstants.TRANSACTION_HASH, configuration::getTransactionHash, String.class); Request<?, EthTransaction> requ...
@Test public void ethGetTransactionByHashTest() throws Exception { EthTransaction response = Mockito.mock(EthTransaction.class); Mockito.when(mockWeb3j.ethGetTransactionByHash(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Transaction transaction = Mo...
@Override public Optional<SearchVersion> version() { final Request request = new Request("GET", "/?filter_path=version.number,version.distribution"); final Optional<JsonNode> resp = Optional.of(jsonApi.perform(request, "Unable to retrieve cluster information")); final Optional<String> vers...
@Test void testOpensearchVersionFetching() throws IOException { mockResponse("{\"version\" : " + " {" + " \"distribution\" : \"opensearch\"," + " \"number\" : \"1.3.1\"" + " }" + "}"); assertThat(toTest.version(...
static String escapeAndJoin(List<String> parts) { return parts.stream() .map(ZetaSqlIdUtils::escapeSpecialChars) .map(ZetaSqlIdUtils::replaceWhitespaces) .map(ZetaSqlIdUtils::backtickIfNeeded) .collect(joining(".")); }
@Test public void testHandlesSpecialCharsInOnePart() { List<String> id = Arrays.asList("a\\ab`bc'cd\"de?e"); assertEquals("`a\\\\ab\\`bc\\'cd\\\"de\\?e`", ZetaSqlIdUtils.escapeAndJoin(id)); }
public static void copyConfigurationToJob(Properties props, Map<String, String> jobProps) throws HiveException, IOException { checkRequiredPropertiesAreDefined(props); resolveMetadata(props); for (Entry<Object, Object> entry : props.entrySet()) { String key = String.valueOf(entry.getKey()); ...
@Test public void testWithAllRequiredSettingsDefined() throws Exception { Properties props = new Properties(); props.put(JdbcStorageConfig.DATABASE_TYPE.getPropertyName(), DatabaseType.MYSQL.toString()); props.put(JdbcStorageConfig.JDBC_URL.getPropertyName(), "jdbc://localhost:3306/hive"); props.put(J...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_contains_successWithNegativeZero() { assertThat(array(1.0f, -0.0f, 3.0f)).usingTolerance(0.0f).contains(0.0f); }
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testNoRedirectWithData() throws Exception { createHttpFSServer(false, false); final String path = "/file"; final String username = HadoopUsersConfTestHelper.getHadoopUsers()[0]; // file creation which should not redirect URL url = new URL(Test...
public <T> Mono<CosmosItemResponse<T>> replaceItem( final T item, final String itemId, final PartitionKey partitionKey, final CosmosItemRequestOptions itemRequestOptions) { CosmosDbUtils.validateIfParameterIsNotEmpty(item, PARAM_ITEM); CosmosDbUtils.validateIfParameterIsNotEmpty(...
@Test void replaceItem() { final CosmosDbContainerOperations operations = new CosmosDbContainerOperations(Mono.just(mock(CosmosAsyncContainer.class))); CosmosDbTestUtils.assertIllegalArgumentException(() -> operations.replaceItem(null, null, null, null)); CosmosDbTestUtils.a...
@Override public void write(DataOutput out) throws IOException { // save history SerializeData data = new SerializeData(); data.jobs = getAllNativeAnalyzeJobList(); data.nativeStatus = new ArrayList<>(getAnalyzeStatusMap().values().stream(). filter(AnalyzeStatus::isNa...
@Test public void testExternalAnalyzeStatusPersist() throws Exception { Table table = connectContext.getGlobalStateMgr().getMetadataMgr().getTable("hive0", "partitioned_db", "t1"); ExternalAnalyzeStatus analyzeStatus = new ExternalAnalyzeStatus(100, "hive0", "partitioned_db", "t1", ...
@Override public void open() { super.open(); for (String propertyKey : properties.stringPropertyNames()) { LOGGER.debug("propertyKey: {}", propertyKey); String[] keyValue = propertyKey.split("\\.", 2); if (2 == keyValue.length) { LOGGER.debug("key: {}, value: {}", keyValue[0], keyVal...
@Test void testIncorrectStatementPrecode() throws IOException, InterpreterException { Properties properties = new Properties(); properties.setProperty("default.driver", "org.h2.Driver"); properties.setProperty("default.url", getJdbcConnection()); properties.setProperty("default.user", ""); ...
@Override public CompletableFuture<Acknowledge> requestSlot( final SlotID slotId, final JobID jobId, final AllocationID allocationId, final ResourceProfile resourceProfile, final String targetAddress, final ResourceManagerId resourceManagerId, ...
@Test void testSlotAcceptance() throws Exception { final InstanceID registrationId = new InstanceID(); final OneShotLatch taskExecutorIsRegistered = new OneShotLatch(); final CompletableFuture<Tuple3<InstanceID, SlotID, AllocationID>> availableSlotFuture = new CompletableFutu...
public static String toString(Object obj) { if (null == obj) { return null; } if (obj instanceof long[]) { return Arrays.toString((long[]) obj); } else if (obj instanceof int[]) { return Arrays.toString((int[]) obj); } else if (obj instanceof short[]) { return Arrays.toString((short[]) obj); } ...
@Test public void toStingTest() { int[] a = {1, 3, 56, 6, 7}; assertEquals("[1, 3, 56, 6, 7]", ArrayUtil.toString(a)); long[] b = {1, 3, 56, 6, 7}; assertEquals("[1, 3, 56, 6, 7]", ArrayUtil.toString(b)); short[] c = {1, 3, 56, 6, 7}; assertEquals("[1, 3, 56, 6, 7]", ArrayUtil.toString(c)); double[] d = ...
public void addProperty(String key, String value) { store.put(key, value); }
@Test void testConversions() { memConfig.addProperty("long", "2147483648"); memConfig.addProperty("byte", "127"); memConfig.addProperty("short", "32767"); memConfig.addProperty("float", "3.14"); memConfig.addProperty("double", "3.14159265358979323846264338327950"); me...
@Override public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { // 校验旧密码密码 validateOldPassword(id, reqVO.getOldPassword()); // 执行更新 AdminUserDO updateObj = new AdminUserDO().setId(id); updateObj.setPassword(encodePassword(reqVO.getNewPassword())); //...
@Test public void testUpdateUserPassword02_success() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); // 准备参数 Long userId = dbUser.getId(); String password = "yudao"; // mock 方法 when(passwordEncoder.encode(anyString()))...
public boolean hasLeadership() { return (state.get() == State.STARTED) && hasLeadership.get(); }
@Test public void testSessionInterruptionDoNotCauseBrainSplit() throws Exception { final String latchPath = "/testSessionInterruptionDoNotCauseBrainSplit"; final Timing2 timing = new Timing2(); final BlockingQueue<TestEvent> events0 = new LinkedBlockingQueue<>(); final BlockingQueue<...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<>(); if(replies.isEmpty()) { return children; } // At least one entry successfully parsed...
@Test public void testParseMlsdMode775() throws Exception { Path path = new Path( "/www", EnumSet.of(Path.Type.directory)); String[] replies = new String[]{ "modify=20090210192929;perm=fle;type=dir;unique=FE03U10006D95;UNIX.group=1001;UNIX.mode=02775;UNIX.owner=2000; ...
public void initialize(ProxyConfiguration conf) throws Exception { for (ProxyExtension extension : extensions.values()) { extension.initialize(conf); } }
@Test public void testInitialize() throws Exception { ProxyConfiguration conf = new ProxyConfiguration(); extensions.initialize(conf); verify(extension1, times(1)).initialize(same(conf)); verify(extension2, times(1)).initialize(same(conf)); }
public static String getTieredStoragePath(String basePath) { return String.format("%s/%s", basePath, TIERED_STORAGE_DIR); }
@Test void testGetTieredStoragePath() { String tieredStoragePath = SegmentPartitionFile.getTieredStoragePath(tempFolder.getPath()); assertThat(tieredStoragePath) .isEqualTo(new File(tempFolder.getPath(), TIERED_STORAGE_DIR).getPath()); }
@Override protected boolean hasPortfolioChildProjectsPermission(String permission, String portfolioUuid) { return false; }
@Test public void hasPortfolioChildProjectsPermission() { assertThat(githubWebhookUserSession.hasPortfolioChildProjectsPermission("perm", "project")).isFalse(); }
public String convertInt(int i) { return convert(i); }
@Test public void testSmoke() { FileNamePattern pp = new FileNamePattern("t", context); assertEquals("t", pp.convertInt(3)); pp = new FileNamePattern("foo", context); assertEquals("foo", pp.convertInt(3)); pp = new FileNamePattern("%i foo", context); assertEquals("...
public static OffsetAndMetadata fromRequest( OffsetCommitRequestData.OffsetCommitRequestPartition partition, long currentTimeMs, OptionalLong expireTimestampMs ) { return new OffsetAndMetadata( partition.committedOffset(), ofSentinel(partition.committedLeaderE...
@Test public void testFromRequest() { MockTime time = new MockTime(); OffsetCommitRequestData.OffsetCommitRequestPartition partition = new OffsetCommitRequestData.OffsetCommitRequestPartition() .setPartitionIndex(0) .setCommittedOffset(100L) ...
void handleSegmentWithDeleteSegmentStartedState(Long startOffset, RemoteLogSegmentId remoteLogSegmentId) { // Remove the offset mappings as this segment is getting deleted. offsetToId.remove(startOffset, remoteLogSegmentId); // Add this entry to unreferenced set for the leader epoch as it is be...
@Test void handleSegmentWithDeleteSegmentStartedState() { RemoteLogSegmentId segmentId1 = new RemoteLogSegmentId(tpId, Uuid.randomUuid()); RemoteLogSegmentId segmentId2 = new RemoteLogSegmentId(tpId, Uuid.randomUuid()); epochState.handleSegmentWithCopySegmentFinishedState(10L, segmentId1, 10...
public long addAndGet(long value) { this.value += value; return this.value; }
@Test public void testAddAndGet() { MutableLong mutableLong = MutableLong.valueOf(13); assertEquals(24L, mutableLong.addAndGet(11)); assertEquals(24L, mutableLong.value); }
public AscendingLongIterator iterator() { return new IteratorImpl(storages); }
@Test public void testIteratorAdvanceAtLeastToDistinctPrefixes() { long prefix = ((long) Integer.MAX_VALUE * 2 + 1); set(0); verifyAdvanceAtLeastTo(); set(prefix + 1); verifyAdvanceAtLeastTo(); set(prefix * 3 + 1); verifyAdvanceAtLeastTo(); set(prefix...
public static Ip4Address valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new Ip4Address(bytes); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfArrayInvalidOffsetIPv4() { Ip4Address ipAddress; byte[] value; value = new byte[] {11, 22, 33, // Preamble 1, 2, 3, 4, 44, 55}; ...
public static DescriptorDigest fromDigest(String digest) throws DigestException { if (!digest.matches(DIGEST_REGEX)) { throw new DigestException("Invalid digest: " + digest); } // Extracts the hash portion of the digest. String hash = digest.substring(DIGEST_PREFIX.length()); return new Descr...
@Test public void testCreateFromDigest_fail() { String badDigest = "sha256:not a valid digest"; try { DescriptorDigest.fromDigest(badDigest); Assert.fail("Invalid digest should have caused digest creation failure."); } catch (DigestException ex) { Assert.assertEquals("Invalid digest: " ...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel()); ...
@Test public void toProtobuf_whenEnabledIdentityProviders_shouldWriteThem() { when(commonSystemInformation.getEnabledIdentityProviders()).thenReturn(List.of("Bitbucket, GitHub")); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Accepted external identity pro...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final Instant lower = calculateLowerBound(windowSt...
@Test @SuppressWarnings("unchecked") public void shouldThrowIfQueryFails_fethAll() { // Given: final StateQueryResult<?> partitionResult = new StateQueryResult<>(); partitionResult.addResult(PARTITION, QueryResult.forFailure(FailureReason.STORE_EXCEPTION, "Boom")); when(kafkaStreams.query(any(StateQ...
static <RequestT, ResponseT> Call<RequestT, ResponseT> of( Caller<RequestT, ResponseT> caller, Coder<ResponseT> responseTCoder) { caller = SerializableUtils.ensureSerializable(caller); return new Call<>( Configuration.<RequestT, ResponseT>builder() .setCaller(caller) .setRe...
@Test public void givenCallerThrowsUserCodeExecutionException_emitsIntoFailurePCollection() { Result<Response> result = pipeline .apply(Create.of(new Request("a"))) .apply( Call.of( new CallerThrowsUserCodeExecutionException(), ...
@Override protected void activate() { move(0, 0, -20); playSound("GROUNDDIVE_SOUND", 5); spawnParticles("GROUNDDIVE_PARTICLE", 20); }
@Test void testActivate() throws Exception { var groundDive = new GroundDive(); var logs = tapSystemOutNormalized(groundDive::activate) .split("\n"); final var expectedSize = 3; final var log1 = logs[0].split("--")[1].trim(); final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )"; fina...
@Override public V remove(K key) { return map.remove(key); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveWithOldValue() { adapter.remove(23, "oldValue"); }
@Override @Transactional(rollbackFor = Exception.class) public void updateJobStatus(Long id, Integer status) throws SchedulerException { // 校验 status if (!containsAny(status, JobStatusEnum.NORMAL.getStatus(), JobStatusEnum.STOP.getStatus())) { throw exception(JOB_CHANGE_STATUS_INVALI...
@Test public void testUpdateJobStatus_changeStatusEquals() { // mock 数据 JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus())); jobMapper.insert(job); // 调用,并断言异常 assertServiceException(() -> jobService.updateJobStatus(job.getId(), job.getSta...
public EtlStatus getEtlJobStatus(SparkLoadAppHandle handle, String appId, long loadJobId, String etlOutputPath, SparkResource resource, BrokerDesc brokerDesc) throws UserException { EtlStatus status = new EtlStatus(); Preconditions.checkState(appId != null && !appId...
@Test public void testGetEtlJobStatus(@Mocked BrokerUtil brokerUtil, @Mocked Util util, @Mocked CommandResult commandResult, @Mocked SparkYarnConfigFiles sparkYarnConfigFiles, @Mocked SparkLoadAppHandle handl...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testTheatreOfBlood() { when(client.getVarbitValue(Varbits.THEATRE_OF_BLOOD_ORB1)).thenReturn(1); when(client.getVarbitValue(Varbits.THEATRE_OF_BLOOD_ORB2)).thenReturn(15); ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Wave 'The Final Challenge' (Normal Mode) complete!<b...
@SuppressWarnings("DataFlowIssue") public static CommandExecutor newInstance(final MySQLCommandPacketType commandPacketType, final CommandPacket commandPacket, final ConnectionSession connectionSession) throws SQLException { if (commandPacket instanceof SQLReceivedPacket) { log.debug("Execute pa...
@Test void assertNewInstanceWithComPing() throws SQLException { assertThat(MySQLCommandExecutorFactory.newInstance(MySQLCommandPacketType.COM_PING, mock(CommandPacket.class), connectionSession), instanceOf(MySQLComPingExecutor.class)); }
public FEELFnResult<String> invoke(@ParameterName("from") Object val) { if ( val == null ) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) ); } }
@Test void invokeDurationHours() { FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofHours(9)), "PT9H"); FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofHours(200)), "P8DT8H"); FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofHours(-200)), "-P8DT8H")...
protected Packet recognizeAndReturnXmppPacket(Element root) throws UnsupportedStanzaTypeException, IllegalArgumentException { checkNotNull(root); Packet packet = null; if (root.getName().equals(XmppConstants.IQ_QNAME)) { packet = new IQ(root); } else if (root.get...
@Test public void testRecognizePacket() throws Exception { Packet iqPacket = xmppDecoder.recognizeAndReturnXmppPacket(iqElement); assertThat(iqPacket, is(instanceOf(IQ.class))); Packet messagePacket = xmppDecoder.recognizeAndReturnXmppPacket(messageElement); assertThat(messagePacket,...
public PDDocument createPDFFromText( Reader text ) throws IOException { PDDocument doc = new PDDocument(); createPDFFromText(doc, text); return doc; }
@Test void testLeadingTrailingSpaces() throws IOException { TextToPDF pdfCreator = new TextToPDF(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String text = "Lorem ipsum dolor sit amet,\n" + " consectetur adipiscing \n" + "\n" ...
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } try { TemporalAccessor parsed = FEEL_TIME.parse(val); i...
@Test void invokeTimeUnitsParamsWithOffset() { FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, 15, Duration.ofHours(1)), OffsetTime.of(10, 43, 15, 0, ...
@Override public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context) throws KeySourceException { var jwksUrl = discoverJwksUrl(); try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) { return jwkSetSource.getJWKSet(null...
@Test void getJWKSet_badCode(WireMockRuntimeInfo wm) { var discoveryUrl = URI.create(wm.getHttpBaseUrl()).resolve(DISCOVERY_PATH); var jwksUrl = URI.create(wm.getHttpBaseUrl()).resolve(JWKS_PATH); stubFor(get(DISCOVERY_PATH).willReturn(okJson("{\"jwks_uri\": \"%s\"}".formatted(jwksUrl)))); stubFor...
public static AppsInfo mergeAppsInfo(ArrayList<AppInfo> appsInfo, boolean returnPartialResult) { AppsInfo allApps = new AppsInfo(); Map<String, AppInfo> federationAM = new HashMap<>(); Map<String, AppInfo> federationUAMSum = new HashMap<>(); for (AppInfo a : appsInfo) { // Check if this App...
@Test public void testMergeAppsFinished() { AppsInfo apps = new AppsInfo(); String amHost = "http://i_am_the_AM1:1234"; AppInfo am = new AppInfo(); am.setAppId(APPID1.toString()); am.setAMHostHttpAddress(amHost); am.setState(YarnApplicationState.FINISHED); int value = 1000; setAppIn...
@Override public TenantPackageDO validTenantPackage(Long id) { TenantPackageDO tenantPackage = tenantPackageMapper.selectById(id); if (tenantPackage == null) { throw exception(TENANT_PACKAGE_NOT_EXISTS); } if (tenantPackage.getStatus().equals(CommonStatusEnum.DISABLE.getS...
@Test public void testValidTenantPackage_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> tenantPackageService.validTenantPackage(id), TENANT_PACKAGE_NOT_EXISTS); }
public static boolean inSagaBranch() { return BranchType.SAGA == getBranchType(); }
@Test public void testInSagaBranch() { RootContext.bind(DEFAULT_XID); assertThat(RootContext.inSagaBranch()).isFalse(); RootContext.bindBranchType(BranchType.SAGA); assertThat(RootContext.inSagaBranch()).isTrue(); RootContext.unbindBranchType(); assertThat(RootContext...
@Operation(summary = "get wid documents for rda", tags = { SwaggerConfig.ACTIVATE_RDA , SwaggerConfig.UPGRADE_LOGIN_LEVEL, SwaggerConfig.WIDCHECKER_RAISE_TO_SUB, SwaggerConfig.REQUEST_ACCOUNT_AND_APP}, operationId = "digidRdaDocuments", parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Paramet...
@Test void validateIfCorrectProcessesAreCalledGetWidDocuments() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException { AppSessionRequest request = new AppSessionRequest(); activationController.getWidDocuments(request); ...
public static <T> Read<T> read(Class<T> classType) { return new AutoValue_CosmosIO_Read.Builder<T>().setClassType(classType).build(); }
@Test public void testRead() { PCollection<Family> output = pipeline.apply( CosmosIO.read(Family.class) .withContainer(CONTAINER) .withDatabase(DATABASE) .withCoder(SerializableCoder.of(Family.class))); PAssert.thatSingleton(output.apply("Co...
@Override public void deleteFile(Long id) throws Exception { // 校验存在 FileDO file = validateFileExists(id); // 从文件存储器中删除 FileClient client = fileConfigService.getFileClient(file.getConfigId()); Assert.notNull(client, "客户端({}) 不能为空", file.getConfigId()); client.delete(...
@Test public void testDeleteFile_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> fileService.deleteFile(id), FILE_NOT_EXISTS); }
@Override public void write(int b) throws IOException { dataOut.write(b); }
@Test public void testWriteForBOffLen() throws Exception { byte[] someInput = new byte[1]; dataOutputStream.write(someInput, 0, someInput.length); verify(mockOutputStream).write(someInput, 0, someInput.length); }
static SourceOperationResponse performSplitWithApiLimit( SourceSplitRequest request, PipelineOptions options, int numBundlesLimit, long apiByteLimit) throws Exception { // Compute the desired bundle size given by the service, or default if none was provided. long desiredBundleSizeBytes = DEFAULT_DES...
@Test public void testSplittingProducedResponseUnderLimit() throws Exception { SourceProducingSubSourcesInSplit source = new SourceProducingSubSourcesInSplit(200, 10_000); com.google.api.services.dataflow.model.Source cloudSource = translateIOToCloudSource(source, options); SourceSplitRequest spli...
@Override public void processWatermarkStatus(WatermarkStatus watermarkStatus) throws Exception {}
@Test void inputStatusesAreNotForwarded() throws Exception { OneInputStreamOperatorTestHarness<Long, Long> testHarness = createTestHarness( WatermarkStrategy.forGenerator((ctx) -> new PeriodicWatermarkGenerator()) .withTimestampAssigner...
public void setErrorAndRollback(final long ntail, final Status st) { Requires.requireTrue(ntail > 0, "Invalid ntail=" + ntail); if (this.currEntry == null || this.currEntry.getType() != EnumOutter.EntryType.ENTRY_TYPE_DATA) { this.currentIndex -= ntail; } else { this.curr...
@Test(expected = IllegalArgumentException.class) public void testSetErrorAndRollbackInvalid() { this.iter.setErrorAndRollback(-1, null); }
@Override public String getDataSource() { return DataSourceConstant.DERBY; }
@Test void testGetDataSource() { String dataSource = configInfoTagMapperByDerby.getDataSource(); assertEquals(DataSourceConstant.DERBY, dataSource); }
public static void addBackgroundErrorsMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics,...
@Test public void shouldAddBackgroundErrorsMetric() { final String name = "background-errors"; final String description = "Total number of background errors"; runAndVerifyMutableMetric( name, description, () -> RocksDBMetrics.addBackgroundErrorsMetric(stre...
Optional<Checkpoint> checkpoint(String group, TopicPartition topicPartition, OffsetAndMetadata offsetAndMetadata) { if (offsetAndMetadata != null) { long upstreamOffset = offsetAndMetadata.offset(); OptionalLong downstreamOffset = offse...
@Test public void testCheckpoint() { long t1UpstreamOffset = 3L; long t1DownstreamOffset = 4L; long t2UpstreamOffset = 7L; long t2DownstreamOffset = 8L; OffsetSyncStoreTest.FakeOffsetSyncStore offsetSyncStore = new OffsetSyncStoreTest.FakeOffsetSyncStore(); offsetSync...
@Override public void onEvent(MembersChangeEvent event) { try { List<Member> members = serverMemberManager.allMembersWithoutSelf(); refresh(members); } catch (NacosException e) { Loggers.CLUSTER.warn("[serverlist] fail to refresh cluster rpc client, event:{}, msg:...
@Test void testOnEvent() { try { clusterRpcClientProxy.onEvent(MembersChangeEvent.builder().build()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Override public void transform(Message message, DataType fromType, DataType toType) { if (message.getHeaders().containsKey(Ddb2Constants.ITEM) || message.getHeaders().containsKey(Ddb2Constants.KEY)) { return; } JsonNode jsonBody = getBodyAsJsonNode(message); ...
@Test void shouldFailForWrongBodyType() throws Exception { Exchange exchange = new DefaultExchange(camelContext); exchange.getMessage().setBody("Hello"); Assertions.assertThrows(CamelExecutionException.class, () -> transformer.transform(exchange.getMessage(), DataType.ANY, ...
@Override public Tcp clone() throws CloneNotSupportedException { return new Tcp(); }
@Test void testClone() throws CloneNotSupportedException { Tcp original = new Tcp(); Tcp cloned = original.clone(); assertEquals(original.hashCode(), cloned.hashCode()); assertEquals(original, cloned); }
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void sessionWindowNamedMaterializedCountShouldPreserveTopologyStructure() { final StreamsBuilder builder = new StreamsBuilder(); builder.stream("input-topic") .groupByKey() .windowedBy(SessionWindows.with(ofMillis(1))) .count(Materialized.<Object, Lon...