focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public KTable<K, VOut> aggregate(final Initializer<VOut> initializer, final Materialized<K, VOut, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(initializer, NamedInternal.empty(), materialized); }
@Test public void shouldNotHaveNullInitializerOnAggregate() { assertThrows(NullPointerException.class, () -> cogroupedStream.aggregate(null)); }
public SerializableFunction<T, Row> getToRowFunction() { return toRowFunction; }
@Test public void testPrimitiveProtoToRow() throws InvalidProtocolBufferException { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(Primitive.getDescriptor()); SerializableFunction<DynamicMessage, Row> toRow = schemaProvider.getToRowFunction(); assertEquals(PRIMITIVE_ROW, toRow.apply(toDyn...
@ConstantFunction(name = "bitxor", argTypes = {SMALLINT, SMALLINT}, returnType = SMALLINT) public static ConstantOperator bitxorSmallInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createSmallInt((short) (first.getSmallint() ^ second.getSmallint())); }
@Test public void bitxorSmallInt() { assertEquals(0, ScalarOperatorFunctions.bitxorSmallInt(O_SI_10, O_SI_10).getSmallint()); }
@Subscribe public void onVarbitChanged(VarbitChanged event) { if (event.getVarbitId() == Varbits.IN_RAID) { removeVarTimer(OVERLOAD_RAID); removeGameTimer(PRAYER_ENHANCE); } if (event.getVarbitId() == Varbits.VENGEANCE_COOLDOWN && config.showVengeance()) { if (event.getValue() == 1) { creat...
@Test public void testDeathChargeCooldown() { when(timersAndBuffsConfig.showArceuusCooldown()).thenReturn(true); VarbitChanged varbitChanged = new VarbitChanged(); varbitChanged.setVarbitId(Varbits.DEATH_CHARGE_COOLDOWN); varbitChanged.setValue(1); timersAndBuffsPlugin.onVarbitChanged(varbitChanged); Ar...
@Override public Optional<JavaClass> tryResolve(String typeName) { String typeFile = typeName.replace(".", "/") + ".class"; Optional<URI> uri = tryGetUriOf(typeFile); return uri.isPresent() ? classUriImporter.tryImport(uri.get()) : Optional.empty(); }
@Test public void finds_uri_of_class_on_classpath() { JavaClass expectedJavaClass = importClassWithContext(Object.class); when(uriImporter.tryImport(TestUtils.uriOf(Object.class))).thenReturn(Optional.of(expectedJavaClass)); Optional<JavaClass> result = resolver.tryResolve(Object.class.getN...
public RandomAccessData increment() throws IOException { RandomAccessData copy = copy(); for (int i = copy.size - 1; i >= 0; --i) { if (copy.buffer[i] != UnsignedBytes.MAX_VALUE) { copy.buffer[i] = UnsignedBytes.checkedCast(UnsignedBytes.toInt(copy.buffer[i]) + 1L); return copy; } ...
@Test public void testIncrement() throws Exception { assertEquals( new RandomAccessData(new byte[] {0x00, 0x01}), new RandomAccessData(new byte[] {0x00, 0x00}).increment()); assertEquals( new RandomAccessData(new byte[] {0x01, UnsignedBytes.MAX_VALUE}), new RandomAccessData(new...
@Override protected Result[] run(String value) { final Map<String, Object> extractedJson; try { extractedJson = extractJson(value); } catch (IOException e) { throw new ExtractorException(e); } final List<Result> results = new ArrayList<>(extractedJson....
@Test public void testRunWithFlattenedObjectAndDifferentKVSeparator() throws Exception { final JsonExtractor jsonExtractor = new JsonExtractor(new MetricRegistry(), "json", "title", 0L, Extractor.CursorStrategy.COPY, "source", "target", ImmutableMap.<String, Object>of("flatten", true, "kv_se...
@Override public String trackTimerStart(String eventName) { return ""; }
@Test public void trackTimerStart() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); ...
@Override public void write(InputT element, Context context) throws IOException, InterruptedException { while (bufferedRequestEntries.size() >= maxBufferedRequests) { flush(); } addEntryToBuffer(elementConverter.apply(element, context), false); nonBlockingFlush(); }
@Test public void testThatSnapshotsAreTakenOfBufferCorrectlyBeforeAndAfterAutomaticFlush() throws IOException, InterruptedException { AsyncSinkWriterImpl sink = new AsyncSinkWriterImplBuilder().context(sinkInitContext).maxBatchSize(3).build(); sink.write("25"); s...
public SerializableFunction<Row, T> getFromRowFunction() { return fromRowFunction; }
@Test public void testWktRowToProto() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(WktMessage.getDescriptor()); SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction(); assertEquals(WKT_MESSAGE_PROTO.toString(), fromRow.apply(WKT_MESSAGE_ROW).toString()...
public static TypeBuilder<Schema> builder() { return new TypeBuilder<>(new SchemaCompletion(), new NameContext()); }
@Test void props() { Schema s = SchemaBuilder.builder().intBuilder().prop("p1", "v1").prop("p2", "v2").prop("p2", "v2real") // overwrite .endInt(); int size = s.getObjectProps().size(); assertEquals(2, size); assertEquals("v1", s.getProp("p1")); assertEquals("v2real", s.getProp("p2")); }
public static void write(HttpServletResponse response, String text, String contentType) { response.setContentType(contentType); Writer writer = null; try { writer = response.getWriter(); writer.write(text); writer.flush(); } catch (IOException e) { throw new UtilException(e); } finally { IoUtil...
@Test @Disabled public void jakartaWriteTest() { jakarta.servlet.http.HttpServletResponse response = null; byte[] bytes = StrUtil.utf8Bytes("地球是我们共同的家园,需要大家珍惜."); //下载文件 // 这里没法直接测试,直接写到这里,方便调用; //noinspection ConstantConditions if (response != null) { String fileName = "签名文件.pdf"; String contentTy...
@Nullable public DnsCache resolveCache() { return resolveCache; }
@Test void resolveCache() { assertThat(builder.build().resolveCache()).isNull(); TestDnsCache resolveCache = new TestDnsCache(); builder.resolveCache(resolveCache); assertThat(builder.build().resolveCache()).isEqualTo(resolveCache); }
@Override public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) { Collection<Stri...
@Test void assertDecideWhenContainsSameShardingCondition() { SelectStatementContext select = createStatementContext(); when(select.isContainsSubquery()).thenReturn(true); Collection<DataNode> includedDataNodes = new HashSet<>(); ShardingRule shardingRule = createShardingRule(); ...
@Override public Temporal with(TemporalField field, long newValue) { return getNewZoneOffset(offsetTime.with(field, newValue)); }
@Test void withTemporalField() { ZoneTime expected = new ZoneTime(offsetTime.with(ChronoField.HOUR_OF_DAY, 3), zoneId, false); assertEquals(expected, zoneTime.with(ChronoField.HOUR_OF_DAY, 3)); }
public static MusicProtocol.MusicAlbum convertMusicReleaseToMusicAlbum(MusicRelease release) { MusicProtocol.MusicAlbum.Builder albumBuilder = MusicProtocol.MusicAlbum.newBuilder(); if (release == null) { return albumBuilder.build(); } if (!StringUtils.isBlank(release.getTi...
@Test public void testConvertMusicReleaseToMusicAlbum() { String expectedArtistName = "Expected Artist Name"; MusicGroup musicGroup = new MusicGroup(expectedArtistName); String expectedICPN = "1234567890abcdefg"; String expectedTitle = "Expected Album Title"; MusicProtocol.M...
protected ScopeTimeConfig calculateStartAndEndForJudgement( CanaryAnalysisExecutionRequest config, long judgementNumber, Duration judgementDuration) { Duration warmupDuration = config.getBeginCanaryAnalysisAfterAsDuration(); Duration offset = judgementDuration.multipliedBy(judgementNumber); ScopeTim...
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_start_iso_only_is_defined() { int interval = 1; String startIso = "2018-12-17T20:56:39.689Z"; Duration lifetimeDuration = Duration.ofMinutes(3L); CanaryAnalysisExecutionRequest request = CanaryAn...
public static SFChooseIdentityPanel sharedChooseIdentityPanel() { return Rococoa.createClass("SFChooseIdentityPanel", SFChooseIdentityPanel._Class.class).sharedChooseIdentityPanel(); }
@Test public void sharedChooseIdentityPanel() { assertNotNull(SFChooseIdentityPanel.sharedChooseIdentityPanel()); }
public CoordinatorResult<TxnOffsetCommitResponseData, CoordinatorRecord> commitTransactionalOffset( RequestContext context, TxnOffsetCommitRequestData request ) throws ApiException { return offsetMetadataManager.commitTransactionalOffset(context, request); }
@Test public void testCommitTransactionalOffset() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class); CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class); C...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabl...
@Test public void testListPlaceholderDot() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path placeholder = new S3Dire...
@SuppressWarnings("ChainOfInstanceofChecks") public OpenFileInformation prepareToOpenFile( final Path path, final OpenFileParameters parameters, final long blockSize) throws IOException { Configuration options = parameters.getOptions(); Set<String> mandatoryKeys = parameters.getMandatoryKeys...
@Test public void testStatusWithValidFilename() throws Throwable { Path p = new Path("file:///tmp/" + TESTPATH.getName()); ObjectAssert<OpenFileSupport.OpenFileInformation> asst = assertFileInfo(prepareToOpenFile( params(FS_OPTION_OPENFILE_LENGTH, "32") .withStatus(status(p...
public String generateHeader() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.cert_type"), x509cert.getType()); append(builder, NLS.str("certificate.serialSigVer"), ((Integer) x509cert.getVersion()).toString()); // serial number append(builder, NLS.str("certificate.serialN...
@Test public void decodeDSAKeyHeader() { assertThat(certificateManagerDSA.generateHeader()) .contains("X.509") .contains("0x16420ba2") .contains("O=\"UJMRFVV CN=EDCVBGT C=TG\""); }
public static Driver load(String className) throws DriverLoadException { final ClassLoader loader = DriverLoader.class.getClassLoader(); return load(className, loader); }
@Test public void testLoad_String_String() throws Exception { String className = "com.mysql.jdbc.Driver"; //we know this is in target/test-classes //File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile(); File ...
String getFileName(double lat, double lon) { int lonInt = getMinLonForTile(lon); int latInt = getMinLatForTile(lat); return toLowerCase(getLatString(latInt) + getNorthString(latInt) + getLonString(lonInt) + getEastString(lonInt) + FILE_NAME_END); }
@Test public void testFileNotFound() { File file = new File(instance.getCacheDir(), instance.getFileName(46, -20) + ".gh"); File zipFile = new File(instance.getCacheDir(), instance.getFileName(46, -20) + ".tif"); file.delete(); zipFile.delete(); instance.setDownloader(new Do...
public String getFieldNames() { if (StringUtils.isBlank(fieldNames)) { this.fieldNames = this.fields.stream().map(TableField::getColumnName).collect(Collectors.joining(", ")); } return this.fieldNames; }
@Test void getFieldNamesTest() { TableInfo tableInfo; ConfigBuilder configBuilder; configBuilder = new ConfigBuilder(GeneratorBuilder.packageConfig(), dataSourceConfig, GeneratorBuilder.strategyConfig(), null, null, null); tableInfo = new TableInfo(configBuilder, "name"); tab...
@Override public Iterator iterator() { if (entries == null) { return Collections.emptyIterator(); } return new ResultIterator(); }
@Test public void testIterator_whenNotEmpty_IterationType_Entry() { List<Map.Entry> entries = new ArrayList<>(); MapEntrySimple entry = new MapEntrySimple("key", "value"); entries.add(entry); ResultSet resultSet = new ResultSet(entries, IterationType.ENTRY); Iterator<Map.Entr...
public void remove(ConnectorTaskId id) { final ScheduledFuture<?> task = committers.remove(id); if (task == null) return; try (LoggingContext loggingContext = LoggingContext.forTask(id)) { task.cancel(false); if (!task.isDone()) task.get(); ...
@Test public void testRemoveTaskAndInterrupted() throws ExecutionException, InterruptedException { expectRemove(); when(taskFuture.get()).thenThrow(new InterruptedException()); committers.put(taskId, taskFuture); assertThrows(ConnectException.class, () -> committer.remove(taskId)); ...
@SuppressWarnings({"rawtypes", "unchecked"}) public SchemaMetaData revise(final SchemaMetaData originalMetaData) { SchemaMetaData result = originalMetaData; for (Entry<ShardingSphereRule, MetaDataReviseEntry> entry : OrderedSPILoader.getServices(MetaDataReviseEntry.class, rules).entrySet()) { ...
@Test void assertReviseWithoutMetaDataReviseEntry() { SchemaMetaData schemaMetaData = new SchemaMetaData("expected", Collections.singleton(mock(TableMetaData.class))); SchemaMetaData actual = new SchemaMetaDataReviseEngine( Collections.emptyList(), new ConfigurationProperties(new Pro...
@Override public Object convertToPropertyType(Class<?> entityType, String[] propertyPath, String value) { IndexValueFieldDescriptor fieldDescriptor = getValueFieldDescriptor(entityType, propertyPath); if (fieldDescriptor == null) { return super.convertToPropertyType(entityType, propertyPath, val...
@Test public void testConvertIntProperty() { assertThat(convertToPropertyType(TestEntity.class, "i", "42")).isEqualTo(42); }
public String deserialize(String password, String encryptedPassword, Validatable config) { if (isNotBlank(password) && isNotBlank(encryptedPassword)) { config.addError(PASSWORD, "You may only specify `password` or `encrypted_password`, not both!"); config.addError(ScmMaterialConfig.ENCRY...
@Test public void shouldErrorOutWhenBothPasswordAndEncryptedPasswordAreGivenForDeserialization() throws CryptoException { SvnMaterialConfig svnMaterialConfig = svn(); PasswordDeserializer passwordDeserializer = new PasswordDeserializer(); passwordDeserializer.deserialize("password", new GoCi...
public Class<?> getServiceInterfaceClass() { return serviceInterfaceClass; }
@Test void getServiceInterfaceClass() { Assertions.assertEquals(DemoService.class, service.getServiceInterfaceClass()); }
public void run() throws Exception { final Terminal terminal = TerminalBuilder.builder() .nativeSignals(true) .signalHandler(signal -> { if (signal == Terminal.Signal.INT || signal == Terminal.Signal.QUIT) { if (execState == ExecState.R...
@Test public void testFileMode() throws Exception { Terminal terminal = TerminalBuilder.builder().build(); final MockLineReader linereader = new MockLineReader(terminal); final Properties props = new Properties(); props.setProperty("webServiceUrl", "http://localhost:8080"); ...
@Override public boolean edgeExists(String source, String target) { checkId(source); checkId(target); NodeDraftImpl sourceNode = getNode(source); NodeDraftImpl targetNode = getNode(target); if (sourceNode != null && targetNode != null) { boolean undirected = edgeD...
@Test public void testEdgeExistsSelfLoop() { ImportContainerImpl importContainer = new ImportContainerImpl(); generateTinyGraphWithSelfLoop(importContainer, EdgeDirection.DIRECTED); Assert.assertTrue(importContainer.edgeExists("1", "1")); importContainer = new ImportContainerImpl();...
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void variable() throws ScanException { String input = "${k0}"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); assertEquals("v0", nodeToStringTransformer.transform()); }
public static <T> T[] getBeans(Class<T> interfaceClass) { Object object = serviceMap.get(interfaceClass.getName()); if(object == null) return null; if(object instanceof Object[]) { return (T[])object; } else { Object array = Array.newInstance(interfaceClass, 1); ...
@Test public void testArrayFromSingle() { // get an array with only one implementation. A[] a = SingletonServiceFactory.getBeans(A.class); Assert.assertEquals(1, a.length); }
@Override public void open(Configuration parameters) throws Exception { this.rateLimiterTriggeredCounter = getRuntimeContext() .getMetricGroup() .addGroup( TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT) .counter(TableMain...
@Test void testEqDeleteRecordCount() throws Exception { TriggerManager manager = manager( sql.tableLoader(TABLE_NAME), new TriggerEvaluator.Builder().eqDeleteRecordCount(3).build()); try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness = ...
@Override public Num calculate(BarSeries series, Position position) { return numberOfPositionsCriterion.calculate(series, position); }
@Test public void calculateWithShortPositions() { BarSeries series = new MockBarSeries(numFunction, 100d, 95d, 102d, 105d, 97d, 113d); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(2, series), Trade.sellAt(3, series), Trade.buyAt(4, series))...
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowIfHandlerSupplierThrows0() { HandlerMaps.forClass(BaseType.class) .put(LeafTypeA.class, () -> { throw new RuntimeException("Boom"); }) .build(); }
@ProcessElement public ProcessContinuation processElement( @Element PulsarSourceDescriptor pulsarSourceDescriptor, RestrictionTracker<OffsetRange, Long> tracker, WatermarkEstimator watermarkEstimator, OutputReceiver<PulsarMessage> output) throws IOException { long startTimestamp = tr...
@Test public void testProcessElement() throws Exception { MockOutputReceiver receiver = new MockOutputReceiver(); long startOffset = fakePulsarReader.getStartTimestamp(); long endOffset = fakePulsarReader.getEndTimestamp(); OffsetRangeTracker tracker = new OffsetRangeTracker(new OffsetRange(startOffse...
@Override public List<Column> getPartitionColumns() { List<Column> partitionColumns = new ArrayList<>(); if (!partColNames.isEmpty()) { partitionColumns = partColNames.stream().map(this::getColumn) .collect(Collectors.toList()); } return partitionColum...
@Test public void testPartitionKeys() { List<ColumnSchema> columns = Arrays.asList( genColumnSchema("a", org.apache.kudu.Type.INT32), genColumnSchema("b", org.apache.kudu.Type.STRING), genColumnSchema("c", org.apache.kudu.Type.DATE) ); List<Col...
public static <T> CloseableResource<T> of(T resource, Closer<T> closer) { checkArgument(resource != null, "Resource must be non-null"); checkArgument(closer != null, "%s must be non-null", Closer.class.getName()); return new CloseableResource<>(resource, closer); }
@Test public void wrapsExceptionsInCloseException() throws Exception { Exception wrapped = new Exception(); thrown.expect(CloseException.class); thrown.expectCause(is(wrapped)); try (CloseableResource<Foo> ignored = CloseableResource.of( new Foo(), foo -> { ...
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void cluster_not_down_if_more_than_min_ratio_of_distributors_available() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(3) .bringEntireClusterUp() .reportDistributorNodeState(0, State.DOWN); final ClusterStateGenerator.Params params = fixture.gen...
@Override public void open(Configuration parameters) throws Exception { this.rateLimiterTriggeredCounter = getRuntimeContext() .getMetricGroup() .addGroup( TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT) .counter(TableMain...
@Test void testCommitCount() throws Exception { TriggerManager manager = manager(sql.tableLoader(TABLE_NAME), new TriggerEvaluator.Builder().commitCount(3).build()); try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness = harness(manager)) { testHarness.o...
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersion.class) || resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersions.class)) { checkVersion(...
@Test public void testFilterWithMultipleDistributionsSuccess() throws Exception { final Method resourceMethod = TestResourceWithMultipleSupportedVersions.class.getMethod("methodWithAnnotation"); when(resourceInfo.getResourceMethod()).thenReturn(resourceMethod); when(versionProvider.get()).th...
@Override public String[] getManagedIndices() { final Set<String> indexNames = indices.getIndexNamesAndAliases(getIndexWildcard()).keySet(); // also allow restore archives to be returned final List<String> result = indexNames.stream() .filter(this::isManagedIndex) ...
@Test public void nullIndexerDoesNotThrowOnIndexName() { final String[] indicesNames = mongoIndexSet.getManagedIndices(); assertThat(indicesNames).isEmpty(); }
@Override public void startScheduling() { checkIdleSlotTimeout(); state.as(Created.class) .orElseThrow( () -> new IllegalStateException( "Can only start scheduling when being in Created st...
@Test void testStartSchedulingSetsResourceRequirementsForReactiveMode() throws Exception { final JobGraph jobGraph = createJobGraph(); final DefaultDeclarativeSlotPool declarativeSlotPool = createDeclarativeSlotPool(jobGraph.getJobID()); final Configuration configuration = ...
@Udf(description = "Converts a string representation of a date in the given format" + " into a DATE value.") public Date parseDate( @UdfParameter( description = "The string representation of a date.") final String formattedDate, @UdfParameter( description = "The format pattern sh...
@Test public void shouldSupportEmbeddedChars() { // When: final Date result = udf.parseDate("2021-12-01Fred", "yyyy-MM-dd'Fred'"); // Then: assertThat(result.getTime(), is(1638316800000L)); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { JWTBearerAssertionAuthenticationToken jwtAuth = (JWTBearerAssertionAuthenticationToken)authentication; try { ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getName()); JWT...
@Test public void should_return_valid_token_when_audience_contains_token_endpoint() { JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder() .issuer(CLIENT_ID) .subject(SUBJECT) .expirationTime(new Date()) .audience(ImmutableList.of("http://issuer.com/token", "invalid")) .build(); JWT jwt = mockSign...
public static long nextLong(final long startInclusive, final long endExclusive) { checkParameters(startInclusive, endExclusive); long diff = endExclusive - startInclusive; if (diff == 0) { return startInclusive; } return (long) (startInclusive + (diff * RANDOM.nextDou...
@Test void testNextLongWithIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> { RandomUtils.nextLong(999L, 199L); }); }
public Mono<Void> resetToOffsets( KafkaCluster cluster, String group, String topic, Map<Integer, Long> targetOffsets) { Preconditions.checkNotNull(targetOffsets); var partitionOffsets = targetOffsets.entrySet().stream() .collect(toMap(e -> new TopicPartition(topic, e.getKey()), Map.Entry::getValue...
@Test void resetToOffsetsCommitsEarliestOrLatestOffsetsIfOffsetsBoundsNotValid() { sendMsgsToPartition(Map.of(0, 10, 1, 10, 2, 10)); var offsetsWithInValidBounds = Map.of(0, -2L, 1, 5L, 2, 500L); var expectedOffsets = Map.of(0, 0L, 1, 5L, 2, 10L); offsetsResetService.resetToOffsets(cluster, groupId, ...
static Map<String, String> determineHeadersFrom(final Response response) { final HttpFields headers = response.getHeaders(); final Map<String, String> answer = new LinkedHashMap<>(); for (final HttpField header : headers) { final String headerName = header.getName(); if...
@Test public void shouldDetermineHeadersFromResponse() { final Response response = mock(Response.class); final HttpFields.Mutable httpHeaders = HttpFields.build(); httpHeaders.add("Date", "Mon, 20 May 2013 22:21:46 GMT"); httpHeaders.add("Sforce-Limit-Info", "api-usage=18/5000"); ...
public Span newTrace() { return _toSpan(null, newRootContext(0)); }
@Test void newTrace_isRootSpan() { assertThat(tracer.newTrace()) .satisfies(s -> assertThat(s.context().parentId()).isNull()) .isInstanceOf(RealSpan.class); }
public void completeSegmentOperations(String tableNameWithType, SegmentMetadata segmentMetadata, FileUploadType uploadType, @Nullable URI finalSegmentLocationURI, File segmentFile, @Nullable String sourceDownloadURIStr, String segmentDownloadURIStr, @Nullable String crypterName, long segmentSizeInByte...
@Test public void testCompleteSegmentOperations() throws Exception { ZKOperator zkOperator = new ZKOperator(_resourceManager, mock(ControllerConf.class), mock(ControllerMetrics.class)); SegmentMetadata segmentMetadata = mock(SegmentMetadata.class); when(segmentMetadata.getName()).thenReturn(SEGMENT...
@Override public ExecuteContext doBefore(ExecuteContext context) { DatabaseInfo databaseInfo = getDataBaseInfo(context); Query query = (Query) context.getArguments()[0]; String sql = query.toString((ParameterList) context.getArguments()[1]); String database = databaseInfo.getDatabase...
@Test public void testDoBefore() throws Exception { // Database write prohibition switch turned off GLOBAL_CONFIG.setEnablePostgreSqlWriteProhibition(false); ExecuteContext context = ExecuteContext.forMemberMethod(queryExecutor, methodMock, argument, null, null); queryExecutorImplInt...
@Override public ConfigOperateResult insertOrUpdateTag(final ConfigInfo configInfo, final String tag, final String srcIp, final String srcUser) { if (findConfigInfo4TagState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), tag) == null) { return ...
@Test void testInsertOrUpdateTagOfAdd() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; String appName = "appname1234"; String content = "c12345"; ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, conte...
public void createQprofileChangesForRuleUpdates(DbSession dbSession, Set<PluginRuleUpdate> pluginRuleUpdates) { List<QProfileChangeDto> changesToPersist = pluginRuleUpdates.stream() .flatMap(pluginRuleUpdate -> { RuleChangeDto ruleChangeDto = createNewRuleChange(pluginRuleUpdate); insertRuleCh...
@Test public void updateWithoutCommit_whenNoRuleChanges_thenDontInteractWithDatabase() { underTest.createQprofileChangesForRuleUpdates(mock(), Set.of()); verifyNoInteractions(dbClient); }
@SuppressWarnings("checkstyle:magicnumber") protected boolean tryProcess4(@Nonnull Object item) throws Exception { return tryProcess(4, item); }
@Test public void when_tryProcess4_then_delegatesToTryProcess() throws Exception { // When boolean done = p.tryProcess4(MOCK_ITEM); // Then assertTrue(done); p.validateReceptionOfItem(ORDINAL_4, MOCK_ITEM); }
public HostAndPort getHttpBindAddress() { return httpBindAddress .requireBracketsForIPv6() .withDefaultPort(GRAYLOG_DEFAULT_PORT); }
@Test public void testHttpBindAddressWithCustomPort() throws RepositoryException, ValidationException { jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_bind_address", "example.com:12345"))) .addConfigurationBean(configuration) .process(); assertT...
public Predicate convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testNotEq() { ConstantOperator value = ConstantOperator.createInt(5); ScalarOperator op = new BinaryPredicateOperator(BinaryType.NE, F0, value); Predicate result = CONVERTER.convert(op); Assert.assertTrue(result instanceof LeafPredicate); LeafPredicate leafP...
public static String asString(byte[] bytes, Charset charset) { if (charset == null) { charset = detectUtfCharset(bytes); } return skipBOM(new String(bytes, charset)); }
@Test void validateTextConversionFromBytes() { assertEquals("A", UtfTextUtils.asString(hexBytes("EFBBBF41"), StandardCharsets.UTF_8)); assertEquals("A", UtfTextUtils.asString(hexBytes("EFBBBF41"), null)); assertEquals("A", UtfTextUtils.asString(hexBytes("41"), StandardCharsets.UTF_8)); assertEquals("...
protected Object createAndFillObject(ObjectNode json, Object toReturn, String className, List<String> genericClasses) { Iterator<Map.Entry<String, JsonNode>> fields = json.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> element = fields.next(); String key = eleme...
@Test public void convertObject_simpleList() { ObjectNode objectNode = new ObjectNode(factory); objectNode.put("key1", "Polissena"); objectNode.put("key2", "Antonia"); Object result = expressionEvaluator.createAndFillObject(objectNode, new HashMap<>(), Map.class.getCanonicalName(),...
public static int getApplicableNodeCountForAM(RMContext rmContext, Configuration conf, List<ResourceRequest> amReqs) { // Determine the list of nodes that are eligible based on the strict // resource requests Set<NodeId> nodesForReqs = new HashSet<>(); for (ResourceRequest amReq : amReqs) { ...
@Test public void testGetApplicableNodeCountForAMLocalityAndLabels() throws Exception { List<NodeId> rack1Nodes = new ArrayList<>(); for (int i = 0; i < 29; i++) { rack1Nodes.add(NodeId.newInstance("host" + i, 1234)); } NodeId node1 = NodeId.newInstance("node1", 1234); NodeId node2 = N...
public SelectionAdapterOptions( SelectionOperation selectionOperation, String[] filters, String defaultFilter, String[] providerFilters, boolean useSchemaPath ) { this.selectionOperation = selectionOperation; this.filters = filters; this.defaultFilter = defaultFilter; ...
@Test public void testSelectionAdapterOptions() { SelectionOperation selectionOperation = SelectionOperation.FILE; FilterType[] filterTypes = new FilterType[] { FilterType.ALL, FilterType.CSV, FilterType.TXT }; FilterType defaultFilter = FilterType.CSV; String[] providerFilters = new String[] { "local...
@ConstantFunction.List(list = { @ConstantFunction(name = "subdate", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true), @ConstantFunction(name = "date_sub", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true), @ConstantFunction(name = "days_sub"...
@Test public void daysSub() { assertEquals("2015-03-13T09:23:55", ScalarOperatorFunctions.daysSub(O_DT_20150323_092355, O_INT_10).getDatetime().toString()); }
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null!"); byte[] ...
@Test public void testRename_keyNotExist() { Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot)); if (sameSlot) { // This is a quirk of the implementation - since same-slot renames use the non...
public SubscriptionName createSubscription(TopicName topicName, String subscriptionName) { checkArgument(!subscriptionName.isEmpty(), "subscriptionName can not be empty"); checkIsUsable(); if (!createdTopics.contains(topicName)) { throw new IllegalArgumentException( "Can not create a subscr...
@Test public void testCreateSubscriptionUnmanagedTopicShouldFail() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> testManager.createSubscription( TopicName.of(PROJECT_ID, "topic-name"), "subscription-na...
@SuppressWarnings("unchecked") public static <T> T deep(final T input) { if (input instanceof Map<?, ?>) { return (T) deepMap((Map<?, ?>) input); } else if (input instanceof List<?>) { return (T) deepList((List<?>) input); } else if (input instanceof RubyString) { ...
@Test public void testRubyStringCloning() { String javaString = "fooBar"; RubyString original = RubyString.newString(RubyUtil.RUBY, javaString); RubyString result = Cloner.deep(original); // Check object identity assertNotSame(original, result); // Check string equal...
@Deprecated public IoFuture<ClientConnection> connect(final URI uri, final XnioWorker worker, ByteBufferPool bufferPool, OptionMap options) { return connect(uri, worker, null, bufferPool, options); }
@Test public void default_group_key_is_used_in_Http2Client_SSL() throws Exception{ final Http2Client client = createClient(); final ClientConnection connection = client.connect(new URI("https://localhost:7778"), worker, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.create(UndertowOptions.ENABL...
@Override public boolean eval(Object arg) { QueryableEntry entry = (QueryableEntry) arg; Data keyData = entry.getKeyData(); return (key == null || key.equals(keyData)) && predicate.apply((Map.Entry) arg); }
@Test public void testEval_givenFilterContainsKey_whenKeyOfEntryIsEqualAndPredicacteIsMatching_thenReturnTrue() { //given Data key1 = serializationService.toData("key1"); Predicate<Object, Object> predicate = Predicates.alwaysTrue(); QueryEventFilter filter = new QueryEventFilter(key...
public static @Nullable List<Map<String, Object>> getListOfMaps( Map<String, Object> map, String name, @Nullable List<Map<String, Object>> defaultValue) { @Nullable Object value = map.get(name); if (value == null) { if (map.containsKey(name)) { throw new IncorrectTypeException(name, map, "a ...
@Test public void testGetListOfMaps() throws Exception { Map<String, Object> o = makeCloudDictionary(); Assert.assertEquals(makeCloudObjects(), getListOfMaps(o, "multipleObjectsKey", null)); try { getListOfMaps(o, "singletonLongKey", null); Assert.fail("should have thrown an exception"); ...
public static NamenodeRole convert(NamenodeRoleProto role) { switch (role) { case NAMENODE: return NamenodeRole.NAMENODE; case BACKUP: return NamenodeRole.BACKUP; case CHECKPOINT: return NamenodeRole.CHECKPOINT; } return null; }
@Test public void testDataNodeInfoPBHelper() { DatanodeID id = DFSTestUtil.getLocalDatanodeID(); DatanodeInfo dnInfos0 = new DatanodeInfoBuilder().setNodeID(id) .build(); dnInfos0.setCapacity(3500L); dnInfos0.setDfsUsed(1000L); dnInfos0.setNonDfsUsed(2000L); dnInfos0.setRemaining(500L)...
void placeOrder(Order order) { sendShippingRequest(order); }
@Test void testPlaceOrderWithDatabaseAndExceptions() throws Exception { long paymentTime = timeLimits.paymentTime(); long queueTaskTime = timeLimits.queueTaskTime(); long messageTime = timeLimits.messageTime(); long employeeTime = timeLimits.employeeTime(); long queueTime = timeLimits....
public static CommonCertificateVerifier getVerifier(boolean isIndividual) { if (isIndividual) { if (individualVerifier == null) { individualVerifier = loadClass(System.getProperty("INDIVIDUAL_CERT_VERIFIER_CLASS_NAME")); } return individualVerifier; } ...
@Test public void testGetVerifierIsInstanceOfNullJuridicalCertificateVerifierOnInvalidEnvironment() throws Exception { Field singleton = CertificateVerifierHolder.class.getDeclaredField("individualVerifier"); singleton.setAccessible(true); singleton.set(null, null); CommonCertificate...
static List<Export> exportedPackages(File jarFile) { var manifest = getOsgiManifest(jarFile); if (manifest == null) return List.of(); try { return parseExports(manifest); } catch (Exception e) { throw new RuntimeException(String.format("Invalid manifest in bundle ...
@Test void require_that_invalid_exports_throws_exception() { try { AnalyzeBundle.exportedPackages(jarFile("errorExport.jar")); fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("Invalid manifest in bundle 'src/test/resources/jar/errorExport...
@ReadOperation public Map<String, Object> router(@Selector String dstService) { Map<String, Object> result = new HashMap<>(); if (StringUtils.hasText(dstService)) { List<RoutingProto.Route> routerRules = serviceRuleManager.getServiceRouterRule(MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE...
@Test public void testHasNotRouterRule() { List<RoutingProto.Route> routes = new LinkedList<>(); when(serviceRuleManager.getServiceRouterRule(anyString(), anyString(), anyString())).thenReturn(routes); Map<String, Object> actuator = polarisRouterEndpoint.router(testDestService); assertThat(actuator.get("rou...
public static <T> void forEachWithIndex(Iterable<T> iterable, ObjectIntProcedure<? super T> procedure) { FJIterate.forEachWithIndex(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
@Test public void testForEachWithIndexException() { assertThrows(RuntimeException.class, () -> FJIterate.forEachWithIndex( FJIterateTest.createIntegerList(5), new PassThruObjectIntProcedureFactory<>(EXCEPTION_OBJECT_INT_PROCEDURE), new PassThruCombiner<>()...
public static double parseDouble(final String str) { final double d = Double.parseDouble(str); if (Double.isInfinite(d) || Double.isNaN(d)) { throw new NumberFormatException("Invalid double value: " + str); } return d; }
@Test public void shouldThrowOnInfinity() { assertThrows(NumberFormatException.class, () -> SqlDoubles.parseDouble("Infinity")); assertThrows(NumberFormatException.class, () -> SqlDoubles.parseDouble("-Infinity")); }
abstract HttpTracing httpTracing(ApplicationContext ctx);
@Test void WebMvc25_httpTracing_byName() { ApplicationContext context = mock(ApplicationContext.class); when(context.containsBean("httpTracing")).thenReturn(true); when(context.getBean("httpTracing")).thenReturn(mock(HttpTracing.class)); new WebMvc25().httpTracing(context); verify(context).contain...
public static void main(String[] args) { var form = new RegisterWorkerForm(NAME, OCCUPATION, DATE_OF_BIRTH); form.submit(); }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { if (!joinKey.isForeignKey()) { ensureMatchingPartitionCounts(buildContext.getServiceContext().getTopicClient()); } final JoinerFactory joinerFactory = new JoinerFactory( buildContext, this, ...
@Test public void shouldHandleJoinIfTableHasNoKeyAndJoinFieldIsRowKey() { // Given: setupStream(left, leftSchemaKStream); setupTable(right, rightSchemaKTable); final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, true, left, right, empty(), "KAFKA"); // When: joinNode...
public static String getSignature(String methodName, Class<?>[] parameterTypes) { StringBuilder sb = new StringBuilder(methodName); sb.append('('); if (parameterTypes != null && parameterTypes.length > 0) { boolean first = true; for (Class<?> type : parameterTypes) { ...
@Test void testGetSignature() throws Exception { Method m = Foo2.class.getDeclaredMethod("hello", int[].class); assertThat(ReflectUtils.getSignature("greeting", m.getParameterTypes()), equalTo("greeting([I)")); }
@Override public ExecuteContext before(ExecuteContext context) { Object[] arguments = context.getArguments(); String application = DubboReflectUtils.getParameter(arguments[0], APPLICATION_KEY); // 保存接口与服务名之间的映射 DubboCache.INSTANCE.putApplication(DubboReflectUtils.getServiceInterface...
@Test public void testBefore() { Object[] arguments = new Object[1]; arguments[0] = APACHE_URL; ExecuteContext context = ExecuteContext.forMemberMethod(new Object(), null, arguments, null, null); interceptor.before(context); Assert.assertEquals(SERVICE_NAME, D...
public static DisplayData from(HasDisplayData component) { checkNotNull(component, "component argument cannot be null"); InternalBuilder builder = new InternalBuilder(); builder.include(Path.root(), component); return builder.build(); }
@Test public void testExceptionsNotWrappedRecursively() { final RuntimeException cause = new RuntimeException("oh noes!"); HasDisplayData component = new HasDisplayData() { @Override public void populateDisplayData(DisplayData.Builder builder) { builder.include( ...
public static PTransformMatcher classEqualTo(Class<? extends PTransform> clazz) { return new EqualClassPTransformMatcher(clazz); }
@Test public void classEqualToDoesNotMatchUnrelatedClass() { PTransformMatcher matcher = PTransformMatchers.classEqualTo(ParDo.SingleOutput.class); AppliedPTransform<?, ?, ?> application = getAppliedTransform(Window.<KV<String, Integer>>into(new GlobalWindows())); assertThat(matcher.matches(appli...
public StatusInfo getStatusInfo() { StatusInfo.Builder builder = StatusInfo.Builder.newBuilder(); // Add application level status int upReplicasCount = 0; StringBuilder upReplicas = new StringBuilder(); StringBuilder downReplicas = new StringBuilder(); StringBuilder repl...
@Test public void testGetStatusInfoUnsetHealth() { StatusUtil statusUtil = getStatusUtil(5, 3, -1); StatusInfo statusInfo = statusUtil.getStatusInfo(); try { statusInfo.isHealthy(); } catch (NullPointerException e) { // Expected that the healthy flag ...
@CanIgnoreReturnValue public final Ordered containsExactly() { return containsExactlyEntriesIn(ImmutableMap.of()); }
@Test public void containsExactlyExtraKeyAndWrongValue() { ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3); expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "march", 33); assertFailureKeys( "keys with wrong values", "for key", "e...
@Subscribe public synchronized void renew(final SchemaAddedEvent event) { contextManager.getMetaDataContextManager().getSchemaMetaDataManager().addSchema(event.getDatabaseName(), event.getSchemaName()); refreshShardingSphereStatisticsData(); }
@Test void assertRenewForSchemaDeleted() { when(contextManager.getMetaDataContexts().getMetaData().getDatabase("db").containsSchema("foo_schema")).thenReturn(true); subscriber.renew(new SchemaDeletedEvent("db", "foo_schema")); verify(contextManager.getMetaDataContexts().getMetaData().getData...
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void testEmptyLabelsAreIgnored() throws Exception { new JmxCollector( "\n---\nrules:\n- pattern: `^hadoop<service=DataNode, name=DataNodeActivity-ams-hdd001-50010><>replaceBlockOpMinTime:`\n name: foo\n labels:\n '': v\n l: ''" .re...
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testSkipBundlesGreaterThanTargetThroughputAfterSplit() { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); var ctx = getContext(); ctx.brokerConfiguration().setLoadBalancerBrokerLoadTargetStd(0.20); ...
@Override public MergedResult decorate(final QueryResult queryResult, final SQLStatementContext sqlStatementContext, final MaskRule rule) { return new MaskMergedResult(maskRule, selectStatementContext, new TransparentMergedResult(queryResult)); }
@Test void assertDecorateQueryResult() throws SQLException { QueryResult queryResult = mock(QueryResult.class); when(queryResult.next()).thenReturn(true); MaskDQLResultDecorator decorator = new MaskDQLResultDecorator(mock(MaskRule.class), mock(SelectStatementContext.class)); MergedRe...
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException { final List<MavenArtifact> result = new ArrayList<>(); try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); JsonParser ...
@Test public void shouldHandleNoMatches() throws IOException { // Given Dependency dependency = new Dependency(); dependency.setSha1sum("94a9ce681a42d0352b3ad22659f67835e560d108"); final HttpURLConnection urlConnection = mock(HttpURLConnection.class); final byte[] payload = (...
@Override public void increment() { increment(1l); }
@Test(expected = IllegalArgumentException.class) public void incrementByNegativeValue() { longCounter.increment(-100l); }
@VisibleForTesting public static List<SegmentZKMetadata> getCompletedSegments(Map<String, String> taskConfigs, List<SegmentZKMetadata> allSegments, long currentTimeInMillis) { List<SegmentZKMetadata> completedSegments = new ArrayList<>(); String bufferPeriod = taskConfigs.getOrDefault(UpsertCompactionTa...
@Test public void testGetCompletedSegments() { long currentTimeInMillis = System.currentTimeMillis(); Map<String, String> taskConfigs = new HashMap<>(); taskConfigs.put(UpsertCompactionTask.BUFFER_TIME_PERIOD_KEY, "1d"); SegmentZKMetadata metadata1 = new SegmentZKMetadata("testTable"); metadata1....
public static void debug(final Logger logger, final String format, final Supplier<Object> supplier) { if (logger.isDebugEnabled()) { logger.debug(format, supplier.get()); } }
@Test public void testNeverDebugWithFormat() { when(logger.isDebugEnabled()).thenReturn(false); LogUtils.debug(logger, "testDebug: {}", supplier); verify(supplier, never()).get(); }
@Override protected ExecuteContext doBefore(ExecuteContext context) { checkState(context, new Response<Map<String, List<String>>>(Collections.emptyMap(), null, null, null)); return context; }
@Test public void doBefore() throws NoSuchMethodException { final ExecuteContext context = interceptor.doBefore(buildContext()); Assert.assertFalse(context.isSkip()); registerConfig.setOpenMigration(true); registerConfig.setEnableSpringRegister(true); RegisterDynamicConfig.IN...
public static boolean or(boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } for (final boolean element : array) { if (element) { return true; } } return false; }
@Test public void orTest(){ assertTrue(BooleanUtil.or(true,false)); assertTrue(BooleanUtil.orOfWrap(true,false)); }
@Override public void loginFailure(HttpRequest request, AuthenticationException e) { checkRequest(request); requireNonNull(e, "AuthenticationException can't be null"); if (!LOGGER.isDebugEnabled()) { return; } Source source = e.getSource(); LOGGER.debug("login failure [cause|{}][method|{...
@Test public void login_failure_fails_with_NPE_if_request_is_null() { logTester.setLevel(Level.INFO); AuthenticationException exception = newBuilder().setSource(Source.sso()).build(); assertThatThrownBy(() -> underTest.loginFailure(null, exception)) .isInstanceOf(NullPointerException.class) ....
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) { if (unsigned) { return payload.getByteBuf().readUnsignedIntLE(); } return payload.getByteBuf().readIntLE(); }
@Test void assertRead() { when(payload.getByteBuf()).thenReturn(Unpooled.wrappedBuffer(new byte[]{1, 0, 0, 0, 1, 0, 0, 0})); assertThat(new MySQLInt4BinaryProtocolValue().read(payload, false), is(1)); assertThat(new MySQLInt4BinaryProtocolValue().read(payload, true), is(1L)); }
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getData(); switch (metric.getType().getValueType()) { case ...
@Test public void toMeasure_for_LEVEL_Metric_ignores_data() { MeasureDto measureDto = new MeasureDto().setAlertStatus(Level.ERROR.name()).setData(SOME_DATA); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThatThrownBy(() ->meas...
public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); }
@Test public void testValidateValueMismatchDate() { assertThrows(DataException.class, () -> ConnectSchema.validateValue(Date.SCHEMA, 1000L)); }