focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void enumerateImportedFields(SDDocumentType documentType) { var search = this.schemas.stream() .filter(s -> s.getDocument() != null) .filter(s -> s.getDocument().getName().equals(documentType.getName())) .f...
@Test void imported_fields_are_enumerated_and_copied_from_correct_search_instance() { String PARENT = "parent"; Schema parentSchema = new Schema(PARENT, MockApplicationPackage.createEmpty()); SDDocumentType parentDocument = new SDDocumentType(PARENT, parentSchema); var parentField = ...
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException { byte[] bytes = pollEntryBytes(timeout); if (bytes == null) { return null; } return DLQEntry.deserialize(bytes); }
@Test public void testFlushAfterDelay() throws Exception { Event event = new Event(); int eventsPerBlock = randomBetween(1,16); int eventsToWrite = eventsPerBlock - 1; event.setField("T", generateMessageContent(PAD_FOR_BLOCK_SIZE_EVENT/eventsPerBlock)); Timestamp timestamp = ...
@Override public final void afterPropertiesSet() { this.refreshLocalCache(); this.afterInitialize(); }
@Test public void testAfterPropertiesSet() { listener.afterPropertiesSet(); assertTrue(listener.getCache().containsKey(ConfigGroupEnum.APP_AUTH.name())); assertTrue(listener.getCache().containsKey(ConfigGroupEnum.PLUGIN.name())); assertTrue(listener.getCache().containsKey(ConfigGroup...
@Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof ChangesOnMyIssuesNotification)) { return null; } ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif; if (notification.getChange() instanceof AnalysisChange) { ...
@Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_user_change() { Project project = newProject("1"); String ruleName = randomAlphabetic(8); String host = randomAlphabetic(15); Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded()); ...
@Override public void applyFlowRules(FlowRule... flowRules) { FlowRuleOperations.Builder builder = FlowRuleOperations.builder(); for (FlowRule flowRule : flowRules) { builder.add(flowRule); } apply(builder.build()); }
@Test public void applyFlowRules() { FlowRule r1 = flowRule(1, 1); FlowRule r2 = flowRule(2, 2); FlowRule r3 = flowRule(3, 3); assertTrue("store should be empty", Sets.newHashSet(vnetFlowRuleService1.getFlowEntries(DID1)).isEmpty()); vnetFlowRuleService1.a...
public void transmit(final int msgTypeId, final DirectBuffer srcBuffer, final int srcIndex, final int length) { checkTypeId(msgTypeId); checkMessageLength(length); final AtomicBuffer buffer = this.buffer; long currentTail = buffer.getLong(tailCounterIndex); int recordOffset ...
@Test void shouldTransmitIntoEmptyBuffer() { final long tail = 0L; final int recordOffset = (int)tail; final int length = 8; final int recordLength = length + HEADER_LENGTH; final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT); final UnsafeBuffer...
public static String uncompress(byte[] compressedURL) { StringBuffer url = new StringBuffer(); switch (compressedURL[0] & 0x0f) { case EDDYSTONE_URL_PROTOCOL_HTTP_WWW: url.append(URL_PROTOCOL_HTTP_WWW_DOT); break; case EDDYSTONE_URL_PROTOCOL_HTTPS_...
@Test public void testUncompressWithSubdomainsAndTrailingSlash() throws MalformedURLException { String testURL = "http://www.forums.google.com/"; byte[] testBytes = {0x00, 'f', 'o', 'r', 'u', 'm', 's', '.', 'g', 'o', 'o', 'g', 'l', 'e', 0x00}; assertEquals(testURL, UrlBeaconUrlCompressor.unc...
@Override public BitMask set(int index) { if (index >= 64) { return BitMask.getEmpty(index+1).setAll(this).set(index); } this.mask = this.mask | (1L << index); return this; }
@Test public void testSet() { assertThat(new LongBitMask().set(0).toString()).isEqualTo("1"); assertThat(new LongBitMask().set(1).toString()).isEqualTo("2"); assertThat(new LongBitMask().set(65).toString()).isEqualTo("0, 2"); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } MapTableField field = (MapTableField) o; ...
@Test public void testEquals() { MapTableField field = new MapTableField("name1", QueryDataType.INT, false, QueryPath.KEY_PATH); checkEquals(field, new MapTableField("name1", QueryDataType.INT, false, QueryPath.KEY_PATH), true); checkEquals(field, new MapTableField("name2", QueryDataType.I...
public void sendCouponNewsletter() { try { // Retrieve the list of contacts from the "weekly-coupons-newsletter" contact // list // snippet-start:[sesv2.java2.newsletter.ListContacts] ListContactsRequest contactListRequest = ListContactsRequest.builder() .contactListName(CONTACT_LI...
@Test public void test_sendCouponNewsletter_success() { ListContactsResponse contactListResponse = ListContactsResponse.builder() .contacts( Contact.builder().emailAddress("user+ses-weekly-newsletter-1@example.com").build(), Contact.builder().emailAddress("user+ses-weekly-newslette...
public Plan validateReservationListRequest( ReservationSystem reservationSystem, ReservationListRequest request) throws YarnException { String queue = request.getQueue(); if (request.getEndTime() < request.getStartTime()) { String errorMessage = "The specified end time must be greater than " ...
@Test public void testListReservationsEmptyQueue() { ReservationListRequest request = new ReservationListRequestPBImpl(); request.setQueue(""); Plan plan = null; try { plan = rrValidator.validateReservationListRequest(rSystem, request); Assert.fail(); } catch (YarnException e) { ...
public Exchange createDbzExchange(DebeziumConsumer consumer, final SourceRecord sourceRecord) { final Exchange exchange; if (consumer != null) { exchange = consumer.createExchange(false); } else { exchange = super.createExchange(); } final Message message...
@Test void testIfCreatesExchangeFromSourceDeleteRecord() { final SourceRecord sourceRecord = createDeleteRecord(); final Exchange exchange = debeziumEndpoint.createDbzExchange(null, sourceRecord); final Message inMessage = exchange.getIn(); assertNotNull(exchange); // asser...
public IndexConfig addAttribute(String attribute) { addAttributeInternal(attribute); return this; }
@Test(expected = NullPointerException.class) public void testAttributeNullAdd() { new IndexConfig().addAttribute(null); }
public Duration getServerTimeoutOrThrow() { // readTimeout = DOWNSTREAM_OVERHEAD + serverTimeout TimeBudget serverBudget = readBudget().withReserved(DOWNSTREAM_OVERHEAD); if (serverBudget.timeLeft().get().compareTo(MIN_SERVER_TIMEOUT) < 0) throw new UncheckedTimeoutException("Timed o...
@Test public void justEnoughTime() { clock.advance(originalTimeout.minus(MINIMUM_TIME_LEFT)); timeouts.getServerTimeoutOrThrow(); }
@Override public void shutDown() throws NacosException { String className = this.getClass().getName(); NAMING_LOGGER.info("{} do shutdown begin", className); serverListManager.shutdown(); serverProxy.shutdown(); ThreadUtils.shutdownThreadPool(executorService, NAMING_LOGGER); ...
@Test void testShutDown() throws NacosException { //when nacosNamingMaintainService.shutDown(); //then verify(serverProxy, times(1)).shutdown(); verify(serverListManager, times(1)).shutdown(); verify(executorService, times(1)).shutdown(); }
protected static boolean isValidValue(Field f, Object value) { if (value != null) { return true; } Schema schema = f.schema(); Type type = schema.getType(); // If the type is null, any value is valid if (type == Type.NULL) { return true; } // If the type is a union that al...
@Test void isValidValueWithUnion() { // Verify that null values are not valid for a union with no null type: Schema unionWithoutNull = Schema .createUnion(Arrays.asList(Schema.create(Type.STRING), Schema.create(Type.BOOLEAN))); assertTrue(RecordBuilderBase.isValidValue(new Field("f", unionWithout...
@Override public void seekPastMagicBytes(ByteBuffer in) throws BufferUnderflowException { int magicCursor = 3; // Which byte of the magic we're looking for currently. while (true) { byte b = in.get(); // We're looking for a run of bytes that is the same as the packet magic b...
@Test(expected = BufferUnderflowException.class) public void testSeekPastMagicBytes() { // Fail in another way, there is data in the stream but no magic bytes. byte[] brokenMessage = ByteUtils.parseHex("000000"); MAINNET.getDefaultSerializer().seekPastMagicBytes(ByteBuffer.wrap(brokenMessage...
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = ...
@Test void testIntToBoolean() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("name", "myname"); map.put("male", 1); map.put("female", 0); PersonInfo personInfo = (PersonInfo) PojoUtils.realize(map, PersonInfo.class); assertEquals("myname", per...
long nextRecordingId() { return nextRecordingId; }
@Test void shouldComputeNextRecordingIdIfValueInHeaderIsZero() throws IOException { setNextRecordingId(0); try (Catalog catalog = new Catalog(archiveDir, null, 0, CAPACITY, clock, null, segmentFileBuffer)) { assertEquals(recordingThreeId + 1, catalog.nextRecordingId()); ...
private HelloWorld() { }
@Test void testHelloWorld() throws IOException { String outputDir = "target/test-output"; String outputFile = outputDir + "/HelloWorld.pdf"; String message = "HelloWorld.pdf"; new File(outputFile).delete(); String[] args = { outputFile, message }; HelloWorld.mai...
public JMXUriBuilder withObjectPropertiesReference(String aReferenceToHashtable) { if (aReferenceToHashtable.startsWith("#")) { addProperty("objectProperties", aReferenceToHashtable); } else { addProperty("objectProperties", "#" + aReferenceToHashtable); } return ...
@Test public void withObjectPropertiesReference() { assertEquals("jmx:platform?objectProperties=#op", new JMXUriBuilder().withObjectPropertiesReference("#op").toString()); }
@Override public ParsedLine parse(final String line, final int cursor, final ParseContext context) { final ParsedLine parsed = delegate.parse(line, cursor, context); if (context != ParseContext.ACCEPT_LINE) { return parsed; } if (UnclosedQuoteChecker.isUnclosedQuote(line)) { throw new EO...
@Test public void shouldAcceptIfEmptyLine() { // Given: givenDelegateWillReturn(""); // When: final ParsedLine result = parser.parse("what ever", 0, ParseContext.ACCEPT_LINE); // Then: assertThat(result, is(parsedLine)); }
@Bean public SpringWebSocketClientEventListener springWebSocketClientEventListener( final ShenyuClientConfig clientConfig, final Environment env, final ShenyuClientRegisterRepository shenyuClientRegisterRepository) { ShenyuClientConfig.ClientPropertiesConfig clientPropert...
@Test public void testSpringWebSocketClientEventListener() { MockedStatic<RegisterUtils> registerUtilsMockedStatic = mockStatic(RegisterUtils.class); registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(), any(), any())).thenReturn(Optional.ofNullable("token")); applicationContextR...
@GetInitialRestriction public OffsetByteRange getInitialRestriction( @Element SubscriptionPartition subscriptionPartition) { Offset offset = offsetReaderFactory.apply(subscriptionPartition).read(); return OffsetByteRange.of(new OffsetRange(offset.value(), Long.MAX_VALUE /* open interval */)); }
@Test public void getInitialRestrictionReadSuccess() { when(initialOffsetReader.read()).thenReturn(example(Offset.class)); OffsetByteRange range = sdf.getInitialRestriction(PARTITION); assertEquals(example(Offset.class).value(), range.getRange().getFrom()); assertEquals(Long.MAX_VALUE, range.getRange(...
public long count() { return dbCollection.countDocuments(); }
@Test void count() { assertThat(service.count()).isEqualTo(16L); }
public FEELFnResult<Object> invoke(@ParameterName("list") List list) { if ( list == null || list.isEmpty() ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty")); } else { try { return FEELFnResult.ofResult(C...
@Test void invokeListWithHeterogenousTypes() { FunctionTestUtil.assertResultError(maxFunction.invoke(Arrays.asList(1, "test", BigDecimal.valueOf(10.2))), InvalidParametersEvent.class); }
public static Builder newBlobColumnDefBuilder() { return new Builder(); }
@Test public void blobColumDef_is_nullable_by_default() { assertThat(newBlobColumnDefBuilder().setColumnName("a").build().isNullable()).isTrue(); }
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test(expected = NullPointerException.class) public void testInvalidValueOfNullArrayIPv4() { IpPrefix ipPrefix; byte[] value; value = null; ipPrefix = IpPrefix.valueOf(IpAddress.Version.INET, value, 24); }
@Override public void logoutSuccess(HttpRequest request, @Nullable String login) { checkRequest(request); if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug("logout success [IP|{}|{}][login|{}]", request.getRemoteAddr(), getAllIps(request), preventLogFlood(emptyIfNull(login))); ...
@Test public void logout_success_fails_with_NPE_if_request_is_null() { logTester.setLevel(Level.INFO); assertThatThrownBy(() -> underTest.logoutSuccess(null, "foo")) .isInstanceOf(NullPointerException.class) .hasMessage("request can't be null"); }
public SchemaKStream<K> selectKey( final FormatInfo valueFormat, final List<Expression> keyExpression, final Optional<KeyFormat> forceInternalKeyFormat, final Stacker contextStacker, final boolean forceRepartition ) { final boolean keyFormatChange = forceInternalKeyFormat.isPresent()...
@Test(expected = UnsupportedOperationException.class) public void shouldFailRepartitionTable() { // Given: givenInitialKStreamOf("SELECT * FROM test2 EMIT CHANGES;"); final UnqualifiedColumnReferenceExp col2 = new UnqualifiedColumnReferenceExp(ColumnName.of("COL2")); // When: schemaKTabl...
@Override public Long clusterCountKeysInSlot(int slot) { RedisClusterNode node = clusterGetNodeForSlot(slot); MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort())); RFuture<Long> f = executorService.readAsync(entry, St...
@Test public void testClusterCountKeysInSlot() { testInCluster(connection -> { Long t = connection.clusterCountKeysInSlot(1); assertThat(t).isZero(); }); }
@Override public void validateConnectorConfig(Map<String, String> connectorProps, Callback<ConfigInfos> callback) { validateConnectorConfig(connectorProps, callback, true); }
@Test public void testConfigValidationTopicsRegexWithDlq() { final Class<? extends Connector> connectorClass = SampleSinkConnector.class; AbstractHerder herder = createConfigValidationHerder(connectorClass, noneConnectorClientConfigOverridePolicy); Map<String, String> config = new HashMap<>...
@Override public List<byte[]> mGet(byte[]... keys) { if (isQueueing() || isPipelined()) { for (byte[] key : keys) { read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key); } return null; } CommandBatchService es = new CommandBatchServi...
@Test public void testMGet() { Map<byte[], byte[]> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(("test" + i).getBytes(), ("test" + i*100).getBytes()); } connection.mSet(map); List<byte[]> r = connection.mGet(map.keySet().toArray(new byte[0][])); ...
public void enableSendingOldValues() { this.sendOldValues = true; this.queryableName = storeName; }
@Test public void testSendingOldValue() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; @SuppressWarnings("unchecked") final KTableImpl<String, String, String> table1 = (KTableImpl<String, String, String>) builder.table(topic1, stri...
public static Workbook createBook(String excelFilePath) { return createBook(excelFilePath, false); }
@Test public void createBookTest(){ Workbook book = WorkbookUtil.createBook(true); assertNotNull(book); book = WorkbookUtil.createBook(false); assertNotNull(book); }
public void densify(FeatureMap fMap) { // Densify! - guitar solo List<String> featureNames = new ArrayList<>(fMap.keySet()); Collections.sort(featureNames); densify(featureNames); }
@Test public void testExtendedListExampleDensify() { MockOutput output = new MockOutput("UNK"); Example<MockOutput> example, expected; // Single feature, contiguous densification example = new ListExample<>(output, new String[]{"F0"}, new double[]{1.0}); example.densify(Arra...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStart, final Range<Instant> windowEnd, final Optional<Position> position ) { try { final WindowRangeQuery<GenericKey, GenericRow> query = WindowR...
@Test public void shouldReturnValueIfSessionStartsAtUpperBoundIfUpperBoundClosed() { // Given: final Range<Instant> startBounds = Range.closed( LOWER_INSTANT, UPPER_INSTANT ); final Instant wend = UPPER_INSTANT.plusMillis(1); givenSingleSession(UPPER_INSTANT, wend); // When: ...
public int getDepth(Throwable ex) { return getDepth(ex.getClass(), 0); }
@Test public void alwaysTrueForThrowable() { RollbackRule rr = new RollbackRule(java.lang.Throwable.class.getName()); assertThat(rr.getDepth(new MyRuntimeException("")) > 0).isTrue(); assertThat(rr.getDepth(new IOException()) > 0).isTrue(); assertThat(rr.getDepth(new ShouldNeverHappe...
public void initialize() { validateBundledPluginDirectory(); validateExternalPluginDirectory(); }
@Test void shouldCreatePluginDirectoryIfItDoesNotExist() { bundledPluginDir.delete(); new DefaultPluginJarLocationMonitor(systemEnvironment).initialize(); assertThat(bundledPluginDir).exists(); }
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type =...
@Test public void applyGeneratesIntegerUsingJavaTypeLong() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "integer"); objectNode.put("existingJavaType", "java....
public int computeThreshold(StreamConfig streamConfig, CommittingSegmentDescriptor committingSegmentDescriptor, @Nullable SegmentZKMetadata committingSegmentZKMetadata, String newSegmentName) { long desiredSegmentSizeBytes = streamConfig.getFlushThresholdSegmentSizeBytes(); if (desiredSegmentSizeBytes <= ...
@Test public void testNoRows() { SegmentFlushThresholdComputer computer = new SegmentFlushThresholdComputer(); StreamConfig streamConfig = mock(StreamConfig.class); when(streamConfig.getFlushThresholdSegmentSizeBytes()).thenReturn(300_0000L); CommittingSegmentDescriptor committingSegmentDescriptor =...
public Publisher<V> descendingIterator() { return iterator(-1, false); }
@Test public void testListIteratorPrevious() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.add(0)); sync(list.add(7)); sync(list.add(...
public long scan( final UnsafeBuffer termBuffer, final long rebuildPosition, final long hwmPosition, final long nowNs, final int termLengthMask, final int positionBitsToShift, final int initialTermId) { boolean lossFound = false; int rebuildOff...
@Test void shouldReplaceOldNakWithNewNak() { long rebuildPosition = ACTIVE_TERM_POSITION; long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L); insertDataFrame(offsetOfMessage(0)); insertDataFrame(offsetOfMessage(2)); lossDetector.scan(termBuffer, rebui...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertBytes() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("blob").dataType("blob").build(); Column column = OracleTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), col...
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof Http2DataFrame) { Http2DataFrame dataFrame = (Http2DataFrame) msg; encoder().writeData(ctx, dataFrame.stream().id(), dataFrame.content(), dataFrame.padd...
@Test public void windowUpdateMayFail() throws Exception { frameInboundWriter.writeInboundHeaders(3, request, 31, false); Http2Connection connection = frameCodec.connection(); Http2Stream stream = connection.stream(3); assertNotNull(stream); Http2HeadersFrame inboundHeaders ...
@ScalarOperator(GREATER_THAN_OR_EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean greaterThanOrEqual(@SqlType(StandardTypes.SMALLINT) long left, @SqlType(StandardTypes.SMALLINT) long right) { return left >= right; }
@Test public void testGreaterThanOrEqual() { assertFunction("SMALLINT'37' >= SMALLINT'37'", BOOLEAN, true); assertFunction("SMALLINT'37' >= SMALLINT'17'", BOOLEAN, true); assertFunction("SMALLINT'17' >= SMALLINT'37'", BOOLEAN, false); assertFunction("SMALLINT'17' >= SMALLINT'17'"...
@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 testCreatePartitionsRetryThrottlingExceptionWhenEnabled() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse( expectCreatePartitio...
public static GenericRecord convertToAvro(Schema schema, Message message) { return AvroSupport.convert(schema, message); }
@Test public void allFieldsSet_wellKnownTypesAndTimestampsAsRecords() throws IOException { Schema.Parser parser = new Schema.Parser(); Schema convertedSchema = parser.parse(getClass().getClassLoader().getResourceAsStream("schema-provider/proto/sample_schema_wrapped_and_timestamp_as_record.avsc")); Pair<Sa...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testOr() throws Exception { BinaryColumn col = binaryColumn("binary_field"); // both evaluate to false (no upper-case letters are in the dictionary) FilterPredicate B = eq(col, Binary.fromString("B")); FilterPredicate C = eq(col, Binary.fromString("C")); // both evaluate to tru...
@Override public Rule register(String ref, RuleKey ruleKey) { requireNonNull(ruleKey, "ruleKey can not be null"); Rule rule = rulesByUuid.get(ref); if (rule != null) { if (!ruleKey.repository().equals(rule.repository()) || !ruleKey.rule().equals(rule.key())) { throw new IllegalArgumentExcep...
@Test public void register_does_not_enforce_some_RuleKey_is_registered_under_a_single_id() { underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); for (int i = 0; i < someRandomInt(); i++) { Rule otherRule = underTest.register(Integer.toString(i), RuleKey.of(SOME_REPOSITORY, SOME_RU...
public static Builder builderFor(long snapshotId, SnapshotRefType type) { return new Builder(type, snapshotId); }
@Test public void testNoTypeFailure() { assertThatThrownBy(() -> SnapshotRef.builderFor(1L, null).build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Snapshot reference type must not be null"); }
static void populateMissingPredictedOutputFieldTarget(final Model model) { if (model.getOutput() != null && model.getMiningSchema() != null) { Optional<OutputField> predictedOutputField = model.getOutput().getOutputFields().stream() .filter(outputField -> (outputField.getResultFe...
@Test void populateMissingPredictedOutputFieldTarget() throws Exception { final InputStream inputStream = getFileInputStream(NO_OUTPUT_FIELD_TARGET_NAME_SAMPLE); final PMML pmml = org.jpmml.model.PMMLUtil.unmarshal(inputStream); final Model toPopulate = pmml.getModels().get(0); final...
public void addTimeline(TimelineEvent event) { timeline.add(event); }
@Test public void testAddDuplicateTimelineEvents() { WorkflowRuntimeSummary summary = new WorkflowRuntimeSummary(); TimelineEvent event = TimelineLogEvent.info("hello world"); summary.addTimeline(event); summary.addTimeline(TimelineLogEvent.info("hello world")); summary.addTimeline(TimelineLogEven...
@Override public BlameAlgorithmEnum getBlameAlgorithm(int availableProcessors, int numberOfFiles) { BlameAlgorithmEnum forcedStrategy = configuration.get(PROP_SONAR_SCM_USE_BLAME_ALGORITHM) .map(BlameAlgorithmEnum::valueOf) .orElse(null); if (forcedStrategy != null) { return forcedStrategy;...
@Test public void useRepositoryBlame_whenFileBlamePropsEnabled_shouldDisableRepoBlame() { when(configuration.get(DefaultBlameStrategy.PROP_SONAR_SCM_USE_BLAME_ALGORITHM)).thenReturn(Optional.of(GIT_FILES_BLAME.name())); assertThat(underTest.getBlameAlgorithm(1, 1)).isEqualTo(GIT_FILES_BLAME); }
public void append(ByteBuffer record, DataType dataType) throws InterruptedException { if (dataType.isEvent()) { writeEvent(record, dataType); } else { writeRecord(record, dataType); } }
@Test void testAppendEventFinishCurrentBuffer() throws Exception { bufferSize = RECORD_SIZE * 3; AtomicInteger finishedBuffers = new AtomicInteger(0); HsMemoryDataManagerOperation memoryDataManagerOperation = TestingMemoryDataManagerOperation.builder() ...
@Override public List<GrokPattern> saveAll(Collection<GrokPattern> patterns, ImportStrategy importStrategy) throws ValidationException { final Map<String, GrokPattern> newPatternsByName; try { newPatternsByName = patterns.stream().collect(Collectors.toMap(GrokPattern::name, Function.ide...
@Test public void issue_3949() { final List<GrokPattern> patternSet = new ArrayList<>(); // Also see: https://github.com/Graylog2/graylog2-server/issues/3949 patternSet.add(GrokPattern.create("POSTFIX_QMGR_REMOVED", "%{POSTFIX_QUEUEID:postfix_queueid}: removed")); patternSet.add(Gro...
public List<VespaConfigChangeAction> validate() { List<VespaConfigChangeAction> result = new ArrayList<>(); for (ImmutableSDField nextField : new LinkedHashSet<>(nextSchema.allConcreteFields())) { String fieldName = nextField.getName(); ImmutableSDField currentField = currentSche...
@Test void requireThatOutputExpressionsAreIgnoredInAdvancedScript() throws Exception { assertTrue(new ScriptFixture("{ input foo | switch { case \"audio\": input bar | index; case \"video\": input baz | index; default: 0 | index; }; }", "{ input foo | switch { case \"audio\": input bar | att...
@Override public final int hashCode() { return Objects.hash(enabled, writeCoalescing, implementation, className, factoryImplementation, factoryClassName, writeDelaySeconds, writeBatchSize, properties, initialLoadMode, offload); }
@Test public void testHashCode() { assumeDifferentHashCodes(); assertNotEquals(defaultCfg.hashCode(), cfgNotEnabled.hashCode()); assertNotEquals(defaultCfg.hashCode(), cfgNotWriteCoalescing.hashCode()); assertNotEquals(defaultCfg.hashCode(), cfgNonNullClassName.hashCode()); a...
@Override public String getResourceOutputNodeType() { return DictionaryConst.NODE_TYPE_FILE_FIELD; }
@Test public void testGetResourceOutputNodeType() throws Exception { assertEquals( DictionaryConst.NODE_TYPE_FILE_FIELD, analyzer.getResourceOutputNodeType() ); }
public Order placeOrder(Order body) throws RestClientException { return placeOrderWithHttpInfo(body).getBody(); }
@Test public void placeOrderTest() { Order body = null; Order response = api.placeOrder(body); // TODO: test validations }
@Override public boolean tryLock(final GlobalLockDefinition lockDefinition, final long timeoutMillis) { return globalLockPersistService.tryLock(lockDefinition, timeoutMillis); }
@Test void assertTryLock() { when(lockPersistService.tryLock(lockDefinition, 3000L)).thenReturn(true); assertTrue(lockContext.tryLock(lockDefinition, 3000L)); }
private List<BindingPattern> serverBindings(DeployState deployState, ConfigModelContext context, Element searchElement, Collection<BindingPattern> defaultBindings) { List<Element> bindings = XML.getChildren(searchElement, "binding"); if (bindings.isEmpty()) return List.copyOf(defaultBindings...
@Test void verify_bindings_for_builtin_handlers() { createBasicContainerModel(); JdiscBindingsConfig config = root.getConfig(JdiscBindingsConfig.class, "default/container.0"); JdiscBindingsConfig.Handlers defaultRootHandler = config.handlers(BindingsOverviewHandler.class.getName()); ...
@Override public int run(PrintWriter out, PrintWriter err, String... args) { try { return Main.main(System.in, out, err, args); } catch (RuntimeException e) { err.print(e.getMessage()); err.flush(); return 1; // pass non-zero value back indicating an error has happened } }
@Test public void testUsageOutputAfterLoadingViaToolName() { String name = "google-java-format"; assertThat( ServiceLoader.load(ToolProvider.class).stream() .map(ServiceLoader.Provider::get) .map(ToolProvider::name)) .contains(name); ToolProvider forma...
@Override public Mono<DeleteAccountResponse> deleteAccount(final DeleteAccountRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice(); return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifi...
@Test void deleteAccountLinkedDevice() { getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1)); //noinspection ResultOfMethodCallIgnored GrpcTestUtils.assertStatusException(Status.PERMISSION_DENIED, () -> authenticatedServiceStub().deleteAcco...
@Override public DictTypeDO getDictType(Long id) { return dictTypeMapper.selectById(id); }
@Test public void testGetDictType_id() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType); // 准备参数 Long id = dbDictType.getId(); // 调用 DictTypeDO dictType = dictTypeService.getDictType(id); // 断言 assertN...
@Override public void getConfig(ZookeeperServerConfig.Builder builder) { ConfigServer[] configServers = getConfigServers(); int[] zookeeperIds = getConfigServerZookeeperIds(); if (configServers.length != zookeeperIds.length) { throw new IllegalArgumentException(String.format("Nu...
@Test void testCuratorConfig() { CuratorConfig config = getConfig(CuratorConfig.class); assertEquals(1, config.server().size()); assertEquals("localhost", config.server().get(0).hostname()); assertEquals(2181, config.server().get(0).port()); assertEquals(120, config.zookeeper...
public static ReadRows readRows() { return new AutoValue_JdbcIO_ReadRows.Builder() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .setStatementPreparator(ignored -> {}) .build(); }
@Test @SuppressWarnings({"UnusedVariable", "AssertThrowsMultipleStatements"}) public void testReadRowsFailedToGetSchema() { Exception exc = assertThrows( BeamSchemaInferenceException.class, () -> { // Using a new pipeline object to avoid the various checks made by T...
@Override public boolean createTopic( final String topic, final int numPartitions, final short replicationFactor, final Map<String, ?> configs, final CreateTopicsOptions createOptions ) { final Optional<Long> retentionMs = KafkaTopicClient.getRetentionMs(configs); if (isTopicE...
@Test public void shouldThrowFromCreateTopicIfNoAclsSet() { // Given: when(adminClient.createTopics(any(), any())) .thenAnswer(createTopicsResult(new TopicAuthorizationException("error"))); // When: final Exception e = assertThrows( KsqlTopicAuthorizationException.class, () ->...
protected <T> Map<String, Object> generate(Class<? extends T> cls, @Nullable Class<T> base) { SchemaGeneratorConfigBuilder builder = new SchemaGeneratorConfigBuilder( SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON ); this.build(builder,false); // we don't ...
@SuppressWarnings("unchecked") @Test void trigger() throws URISyntaxException { Helpers.runApplicationContext((applicationContext) -> { JsonSchemaGenerator jsonSchemaGenerator = applicationContext.getBean(JsonSchemaGenerator.class); Map<String, Object> jsonSchema = jsonSchemaGen...
@Override public void validateUserList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得岗位信息 List<AdminUserDO> users = userMapper.selectBatchIds(ids); Map<Long, AdminUserDO> userMap = CollectionUtils.convertMap(users, AdminUserDO::getId); ...
@Test public void testValidateUserList_notEnable() { // mock 数据 AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); userMapper.insert(userDO); // 准备参数 List<Long> ids = singletonList(userDO.getId()); // 调用, 并断言异常 assertSer...
public HttpResponse get(Application application, String hostName, String serviceType, Path path, Query query) { return get(application, hostName, serviceType, path, query, null); }
@Test(expected = RequestTimeoutException.class) public void testFetchException() { when(fetcher.get(any(), any())).thenThrow(new RequestTimeoutException("timed out")); proxy.get(applicationMock, hostname, CLUSTERCONTROLLER_CONTAINER.serviceName, Path.parse("clustercontroller-statu...
@SuppressWarnings("unchecked") @Override public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { NodeStatus remoteNodeStatus = request.getNodeStatus(); /** * Here is the node heartbeat sequence... * 1. Check if it's a valid (i.e. not excl...
@Test public void testAddNewExcludePathToConfiguration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); ClusterMetrics metrics = ClusterMetrics....
public static String formatTime(Duration duration) { int totalSeconds = Ints.saturatedCast(duration.roundTo(SECONDS)); if (totalSeconds == 0) { return format("%sms", Ints.saturatedCast(duration.roundTo(MILLISECONDS))); } int minutes = totalSeconds / 60; int second...
@Test public void testFormatTime() { assertEquals(FormatUtils.formatTime(Duration.succinctNanos(100L)), "0ms"); assertEquals(FormatUtils.formatTime(Duration.succinctDuration(1.1, TimeUnit.MILLISECONDS)), "1ms"); assertEquals(FormatUtils.formatTime(Duration.succinctDuration(1.1, TimeUnit....
@Nullable public static String decrypt(String cipherText, String encryptionKey, String salt) { try { return tryDecrypt(cipherText, encryptionKey, salt); } catch (Exception ex) { LOG.error("Could not decrypt (legacy) value.", ex); return null; } }
@Test public void testDecryptStaticISO10126PaddedCipherText() { // The cipherText was encrypted using the legacy AES/CBC/ISO10126Padding transformation. // If this test fails, we changed the transformation. If the change was intentional, this test must // be updated, and we need to create a ...
@Override public DataSink createDataSink(Context context) { FactoryHelper.createFactoryHelper(this, context).validateExcept(PROPERTIES_PREFIX); Configuration configuration = Configuration.fromMap(context.getFactoryConfiguration().toMap()); DeliveryGuarantee deliveryGuarantee...
@Test void testCreateDataSink() { DataSinkFactory sinkFactory = FactoryDiscoveryUtils.getFactoryByIdentifier("kafka", DataSinkFactory.class); Assertions.assertThat(sinkFactory).isInstanceOf(KafkaDataSinkFactory.class); Configuration conf = Configuration.fromMap(ImmutableMap....
@Override public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey, @Nullable String projectName) { String key = Optional.ofNullable(projectKey).orElse(generateUniqueProjectKey()); boolean isManaged ...
@Test void createProjectAndBindToDevOpsPlatformFromScanner_whenVisibilitySyncDeactivated_successfullyCreatesProjectAndUseDefaultProjectVisibility() { // given mockGeneratedProjectKey(); ComponentCreationData componentCreationData = mockProjectCreation("generated_orga2/repo1"); ProjectAlmSettingDao pr...
@Override public void add(Object task, boolean priority) { checkNotNull(task, "task can't be null"); if (priority) { priorityQueue.add(task); normalQueue.add(TRIGGER_TASK); } else { normalQueue.add(task); } }
@Test(expected = NullPointerException.class) public void add_whenNull() { operationQueue.add(null, false); }
SortedReplicas(Broker broker, Set<Function<Replica, Boolean>> selectionFuncs, List<Function<Replica, Integer>> priorityFuncs, Function<Replica, Double> scoreFunction) { this(broker, null, selectionFuncs, priorityFuncs, scoreFunction, true); }
@Test public void testScoreFunctionOnly() { Broker broker = generateBroker(NUM_REPLICAS); broker.trackSortedReplicas(SORT_NAME, null, null, SCORE_FUNC); SortedReplicas sr = broker.trackedSortedReplicas(SORT_NAME); double lastScore = Double.NEGATIVE_INFINITY; for (Replica r : sr.sortedReplicas(fal...
public Map<E, ValuesAndExtrapolations> peekCurrentWindow() { // prevent window rolling. _windowRollingLock.lock(); try { Map<E, ValuesAndExtrapolations> result = new HashMap<>(); _rawMetrics.forEach((entity, rawMetric) -> { ValuesAndExtrapolations vae = rawMetric.peekCurrentWindow(_curre...
@Test public void testPeekCurrentWindow() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); // Add samples to three entities. // Entity1 has 2 windows with i...
@Override public void createPort(K8sPort port) { checkNotNull(port, ERR_NULL_PORT); checkArgument(!Strings.isNullOrEmpty(port.portId()), ERR_NULL_PORT_ID); checkArgument(!Strings.isNullOrEmpty(port.networkId()), ERR_NULL_PORT_NET_ID); k8sNetworkStore.createPort(port); log.in...
@Test(expected = IllegalArgumentException.class) public void createDuplicatePort() { target.createPort(PORT); target.createPort(PORT); }
@VisibleForTesting List<ExecNode<?>> calculatePipelinedAncestors(ExecNode<?> node) { List<ExecNode<?>> ret = new ArrayList<>(); AbstractExecNodeExactlyOnceVisitor ancestorVisitor = new AbstractExecNodeExactlyOnceVisitor() { @Override protected ...
@Test void testCalculateBoundedPipelinedAncestors() { // P = InputProperty.DamBehavior.PIPELINED, E = InputProperty.DamBehavior.END_INPUT // // 0 -P-> 1 -P-> 2 // 3 -P-> 4 -E/ TestingBatchExecNode[] nodes = new TestingBatchExecNode[5]; for (int i = 0; i < nodes.length...
public void isNotEqualTo(@Nullable Object unexpected) { standardIsNotEqualTo(unexpected); }
@Test public void isNotEqualToFailureWithNulls() { Object o = null; expectFailure.whenTesting().that(o).isNotEqualTo(null); assertFailureKeys("expected not to be"); assertFailureValue("expected not to be", "null"); }
public static int compare(Object o1, Object o2) { return o1.getClass() != o2.getClass() && o1 instanceof Number && o2 instanceof Number ? asBigDecimal((Number)o1).compareTo(asBigDecimal((Number)o2)) : ((Comparable) o1).compareTo(o2); }
@Test public void compareWithNumbers() { assertThat(OperatorUtils.compare(1, 1)).isZero(); assertThat(OperatorUtils.compare(1L, 1L)).isZero(); assertThat(OperatorUtils.compare(1.0f, 1.0f)).isZero(); assertThat(OperatorUtils.compare(1.0, 1.0)).isZero(); assertThat(OperatorUti...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 2) { onInvalidDataReceived(device, data); return; } // Read flags int offset = 0; final int flags = data.getIntValue(Data.FORMAT_UINT8, offse...
@Test public void onHeartRateMeasurementReceived_uint16() { success = false; final Data data = new Data(new byte[] { 0b11111, 1, 1, 50, 1, 1, 0, 2, 1, (byte) 0xFF, (byte) 0xFF}); response.onDataReceived(null, data); assertTrue(response.isValid()); assertTrue(success); assertEquals(257, heartRate); assert...
@Override public List<String> listTableNames(String dbName) { return deltaOps.getAllTableNames(dbName); }
@Test public void testListTableNames() { List<String> tableNames = deltaLakeMetadata.listTableNames("db1"); Assert.assertEquals(2, tableNames.size()); Assert.assertEquals("table1", tableNames.get(0)); Assert.assertEquals("table2", tableNames.get(1)); }
static void cleanStackTrace(Throwable throwable) { new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet()); }
@Test public void truthFrameWithOutSubject_shouldNotCleaned() { Throwable throwable = createThrowableWithStackTrace( "com.google.random.Package", // two or more truth frame will trigger string matching mechenism to got it collapsed "com.google.common.truth.FailureMetada...
public static void repair(final Path path) throws IOException { if (!path.toFile().isDirectory()) { throw new IllegalArgumentException( String.format("Given PQ path %s is not a directory.", path) ); } LOGGER.info("Start repairing queue dir: {}", path.toSt...
@Test public void testRemoveTempCheckPoint() throws Exception { Files.createFile(dataPath.resolve("checkpoint.head.tmp")); Files.createFile(dataPath.resolve("checkpoint.1.tmp")); PqRepair.repair(dataPath); verifyQueue(); }
@Converter(fallback = true) public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (NodeInfo.class.isAssignableFrom(value.getClass())) { // use a fallback type converter so we can convert the embedded body if the value is NodeInfo ...
@Test public void convertToDocument() { Document document = context.getTypeConverter().convertTo(Document.class, exchange, doc); assertNotNull(document); String string = context.getTypeConverter().convertTo(String.class, exchange, document); assertEquals(CONTENT, string); }
public static List<String> getParams(String description) { // find all match params key in description Matcher matcher = PARAMS_PATTERN.matcher(description); List<String> params = new ArrayList<>(); while (matcher.find()) { String key = matcher.group(1); params.ad...
@Test void testGetParamsForDescription() { String description = "test description with param <key1>, <key2> and <key3>."; Assertions.assertIterableEquals( Arrays.asList("key1", "key2", "key3"), ExceptionParamsUtil.getParams(description)); String description2 = "test descripti...
@Udf(description = "Returns the inverse (arc) tangent of y / x") public Double atan2( @UdfParameter( value = "y", description = "The ordinate (y) coordinate." ) final Integer y, @UdfParameter( value = "x", descriptio...
@Test public void shouldHandleNull() { assertThat(udf.atan2(null, 1), is(nullValue())); assertThat(udf.atan2(null, 1L), is(nullValue())); assertThat(udf.atan2(null, 0.45), is(nullValue())); assertThat(udf.atan2(1, null), is(nullValue())); assertThat(udf.atan2(1L, null), is(nullValue())); asser...
@Override public void validate() { super.validate(); sourceOptions.validate(); }
@Test public void testSourceOptionsWithNegativeNumRecords() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("numRecords should be a non-negative number, but found -100"); testSourceOptions.numRecords = -100; testSourceOptions.validate(); }
@Override public V get(final K key) { Objects.requireNonNull(key); final List<ReadOnlyKeyValueStore<K, V>> stores = storeProvider.stores(storeName, storeType); for (final ReadOnlyKeyValueStore<K, V> store : stores) { try { final V result = store.get(key); ...
@Test public void shouldReturnNullIfKeyDoesNotExist() { assertNull(theStore.get("whatever")); }
@Override public HttpResponse send(HttpRequest httpRequest) throws IOException { return send(httpRequest, null); }
@Test public void send_always_canonicalizesRequestUrl() throws IOException, InterruptedException { String responseBody = "test response"; mockWebServer.enqueue( new MockResponse() .setResponseCode(HttpStatus.OK.code()) .setHeader(CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toStrin...
public static <T extends PipelineOptions> T as(Class<T> klass) { return new Builder().as(klass); }
@Test public void testNotAllGettersAnnotatedWithJsonIgnore() throws Exception { // Initial construction is valid. GetterWithJsonIgnore options = PipelineOptionsFactory.as(GetterWithJsonIgnore.class); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( "E...
@Override public boolean isEmpty() { return multiResult.isEmpty(); }
@Test public void testIsEmpty_whenEmpty() { MultiResult<Integer> multiResult = new MultiResult<>(); immutableMultiResult = new ImmutableMultiResult<>(multiResult); assertTrue(immutableMultiResult.isEmpty()); }
public static Map<String, String> parseToMap(String attributesModification) { if (Strings.isNullOrEmpty(attributesModification)) { return new HashMap<>(); } // format: +key1=value1,+key2=value2,-key3,+key4=value4 Map<String, String> attributes = new HashMap<>(); Stri...
@Test public void parseToMap_ValidAttributesModification_ReturnsExpectedMap() { String attributesModification = "+key1=value1,+key2=value2,-key3,+key4=value4"; Map<String, String> result = AttributeParser.parseToMap(attributesModification); Map<String, String> expectedMap = new HashMap<>();...
@Override public PinotDataBuffer getBuffer(String column, IndexType<?, ?, ?> type) throws IOException { return checkAndGetIndexBuffer(column, type); }
@Test(expectedExceptions = RuntimeException.class) public void testMissingIndex() throws IOException, ConfigurationException { try (SingleFileIndexDirectory columnDirectory = new SingleFileIndexDirectory(TEMP_DIR, _segmentMetadata, ReadMode.mmap)) { columnDirectory.getBuffer("column1", Standar...
@Override public List<KsqlPartitionLocation> locate( final List<KsqlKey> keys, final RoutingOptions routingOptions, final RoutingFilterFactory routingFilterFactory, final boolean isRangeScan ) { if (isRangeScan && keys.isEmpty()) { throw new IllegalStateException("Query is range sc...
@Test public void shouldReturnActiveAndStandBysWhenRoutingStandbyEnabledHeartBeatNotEnabled() { // Given: getActiveAndStandbyMetadata(); // When: final List<KsqlPartitionLocation> result = locator.locate(ImmutableList.of(KEY), routingOptions, routingFilterFactoryStandby, false); // Then:...
public static Record convertDataRecordToRecord(final String database, final String schema, final DataRecord dataRecord) { List<TableColumn> before = new LinkedList<>(); List<TableColumn> after = new LinkedList<>(); for (Column column : dataRecord.getColumns()) { before.add(TableColum...
@Test void assertConvertDataRecordToRecord() throws InvalidProtocolBufferException, SQLException { DataRecord dataRecord = new DataRecord(PipelineSQLOperationType.INSERT, "t_order", new IntegerPrimaryKeyIngestPosition(0L, 1L), 2); dataRecord.addColumn(new Column("order_id", BigInteger.ONE, false, tr...
@Override public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback) { Mono<T> toReturn = toRun.transform(new PolarisCircuitBreakerReactorTransformer<>(invokeHandler)); if (fallback != null) { toReturn = toReturn.onErrorResume(throwable -> { if (throwable instanceof CallAbortedException) {...
@Test public void run() { this.reactiveContextRunner.run(context -> { ReactivePolarisCircuitBreakerFactory polarisCircuitBreakerFactory = context.getBean(ReactivePolarisCircuitBreakerFactory.class); ReactiveCircuitBreaker cb = polarisCircuitBreakerFactory.create(SERVICE_CIRCUIT_BREAKER); PolarisCircuitBrea...