focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == GET_UNKNOWN_SUB_COMMAND_NAME) { returnCommand = getUnknownMember(reader); }...
@Test public void testUnknown() { String inputCommand1 = ReflectionCommand.GET_UNKNOWN_SUB_COMMAND_NAME + "\n" + "java" + "\nrj\ne\n"; String inputCommand2 = ReflectionCommand.GET_UNKNOWN_SUB_COMMAND_NAME + "\n" + "java.lang" + "\nrj\ne\n"; String inputCommand3 = ReflectionCommand.GET_UNKNOWN_SUB_COMMAND_NAME + ...
static List<IdentifierTree> getVariableUses(ExpressionTree tree) { List<IdentifierTree> freeVars = new ArrayList<>(); new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void v) { if (((JCIdent) node).sym instanceof VarSymbol) { freeVars.add(...
@Test public void getVariableUses() { writeFile("A.java", "public class A {", " public String b;", " void foo() {}", "}"); writeFile( "B.java", "public class B {", " A my;", " B bar() { return null; }", " void foo(String x, A a) {", " x.trim().intern();"...
@Override public void start() { try { forceMkdir(fs.getUninstalledPluginsDir()); } catch (IOException e) { throw new IllegalStateException("Fail to create the directory: " + fs.getUninstalledPluginsDir(), e); } }
@Test public void create_uninstall_dir() { File dir = new File(testFolder.getRoot(), "dir"); when(fs.getUninstalledPluginsDir()).thenReturn(dir); assertThat(dir).doesNotExist(); underTest.start(); assertThat(dir).isDirectory(); }
@Override public void store(Measure newMeasure) { saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure); }
@Test public void should_not_skip_file_measures_on_pull_request_when_file_status_is_SAME() { DefaultInputFile file = new TestInputFileBuilder("foo", "src/Foo.php").setStatus(InputFile.Status.SAME).build(); when(branchConfiguration.isPullRequest()).thenReturn(true); underTest.store(new DefaultMeasure() ...
@Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final Header header = (Header) o; if(!Objects.equals(name, header.name)) { return false; ...
@Test public void testEquals() { assertEquals(new Header("k", "v"), new Header("k", "v")); assertNotEquals(new Header("k", "v"), new Header("k", "f")); assertNotEquals(new Header("k", "v"), new Header("m", "v")); }
@Override public KeyVersion createKey(final String name, final byte[] material, final Options options) throws IOException { return doOp(new ProviderCallable<KeyVersion>() { @Override public KeyVersion call(KMSClientProvider provider) throws IOException { return provider.createKey(name, m...
@Test public void testClientRetriesSucceedsSecondTime() throws Exception { Configuration conf = new Configuration(); conf.setInt( CommonConfigurationKeysPublic.KMS_CLIENT_FAILOVER_MAX_RETRIES_KEY, 3); KMSClientProvider p1 = mock(KMSClientProvider.class); when(p1.createKey(Mockito.anyString(), ...
@Override public CreatePartitionsResult createPartitions(final Map<String, NewPartitions> newPartitions, final CreatePartitionsOptions options) { final Map<String, KafkaFutureImpl<Void>> futures = new HashMap<>(newPartitions.size()); final CreatePar...
@Test public void testCreatePartitionsDontRetryThrottlingExceptionWhenDisabled() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse( expectCreatePar...
@Override public Processor<K, Change<V>, K, Change<VOut>> get() { return new KTableTransformValuesProcessor(transformerSupplier.get()); }
@Test public void shouldThrowOnGetIfSupplierReturnsNull() { final KTableTransformValues<String, String, String> transformer = new KTableTransformValues<>(parent, new NullSupplier(), QUERYABLE_NAME); try { transformer.get(); fail("NPE expected"); } catch (...
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates) { List<String> perColumnExpressions = new ArrayList<>(); int expressionLength = 0; for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) { String columnName = partition...
@Test public void testBuildGlueExpressionTupleDomainEqualsAndInClause() { Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR) .addStringValues("col1", "2020-01-01") .addStringValues("col2", "2020-02-20", "2020-02-28") .build()...
public Formula(Term response, Term... predictors) { if (response instanceof Dot || response instanceof FactorCrossing) { throw new IllegalArgumentException("The response variable cannot be '.' or FactorCrossing."); } this.response = response; this.predictors = predictors; ...
@Test public void testFormula() { System.out.println("formula"); Formula formula = Formula.of("salary", $("age")); assertEquals("salary ~ age", formula.toString()); DataFrame output = formula.frame(df); System.out.println(output); assertEquals(df.size(), output.size(...
private static void handleSetTabletBinlogConfig(long backendId, Map<Long, TTablet> backendTablets) { List<Pair<Long, BinlogConfig>> tabletToBinlogConfig = Lists.newArrayList(); TabletInvertedIndex invertedIndex = GlobalStateMgr.getCurrentState().getTabletInvertedIndex(); for (TTablet backendTab...
@Test public void testHandleSetTabletBinlogConfig() { Database db = GlobalStateMgr.getCurrentState().getDb("test"); long dbId = db.getId(); OlapTable olapTable = (OlapTable) db.getTable("binlog_report_handler_test"); long backendId = 10001L; List<Long> tabletIds = GlobalState...
public IntersectAllOperator(OpChainExecutionContext opChainExecutionContext, List<MultiStageOperator> inputOperators, DataSchema dataSchema) { super(opChainExecutionContext, inputOperators, dataSchema); }
@Test public void testIntersectAllOperator() { DataSchema schema = new DataSchema(new String[]{"int_col"}, new DataSchema.ColumnDataType[]{DataSchema.ColumnDataType.INT}); Mockito.when(_leftOperator.nextBlock()) .thenReturn(OperatorTestUtil.block(schema, new Object[]{1}, new Object[]{2}, new ...
@Override public boolean apply(InputFile inputFile) { return extension.equals(getExtension(inputFile)); }
@Test public void should_not_match_incorrect_extension() throws IOException { FileExtensionPredicate predicate = new FileExtensionPredicate("bat"); assertThat(predicate.apply(mockWithName("prog.batt"))).isFalse(); assertThat(predicate.apply(mockWithName("prog.abat"))).isFalse(); assertThat(predicate.a...
public static String convertToBitcoinURI(Address address, Coin amount, String label, String message) { return convertToBitcoinURI(address.network(), address.toString(), amount, label, message); }
@Test public void testConvertToBitcoinURI_segwit() { Address segwitAddress = AddressParser.getDefault(MAINNET).parseAddress(MAINNET_GOOD_SEGWIT_ADDRESS); assertEquals("bitcoin:" + MAINNET_GOOD_SEGWIT_ADDRESS + "?message=segwit%20rules", BitcoinURI.convertToBitcoinURI( segwitAddress, ...
public String getName() { return name; }
@Test public void hasAName() throws Exception { assertThat(handler.getName()) .isEqualTo("handler"); }
public void start(XmppDeviceFactory deviceFactory) { log.info("XMPP Server has started."); this.run(deviceFactory); }
@Test public void testStart() { XmppDeviceFactory mockXmppDeviceFactory = EasyMock.createMock(XmppDeviceFactory.class); server.start(mockXmppDeviceFactory); assertNotNull(server.channel); assertNotNull(server.channelClass); assertNotNull(server.eventLoopGroup); }
@Override protected void handlePut(final String listenTo, final ClusterProperties discoveryProperties) { if (discoveryProperties != null) { ActivePropertiesResult pickedPropertiesResult = pickActiveProperties(discoveryProperties); ClusterInfoItem newClusterInfoItem = new ClusterInfoItem( ...
@Test(dataProvider = "getConfigsAndDistributions") public void testWithCanaryConfigs(ClusterProperties stableConfigs, ClusterProperties canaryConfigs, CanaryDistributionStrategy distributionStrategy, CanaryDistributionProvider.Distribution distribution, FailoutProperties failoutProperties) { ClusterLoadBa...
@Override public void write(T record) { recordConsumer.startMessage(); try { messageWriter.writeTopLevelMessage(record); } catch (RuntimeException e) { Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record; LOG.error("Cannot write message...
@Test public void testProto3MapIntMessageEmpty() throws Exception { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); ProtoWriteSupport<TestProto3.MapIntMessage> instance = createReadConsumerInstance(TestProto3.MapIntMessage.class, readConsumerMock); TestProto3.MapIntMessage.B...
public Properties build() { checkNotNull(logDir, config); checkState(jsonOutput || (logPattern != null), "log pattern must be specified if not using json output"); configureGlobalFileLog(); if (allLogsToConsole) { configureGlobalStdoutLog(); } ofNullable(logLevelConfig).ifPresent(this::ap...
@Test public void buildLogPattern_does_not_put_threadIdFieldPattern_from_RootLoggerConfig_is_null() { String pattern = newLog4JPropertiesBuilder().buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.COMPUTE_ENGINE) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.d...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetchOnCompletedFetchesForAllPausedPartitions() { buildFetcher(); assignFromUser(mkSet(tp0, tp1)); // seek to tp0 and tp1 in two polls to generate 2 complete requests and responses // #1 seek, request, poll, response subscriptions.seekUnvalidated(tp0,...
@Override public double score(int[] truth, int[] cluster) { return of(truth, cluster); }
@Test public void test() { System.out.println("adjusted rand index"); int[] clusters = {2, 3, 3, 1, 1, 3, 3, 1, 3, 1, 1, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1, 1, 1, 1, 1, 4, 1, 3, 3, 3, 3, 3, 1, 4, 4, 4, 3, 1, 1, 3, 1, 4, 3, 3, 3, 3, 1, 1, 3, 1, 1, 3, 3, 3, 3, 4, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, 3, 3, 2, 3, 3,...
@Override public QueryStats execute(Statement statement) { return execute(statement, Optional.empty()).getQueryStats(); }
@Test public void testQuerySucceededWithConverter() { QueryResult<Integer> result = prestoAction.execute( SQL_PARSER.createStatement("SELECT x FROM (VALUES (1), (2), (3)) t(x)", PARSING_OPTIONS), resultSet -> resultSet.getInt("x") * resultSet.getInt("x")); assertE...
public static boolean isValidOrigin(String sourceHost, ZeppelinConfiguration zConf) throws UnknownHostException, URISyntaxException { String sourceUriHost = ""; if (sourceHost != null && !sourceHost.isEmpty()) { sourceUriHost = new URI(sourceHost).getHost(); sourceUriHost = (sourceUriHost ==...
@Test void emptyOrigin() throws URISyntaxException, UnknownHostException { assertFalse(CorsUtils.isValidOrigin("", ZeppelinConfiguration.load("zeppelin-site.xml"))); }
@Override public Enumeration<URL> getResources(String name) throws IOException { List<URL> resources = new ArrayList<>(); ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resources '{}'", name); for (ClassLoadingStrategy.Source...
@Test void parentLastGetResourcesExistsOnlyInDependency() throws IOException, URISyntaxException { Enumeration<URL> resources = parentLastPluginClassLoader.getResources("META-INF/dependency-file"); assertNumberOfResourcesAndFirstLineOfFirstElement(1, "dependency", resources); }
public MapStoreConfig setFactoryImplementation(@Nonnull Object factoryImplementation) { this.factoryImplementation = checkNotNull(factoryImplementation, "Map store factory cannot be null!"); this.factoryClassName = null; return this; }
@Test public void setFactoryImplementation() { Object mapStoreFactoryImpl = new Object(); MapStoreConfig cfg = new MapStoreConfig().setFactoryImplementation(mapStoreFactoryImpl); assertEquals(mapStoreFactoryImpl, cfg.getFactoryImplementation()); assertEquals(new MapStoreConfig().setF...
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) { SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt() .orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo())); SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt() ...
@Test public void testAllowNullCorrectPolymorphism() { Bar bar = new Bar(); bar.setField1(true); DerivedFoo derivedFoo = new DerivedFoo(); derivedFoo.setField1("foo1"); derivedFoo.setField2("bar2"); derivedFoo.setField3(4); derivedFoo.setField4(bar); ...
@Override public String toString() { return "SmppConfiguration[usingSSL=" + usingSSL + ", enquireLinkTimer=" + enquireLinkTimer + ", host=" + host + ", password=" + password + ", port=" + port + ", systemId=" + systemId ...
@Test public void toStringShouldListAllInstanceVariables() { String expected = "SmppConfiguration[" + "usingSSL=false, " + "enquireLinkTimer=60000, " + "host=localhost, " + "password=null, " ...
static String generateRustLiteral(final PrimitiveType type, final String value) { Verify.notNull(type, "type"); Verify.notNull(value, "value"); final String typeName = rustTypeName(type); if (typeName == null) { throw new IllegalArgumentException("Unknown Rust typ...
@Test void generateRustLiteralNullValueParam() { assertThrows(NullPointerException.class, () -> generateRustLiteral(INT8, null)); }
@Override public List<BufferedRequestState<RequestEntryT>> snapshotState(long checkpointId) { return Collections.singletonList(new BufferedRequestState<>((bufferedRequestEntries))); }
@Test public void testRestoreFromMultipleStates() throws IOException { List<BufferedRequestState<Integer>> states = Arrays.asList( new BufferedRequestState<>( Arrays.asList( new RequestEntryWrappe...
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"}) void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas, MigrationDecisionCallback callback) { assert oldReplicas.length == newReplicas.leng...
@Test public void test_MOVE() throws UnknownHostException { final PartitionReplica[] oldReplicas = { new PartitionReplica(new Address("localhost", 5701), uuids[0]), new PartitionReplica(new Address("localhost", 5702), uuids[1]), new PartitionReplica(new Addres...
public String toString() { return "RecordingLog{" + "entries=" + entriesCache + ", cacheIndex=" + cacheIndexByLeadershipTermIdMap + '}'; }
@Test void entryToString() { final RecordingLog.Entry entry = new RecordingLog.Entry( 42, 5, 1024, 701, 1_000_000_000_000L, 16, ENTRY_TYPE_SNAPSHOT, null, true, 2); assertEquals( "Entry{recordingId=42, leadershipTermId=5, termBaseLogPosition=1024, logPosition=701, " + ...
public Object resolve(final Expression expression) { return new Visitor().process(expression, null); }
@Test public void shouldParseTimestamp() { // Given: final SqlType type = SqlTypes.TIMESTAMP; final Expression exp = new StringLiteral("2021-01-09T04:40:02"); // When: Object o = new GenericExpressionResolver(type, FIELD_NAME, registry, config, "insert value", false).resolve(exp); //...
protected ConfiguredCloseableHttpClient createClient( final org.apache.hc.client5.http.impl.classic.HttpClientBuilder builder, final InstrumentedHttpClientConnectionManager manager, final String name) { final String cookiePolicy = configuration.isCookiesEnabled() ? StandardCo...
@Test void exposedConfigIsTheSameAsInternalToTheWrappedHttpClient() { ConfiguredCloseableHttpClient client = builder.createClient(apacheBuilder, connectionManager, "test"); assertThat(client).isNotNull(); assertThat(client.getClient()).extracting("defaultConfig").isEqualTo(client.getDefault...
public Plan validateReservationUpdateRequest( ReservationSystem reservationSystem, ReservationUpdateRequest request) throws YarnException { ReservationId reservationId = request.getReservationId(); Plan plan = validateReservation(reservationSystem, reservationId, AuditConstants.UPDATE_RESERV...
@Test public void testUpdateReservationInvalidRR() { ReservationUpdateRequest request = createSimpleReservationUpdateRequest(0, 0, 1, 5, 3); Plan plan = null; try { plan = rrValidator.validateReservationUpdateRequest(rSystem, request); Assert.fail(); } catch (YarnException e) { ...
public static void checkNotNullAndNotEmpty(String arg, String argName) { checkNotNull(arg, argName); checkArgument( !arg.isEmpty(), "'%s' must not be empty.", argName); }
@Test public void testCheckNotNullAndNotEmpty() throws Exception { // Should not throw. Validate.checkNotNullAndNotEmpty(NON_EMPTY_ARRAY, "array"); Validate.checkNotNullAndNotEmpty(NON_EMPTY_BYTE_ARRAY, "array"); Validate.checkNotNullAndNotEmpty(NON_EMPTY_SHORT_ARRAY, "array"); Validate.checkNotNu...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldInsertValuesIntoHeaderSchemaValueColumns() { // Given: givenSourceStreamWithSchema(SCHEMA_WITH_HEADERS, SerdeFeatures.of(), SerdeFeatures.of()); final ConfiguredStatement<InsertValues> statement = givenInsertValues( ImmutableList.of(K0, COL0, COL1), ImmutableList.of...
@Override public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { List<Class<?>> groups = new ArrayList<>(); Class<?> methodClass = methodClass(methodName); if (methodClass != null) { groups.add(methodClass); } Me...
@Test void testItWithNestedParameterValidationWithNullParam() { Assertions.assertThrows(ValidationException.class, () -> { URL url = URL.valueOf( "test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = n...
@Override public boolean supportsConvert() { return false; }
@Test void assertSupportsConvertWithParameter() { assertFalse(metaData.supportsConvert(0, 0)); }
@Override public String getDescription() { return "Write metadata"; }
@Test public void getDescription_is_defined() { assertThat(underTest.getDescription()).isNotEmpty(); }
@Override public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) { Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems); Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems); //remove comment and blank item map. ...
@Test public void testAddCommentAndBlankItem() { ItemChangeSets changeSets = resolver.resolve(1, "#ddd\na=b\n\nb=c\nc=d", mockBaseItemHas3Key()); Assert.assertEquals(2, changeSets.getCreateItems().size()); Assert.assertEquals(3, changeSets.getUpdateItems().size()); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { if(implementations.containsKey(Command.mlsd)) { // Note that there is no distinct FEAT output for MLSD. The presence of the MLST feature ...
@Test(expected = NotfoundException.class) public void testListNotfound() throws Exception { final Path f = new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); final FTPListService service = new FTPListService(session, null, TimeZone.getDefault()); service.list(f, new Dis...
@Override public void blame(BlameInput input, BlameOutput result) { for (InputFile inputFile : input.filesToBlame()) { processFile(inputFile, result); } }
@Test public void testBlameWithRelativeDate() throws IOException { File source = new File(baseDir, "src/foo.xoo"); FileUtils.write(source, "sample content"); File scm = new File(baseDir, "src/foo.xoo.scm"); FileUtils.write(scm, "123,julien,-10\n234,julien,-10"); DefaultInputFile inputFile = new Te...
public static NativeReader<WindowedValue<?>> create( final CloudObject spec, final PipelineOptions options, DataflowExecutionContext executionContext) throws Exception { @SuppressWarnings("unchecked") final Source<Object> source = (Source<Object>) deserializeFromCloudSource(spec); ...
@Test public void testReadUnboundedReader() throws Exception { CounterSet counterSet = new CounterSet(); StreamingModeExecutionStateRegistry executionStateRegistry = new StreamingModeExecutionStateRegistry(); ReaderCache readerCache = new ReaderCache(Duration.standardMinutes(1), Runnable::run); ...
@Override public Row poll() { return poll(Duration.ZERO); }
@Test public void shouldDeliverBufferedRowsIfComplete() throws Exception { // Given givenPublisherAcceptsOneRow(); completeQueryResult(); // When final Row receivedRow = queryResult.poll(); // Then assertThat(receivedRow, is(row)); }
public static boolean isDirectory(URL resourceURL) throws URISyntaxException { final String protocol = resourceURL.getProtocol(); switch (protocol) { case "jar": try { final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection(); ...
@Test void isDirectoryReturnsTrueForURLEncodedDirectoriesInJars() throws Exception { final URL url = new URL("jar:" + resourceJar.toExternalForm() + "!/dir%20with%20space/"); assertThat(url.getProtocol()).isEqualTo("jar"); assertThat(ResourceURL.isDirectory(url)).isTrue(); }
@PostConstruct public void init() { rejectTips = RateLimitUtils.getRejectTips(polarisRateLimitProperties); }
@Test public void testInit() { quotaCheckReactiveFilter.init(); try { Field rejectTips = QuotaCheckReactiveFilter.class.getDeclaredField("rejectTips"); rejectTips.setAccessible(true); assertThat(rejectTips.get(quotaCheckReactiveFilter)).isEqualTo("RejectRequestTips提示消息"); } catch (NoSuchFieldException...
@Override public ObjectNode encode(Instruction instruction, CodecContext context) { checkNotNull(instruction, "Instruction cannot be null"); return new EncodeInstructionCodecHelper(instruction, context).encode(); }
@Test public void outputInstructionTest() { final Instructions.OutputInstruction instruction = Instructions.createOutput(PortNumber.portNumber(22)); final ObjectNode instructionJson = instructionCodec.encode(instruction, context); assertThat(instructionJson, m...
@Override public InputStream getInputStream() { return new RedissonInputStream(); }
@Test public void testRead() throws IOException { RBinaryStream stream = redisson.getBinaryStream("test"); byte[] value = {1, 2, 3, 4, 5, (byte)0xFF}; stream.set(value); InputStream s = stream.getInputStream(); int b = 0; byte[] readValue = new byte[6]; ...
@VisibleForTesting static Optional<Dependency> parseDependency(String line) { Matcher dependencyMatcher = SHADE_INCLUDE_MODULE_PATTERN.matcher(line); if (!dependencyMatcher.find()) { return Optional.empty(); } return Optional.of( Dependency.create( ...
@Test void testLineParsingGroupId() { assertThat( ShadeParser.parseDependency( "Including external:dependency1:jar:1.0 in the shaded jar.")) .hasValueSatisfying( dependency -> assertThat(dependency.getGroupId())....
public static void disablePullConsumption(DefaultLitePullConsumerWrapper wrapper, Set<String> topics) { Set<String> subscribedTopic = wrapper.getSubscribedTopics(); if (subscribedTopic.stream().anyMatch(topics::contains)) { suspendPullConsumer(wrapper); return; } ...
@Test public void testDisablePullConsumptionWithAssignSubTractTopics() { subscribedTopics = new HashSet<>(); subscribedTopics.add("test-topic-1"); subscribedTopics.add("test-topic-2"); pullConsumerWrapper.setSubscribedTopics(subscribedTopics); pullConsumerWrapper.setSubscript...
@GetMapping("list") public String getProductsList(Model model, @RequestParam(name = "filter", required = false) String filter) { model.addAttribute("products", this.productsRestClient.findAllProducts(filter)); model.addAttribute("filter", filter); return "catalogue/products/list"; }
@Test void getProductsList_ReturnsProductsListPage() { // given var model = new ConcurrentModel(); var filter = "товар"; var products = IntStream.range(1, 4) .mapToObj(i -> new Product(i, "Товар №%d".formatted(i), "Описание товара №%d".formatt...
public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize); check("size()").that(checkNotNull(actual).size()).isEqualTo(expectedSize); }
@Test public void hasSize() { assertThat(ImmutableMultimap.of(1, 2, 3, 4)).hasSize(2); }
public PlanNode plan(Analysis analysis) { return planStatement(analysis, analysis.getStatement()); }
@Test public void testRedundantLimitNodeRemoval() { String query = "SELECT count(*) FROM orders LIMIT 10"; assertFalse( searchFrom(plan(query, OPTIMIZED).getRoot()) .where(LimitNode.class::isInstance) .matches(), for...
public static ClusterAllocationDiskSettings create(boolean enabled, String low, String high, String floodStage) { if (!enabled) { return ClusterAllocationDiskSettings.create(enabled, null); } return ClusterAllocationDiskSettings.create(enabled, createWatermarkSettings(low, high, floo...
@Test public void createAbsoluteValueWatermarkSettings() throws Exception { ClusterAllocationDiskSettings clusterAllocationDiskSettings = ClusterAllocationDiskSettingsFactory.create(true, "20Gb", "10Gb", "5Gb"); assertThat(clusterAllocationDiskSettings).isInstanceOf(ClusterAllocationDiskSettings.cl...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testShhVersion() throws Exception { web3j.shhVersion().send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"shh_version\"," + "\"params\":[],\"id\":1}"); }
public static Ethernet buildNdpAdv(Ip6Address srcIp, MacAddress srcMac, Ethernet request) { checkNotNull(srcIp, "IP address cannot be null"); checkNotNull(srcMac, "MAC address cannot be null"); checkNotNull(request, "...
@Test public void testBuildNdpAdv() { Ethernet eth = new Ethernet(); eth.setSourceMACAddress(MAC_ADDRESS); eth.setDestinationMACAddress(MAC_ADDRESS2); IPv6 ipv6 = new IPv6(); ipv6.setSourceAddress(IPV6_SOURCE_ADDRESS); ipv6.setDestinationAddress(IPV6_DESTINATION_ADDR...
public static ContentClusterStats generate(Distributor distributor) { Map<Integer, ContentNodeStats> mapToNodeStats = new HashMap<>(); for (StorageNode storageNode : distributor.getStorageNodes()) { mapToNodeStats.put(storageNode.getIndex(), new ContentNodeStats(storageNode)); } ...
@Test void testContentNodeStats() throws IOException { String data = getJsonString(); HostInfo hostInfo = HostInfo.createHostInfo(data); ContentClusterStats clusterStats = StorageNodeStatsBridge.generate(hostInfo.getDistributor()); Iterator<ContentNodeStats> itr = clusterStats.itera...
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { try { if (statement.getStatement() instanceof CreateAsSelect) { registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement); ...
@Test public void shouldNotRegisterSchemaForSchemaRegistryDisabledFormatCreateSource() { // Given: givenStatement("CREATE STREAM sink (f1 VARCHAR) WITH(kafka_topic='expectedName', key_format='KAFKA', value_format='DELIMITED', partitions=1);"); // When: injector.inject(statement); // Then: ve...
static void setEntryValue( StepInjectionMetaEntry entry, RowMetaAndData row, SourceStepField source ) throws KettleValueException { // A standard attribute, a single row of data... // Object value = null; switch ( entry.getValueType() ) { case ValueMetaInterface.TYPE_STRING: value = ro...
@Test public void setEntryValue_date() throws KettleValueException { StepInjectionMetaEntry entry = mock( StepInjectionMetaEntry.class ); doReturn( ValueMetaInterface.TYPE_DATE ).when( entry ).getValueType(); RowMetaAndData row = createRowMetaAndData( new ValueMetaDate( TEST_FIELD ), null ); SourceSte...
@Restricted(NoExternalUse.class) public static String[] printLogRecordHtml(LogRecord r, LogRecord prior) { String[] oldParts = prior == null ? new String[4] : logRecordPreformat(prior); String[] newParts = logRecordPreformat(r); for (int i = 0; i < /* not 4 */3; i++) { newParts[i...
@Test public void printLogRecordHtmlNoLogger() { LogRecord lr = new LogRecord(Level.INFO, "<discarded/>"); assertEquals("&lt;discarded/&gt;\n", Functions.printLogRecordHtml(lr, null)[3]); }
@Override public Comparable convert(Comparable value) { if (!(value instanceof CompositeValue)) { throw new IllegalArgumentException("Cannot convert [" + value + "] to composite"); } CompositeValue compositeValue = (CompositeValue) value; Comparable[] components = compos...
@Test(expected = IllegalArgumentException.class) public void testConversionAcceptsOnlyCompositeValues() { converter(STRING_CONVERTER).convert("value"); }
public Set<Analysis.AliasedDataSource> extractDataSources(final AstNode node) { new Visitor().process(node, null); return getAllSources(); }
@Test public void shouldThrowIfInnerJoinSourceDoesNotExist() { // Given: final AstNode stmt = givenQuery("SELECT * FROM TEST1 JOIN UNKNOWN" + " ON test1.col1 = UNKNOWN.col1;"); // When: final Exception e = assertThrows( KsqlException.class, () -> extractor.extractDataSources(s...
public static org.apache.iceberg.Table loadIcebergTable(SparkSession spark, String name) throws ParseException, NoSuchTableException { CatalogAndIdentifier catalogAndIdentifier = catalogAndIdentifier(spark, name); TableCatalog catalog = asTableCatalog(catalogAndIdentifier.catalog); Table sparkTable =...
@Test public void testLoadIcebergTable() throws Exception { spark.conf().set("spark.sql.catalog.hive", SparkCatalog.class.getName()); spark.conf().set("spark.sql.catalog.hive.type", "hive"); spark.conf().set("spark.sql.catalog.hive.default-namespace", "default"); String tableFullName = "hive.default....
public Schema toKsqlSchema(final Schema schema) { try { final Schema rowSchema = toKsqlFieldSchema(schema); if (rowSchema.type() != Schema.Type.STRUCT) { throw new KsqlException("KSQL stream/table schema must be structured"); } if (rowSchema.fields().isEmpty()) { throw new K...
@Test public void shouldTranslateMaps() { final Schema connectSchema = SchemaBuilder .struct() .field("mapField", SchemaBuilder.map(Schema.STRING_SCHEMA, Schema.INT32_SCHEMA)) .build(); final Schema ksqlSchema = translator.toKsqlSchema(connectSchema); assertThat(ksqlSchema.field(n...
@Override public void run() { int numFilesCleaned = 0; long diskSpaceCleaned = 0L; try (Timer.Context t = cleanupRoutineDuration.time()) { final long nowMills = Time.currentTimeMillis(); Set<Path> oldLogDirs = selectDirsForCleanup(nowMills); final long no...
@Test public void testCleanupFn() throws IOException { try (TmpPath dir1 = new TmpPath(); TmpPath dir2 = new TmpPath()) { Files.createDirectory(dir1.getFile().toPath()); Files.createDirectory(dir2.getFile().toPath()); Map<String, Object> conf = Utils.readStormConfig(); ...
static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, final AppendEntriesResponse response, final long rpcSendTime) { if (id == null) { // replicator already was destroyed. return; } ...
@Test public void testOnHeartbeatReturnedTermMismatch() { final Replicator r = getReplicator(); final RpcRequests.AppendEntriesRequest request = createEmptyEntriesRequest(); final RpcRequests.AppendEntriesResponse response = RpcRequests.AppendEntriesResponse.newBuilder() // .setS...
@Override public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignClientFactory context, Target.HardCodedTarget<T> target) { if (!(feign instanceof PolarisFeignCircuitBreaker.Builder)) { return feign.target(target); } PolarisFeignCircuitBreaker.Builder builder = (PolarisFeignCircuitBr...
@Test public void testTarget() { PolarisFeignCircuitBreakerTargeter targeter = new PolarisFeignCircuitBreakerTargeter(circuitBreakerFactory, circuitBreakerNameResolver); targeter.target(new FeignClientFactoryBean(), new Feign.Builder(), new FeignClientFactory(), new Target.HardCodedTarget<>(TestApi.class, "/test")...
public Optional<DbEntityCatalogEntry> getByCollectionName(final String collection) { return Optional.ofNullable(entitiesByCollectionName.get(collection)); }
@Test void returnsEmptyOptionalsOnEmptyCatalog() { DbEntitiesCatalog catalog = new DbEntitiesCatalog(List.of()); assertThat(catalog.getByCollectionName("Guadalajara")).isEmpty(); }
@Override public IConfigContext getConfigContext() { return configContext; }
@Test void getConfigContext() { ConfigResponse configResponse = new ConfigResponse(); IConfigContext configContext = configResponse.getConfigContext(); assertNotNull(configContext); }
public static boolean isValidValue(Map<String, Object> serviceSuppliedConfig, Map<String, Object> clientSuppliedServiceConfig, String propertyName) { // prevent clients from violating SLAs as published by the service if (propertyName.eq...
@Test public void testParseFailureHttpRequestTimeout() { Map<String, Object> serviceSuppliedProperties = new HashMap<>(); serviceSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "1000"); Map<String, Object> clientSuppliedProperties = new HashMap<>(); clientSuppliedProperties.put(PropertyKe...
@CanDistro @PatchMapping @Secured(action = ActionTypes.WRITE) public String patch(HttpServletRequest request) throws Exception { String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); NamingUtils.checkServiceNameFormat(serviceName); String ip = WebUtils.required(...
@Test void testPatch() throws Exception { mockRequestParameter("metadata", "{}"); mockRequestParameter("app", "test"); mockRequestParameter("weight", "10"); mockRequestParameter("healthy", "false"); mockRequestParameter("enabled", "false"); assertEquals("ok", instance...
public static long toUpperCase(final long word) { final long mask = applyLowerCasePattern(word) >>> 2; return word & ~mask; }
@Test void toUpperCaseLong() { // given final byte[] asciiTable = getExtendedAsciiTable(); shuffleArray(asciiTable, random); // when for (int idx = 0; idx < asciiTable.length; idx += Long.BYTES) { final long value = getLong(asciiTable, idx); final lon...
static void validateJarPathNotNull(Path jarPath) { // Check that parameter is not null, because it is used to access the file if (Objects.isNull(jarPath)) { throw new JetException("File path can not be null"); } }
@Test public void testValidateJarPathNotNull() { assertThatThrownBy(() -> JarOnMemberValidator.validateJarPathNotNull(null)) .isInstanceOf(JetException.class) .hasMessageContaining("File path can not be null"); }
public void register(String noteId, String className, String event, String cmd) throws InvalidHookException { synchronized (registry) { if (!HookType.ValidEvents.contains(event)) { throw new InvalidHookException("event " + event + " is not valid hook event"); } if (n...
@Test void testValidEventCode() { assertThrows(InvalidHookException.class, () -> { InterpreterHookRegistry registry = new InterpreterHookRegistry(); // Test that only valid event codes ("pre_exec", "post_exec") are accepted registry.register("foo", "bar", "baz", "whatever"); }); }
static BaseFilesTable.ManifestReadTask fromJson(JsonNode jsonNode) { Preconditions.checkArgument(jsonNode != null, "Invalid JSON node for files task: null"); Preconditions.checkArgument( jsonNode.isObject(), "Invalid JSON node for files task: non-object (%s)", jsonNode); Schema dataTableSchema = Sc...
@Test public void invalidJsonNode() throws Exception { String jsonStr = "{\"str\":\"1\", \"arr\":[]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.reader().readTree(jsonStr); assertThatThrownBy(() -> FilesTableTaskParser.fromJson(rootNode.get("str"))) .isInstanceOf(Il...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BatchEventData that)) { return false; } return events != null ? events.equals(that.events) : that.events == null; }
@Test public void testEquals() { assertEquals(batchEventData, batchEventData); assertEquals(batchEventData, batchEventDataSameAttribute); assertNotEquals(null, batchEventData); assertNotEquals(new Object(), batchEventData); assertEquals(batchEventData, batchEventDataOtherSo...
public Optional<Throwable> run(String... arguments) { try { if (isFlag(HELP, arguments)) { parser.printHelp(stdOut); } else if (isFlag(VERSION, arguments)) { parser.printVersion(stdOut); } else { final Namespace namespace = pars...
@Test void unhandledExceptionsCustomCommandDebug() throws Exception { doThrow(new BadAppException()).when(command).run(any(), any(Namespace.class), any(Configuration.class)); assertThat(cli.run("custom", "--debug")) .hasValueSatisfying(t -> assertThat(t).isInstanceOf(RuntimeExceptio...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public ClusterInfo get() { return getClusterInfo(); }
@Test public void testClusterMetrics() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("cluster") .path("metrics").accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + ...
public static String truncateByByteLength(String str, Charset charset, int maxBytes, int factor, boolean appendDots) { //字符数*速算因子<=最大字节数 if (str == null || str.length() * factor <= maxBytes) { return str; } final byte[] sba = str.getBytes(charset); if (sba.length <= maxBytes) { return str; } //限制...
@Test public void truncateByByteLengthTest() { final String str = "This is English"; final String ret = StrUtil.truncateByByteLength(str, StandardCharsets.ISO_8859_1, 10, 1, false); assertEquals("This is En", ret); }
public Span newTrace() { return _toSpan(null, newRootContext(0)); }
@Test void useSpanAfterFinished_doesNotCauseBraveFlush() { simulateInProcessPropagation(tracer, tracer); GarbageCollectors.blockOnGC(); tracer.newTrace().start().abandon(); //trigger orphaned span check assertThat(spans).hasSize(1); assertThat(spans.get(0).annotations()) .extracting(Map.Entry:...
@Override public AuthLoginRespVO refreshToken(String refreshToken) { OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT); return AuthConvert.INSTANCE.convert(accessTokenDO); }
@Test public void testRefreshToken() { // 准备参数 String refreshToken = randomString(); // mock 方法 OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class); when(oauth2TokenService.refreshAccessToken(eq(refreshToken), eq("default"))) .thenReturn(...
Future<Boolean> canRoll(int podId) { LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId); return canRollBroker(descriptions, podId); }
@Test public void testMinIsrEqualsReplicasWithOfflineReplicas(VertxTestContext context) { KSB ksb = new KSB() .addNewTopic("A", false) .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "3") .addNewPartition(0) .replicaOn(0, 1, 2) ...
public static String processPattern(String pattern, TbMsg tbMsg) { try { String result = processPattern(pattern, tbMsg.getMetaData()); JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData()); if (json.isObject()) { Matcher matcher = DATA_PATTERN.matcher(result...
@Test public void testSimpleReplacement() { String pattern = "ABC ${metadata_key} $[data_key]"; TbMsgMetaData md = new TbMsgMetaData(); md.putValue("metadata_key", "metadata_value"); ObjectNode node = JacksonUtil.newObjectNode(); node.put("data_key", "data_value"); ...
@Override public String getName() { return FUNCTION_NAME; }
@Test public void testDivisionNullLiteral() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("div(%s,null)", INT_SV_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); Assert.assertTrue(transformFunction instanceof Divis...
public static int getRemoteExecutorTimesOfProcessors() { String timesString = System.getProperty("remote.executor.times.of.processors"); if (NumberUtils.isDigits(timesString)) { int times = Integer.parseInt(timesString); return times > 0 ? times : REMOTE_EXECUTOR_TIMES_OF_PROCESS...
@Test void testGetRemoteExecutorTimesOfProcessors() { int defaultExpectVal = 1 << 4; int defaultVal = RemoteUtils.getRemoteExecutorTimesOfProcessors(); assertEquals(defaultExpectVal, defaultVal); System.setProperty("remote.executor.times.of.processors", "10"); int va...
public void refreshStarted(long currentVersion, long requestedVersion) { updatePlanDetails = new ConsumerRefreshMetrics.UpdatePlanDetails(); refreshStartTimeNano = System.nanoTime(); refreshMetricsBuilder = new ConsumerRefreshMetrics.Builder(); refreshMetricsBuilder.setIsInitialLoad(curr...
@Test public void testRefreshStartedWithSubsequentLoad() { concreteRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); Assert.assertFalse(refreshMetrics.getIsInitialL...
String generateName(List<String> symbols) { if (_serverNodeUri == null) { throw new IllegalStateException("Cannot generate symbol table name with null server node URI."); } return _serverNodeUri + SERVER_NODE_URI_PREFIX_TABLENAME_SEPARATOR + _symbolTablePrefix + PREFIX_HASH_SEPARATOR + ...
@Test public void testGenerateName() { List<String> symbols = Collections.unmodifiableList(Arrays.asList("Haha", "Hehe")); String name = SYMBOL_TABLE_NAME_HANDLER.generateName(symbols); Assert.assertEquals(name, "https://Host:100/service|Prefix-" + symbols.hashCode()); }
@VisibleForTesting long calculateRenewalDelay(Clock clock, long nextRenewal) { long now = clock.millis(); long renewalDelay = Math.round(tokensRenewalTimeRatio * (nextRenewal - now)); LOG.debug( "Calculated delay on renewal is {}, based on next renewal {} and the ratio {}, an...
@Test public void calculateRenewalDelayShouldConsiderRenewalRatio() { Configuration configuration = new Configuration(); configuration.setBoolean(CONFIG_PREFIX + ".throw.enabled", false); configuration.set(DELEGATION_TOKENS_RENEWAL_TIME_RATIO, 0.5); DefaultDelegationTokenManager dele...
public static Date getDateFromString( String dateString ) throws ParseException { String dateFormat = detectDateFormat( dateString ); if ( dateFormat == null ) { throw new ParseException( "Unknown date format.", 0 ); } return getDateFromStringByFormat( dateString, dateFormat ); }
@Test public void testGetDateFromStringLocale() throws ParseException { assertEquals( SAMPLE_DATE_US, DateDetector.getDateFromString( SAMPLE_DATE_STRING_US, LOCALE_en_US ) ); try { DateDetector.getDateFromString( null ); } catch ( ParseException e ) { // expected exception } try { ...
public void process(final Exchange exchange) { final ExecutionContext executionContext = smooks.createExecutionContext(); try { executionContext.put(EXCHANGE_TYPED_KEY, exchange); String charsetName = (String) exchange.getProperty(Exchange.CHARSET_NAME); if (charsetNa...
@Test public void testProcess() throws Exception { context.addRoutes(createEdiToXmlRouteBuilder()); context.start(); assertOneProcessedMessage(); }
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testUpCastRetainsSubClassValues() throws Exception { ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); SubClass extended = handler.as(SubClass.class); extended.setExtended("subClassValue"); SubClass extended2 = extended.as(Simple.class).as(SubClass.clas...
@Override public Job drainJob(String project, String region, String jobId) { LOG.info("Draining {} under {}", jobId, project); Job job = new Job().setRequestedState(JobState.DRAINED.toString()); LOG.info("Sending job to update {}:\n{}", jobId, formatForLogging(job)); return Failsafe.with(clientRetryPo...
@Test public void testDrainJobThrowsException() throws IOException { when(getLocationJobs(client).update(any(), any(), any(), any())).thenThrow(new IOException()); assertThrows( FailsafeException.class, () -> new FakePipelineLauncher(client).drainJob(PROJECT, REGION, JOB_ID)); }
@Override public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) { Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems); Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems); //remove comment and blank item map. ...
@Test public void testAllSituation(){ ItemChangeSets changeSets = resolver.resolve(1, "#ww\nd=e\nb=c\na=b\n\nq=w\n#eee", mockBaseItemWith2Key1Comment1Blank()); Assert.assertEquals(2, changeSets.getDeleteItems().size()); Assert.assertEquals(2, changeSets.getUpdateItems().size()); Assert.assertEquals(5,...
@Override public void setValue(String value) throws IOException { checkValue(value); // if there are export values/an Opt entry there is a different // approach to setting the value if (!getExportValues().isEmpty()) { updateByOption(value); }...
@Test void testRadioButtonWithOptions() { File file = new File(TARGET_PDF_DIR, "PDFBOX-3656.pdf"); try (PDDocument pdfDocument = Loader.loadPDF(file)) { PDRadioButton radioButton = (PDRadioButton) pdfDocument.getDocumentCatalog().getAcroForm().getField("Checking/S...
@Override public final String toString() { StringBuilder out = new StringBuilder(); appendTo(out); return out.toString(); }
@Test void requireThatPredicatesCanBeBuiltUsingChainedMethodCalls() { assertEquals("country not in [no, se] or age in [20..] or height in [..160]", new Disjunction() .addOperand(new Negation(new FeatureSet("country").addValue("no").addValue("se"))) ...
void handleRestore(final QueuedCommand queuedCommand) { throwIfNotConfigured(); handleStatementWithTerminatedQueries( queuedCommand.getAndDeserializeCommand(commandDeserializer), queuedCommand.getAndDeserializeCommandId(), queuedCommand.getStatus(), Mode.RESTORE, queuedC...
@Test(expected = IllegalStateException.class) public void shouldThrowOnHandleRestoreIfNotConfigured() { // Given: statementExecutor = new InteractiveStatementExecutor( serviceContext, mockEngine, mockParser, mockQueryIdGenerator, commandDeserializer ); final Map...
protected static VplsOperation getOptimizedVplsOperation(Deque<VplsOperation> operations) { if (operations.isEmpty()) { return null; } // no need to optimize if the queue contains only one operation if (operations.size() == 1) { return operations.getFirst(); ...
@Test public void testOptimizeOperationsAToA() { Deque<VplsOperation> operations = new ArrayDeque<>(); VplsData vplsData = VplsData.of(VPLS1); vplsData.addInterfaces(ImmutableSet.of(V100H1)); VplsOperation vplsOperation = VplsOperation.of(vplsData, ...
@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_whenExternalUserAuthentication_shouldWriteIt() { when(commonSystemInformation.getExternalUserAuthentication()).thenReturn("LDAP"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External User Authentication", "LDAP"); }
public Future<KafkaVersionChange> reconcile() { return getVersionFromController() .compose(i -> getPods()) .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testNoopWithoutVersionFromSts(VertxTestContext context) { String kafkaVersion = VERSIONS.defaultVersion().version(); String interBrokerProtocolVersion = VERSIONS.defaultVersion().protocolVersion(); String logMessageFormatVersion = VERSIONS.defaultVersion().messageVersion();...
@Nonnull public static RuntimeException rethrow(@Nonnull final Throwable t) { com.hazelcast.internal.util.ExceptionUtil.rethrowIfError(t); throw peeledAndUnchecked(t); }
@Test public void when_throwableIsExecutionExceptionWithNullCause_then_returnHazelcastException() { ExecutionException exception = new ExecutionException(null); assertThrows(JetException.class, () -> { throw rethrow(exception); }); }