focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Mono<GetAccountIdentityResponse> getAccountIdentity(final GetAccountIdentityRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.account...
@Test void getAccountIdentity() { final UUID phoneNumberIdentifier = UUID.randomUUID(); final String e164 = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); final byte[] usernameHash = TestRandomUtil.nextBytes(32)...
public boolean contains(long value) { if (isEmpty()) { return false; } Sequence sequence = getHead(); while (sequence != null) { if (sequence.contains(value)) { return true; } sequence = sequence.getNext(); } ...
@Test public void testContains() { SequenceSet set = new SequenceSet(); set.add(new Sequence(0, 10)); set.add(new Sequence(21, 42)); set.add(new Sequence(47, 90)); set.add(new Sequence(142, 512)); assertTrue(set.contains(0)); assertTrue(set.contains(42)); ...
public static <T> Inner<T> fields(String... fields) { return fields(FieldAccessDescriptor.withFieldNames(fields)); }
@Test @Category(NeedsRunner.class) public void testDropNestedArrayField() { Schema expectedSchema = Schema.builder().addArrayField("field2", FieldType.STRING).build(); PCollection<Row> result = pipeline .apply( Create.of( nestedArray(simpleRow(1, ...
public String toString(Object object) { return toJson(object); }
@Test public void testLocal() { Map<String, Object> result = new HashMap<>(8); result.put("date1", new Date()); result.put("date2", LocalDate.now()); result.put("date3", LocalDateTime.now()); System.out.println(JsonKit.toString(result)); }
@Override public void trace(String msg) { logger.trace(msg); }
@Test void testTraceWithFormat() { jobRunrDashboardLogger.trace("trace with {}", "format"); verify(slfLogger).trace("trace with {}", "format"); }
@Override public int getCurrentVersion() { return 3; }
@Disabled @Test void writeCurrentVersionSnapshot() throws IOException { AvroSerializer<GenericRecord> serializer = new AvroSerializer<>(GenericRecord.class, Address.getClassSchema()); DataOutputSerializer out = new DataOutputSerializer(1024); TypeSerializerSnapshotSeria...
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { // Retrieve the message body as input stream InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, graph); // and covert that to XML Docume...
@Test public void testPartialPayloadMultiNodeXMLContentEncryption() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { from("direct:start") .marshal().xmlSecurity("//cheesesites/*/cheese", true, defaultKey.getEncoded()) ...
@Override public void shutdown() throws PulsarClientException { try { // We will throw the last thrown exception only, though logging all of them. Throwable throwable = null; if (lookup != null) { try { lookup.close(); }...
@Test public void testInitializeWithDNSServerAddresses() throws Exception { ClientConfigurationData conf = new ClientConfigurationData(); conf.setDnsServerAddresses(DefaultDnsServerAddressStreamProvider.defaultAddressList()); conf.setServiceUrl("pulsar://localhost:6650"); initializeE...
public Object getCell(final int columnIndex) { Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.length + 1); return data[columnIndex - 1]; }
@Test void assertGetCellWithNegativeColumnIndex() { assertThrows(IllegalArgumentException.class, () -> memoryResultSetRow.getCell(-1)); }
@Override protected void handlePartitionMetadataRequest(CommandPartitionedTopicMetadata partitionMetadata) { checkArgument(state == State.Connected); final long requestId = partitionMetadata.getRequestId(); if (log.isDebugEnabled()) { log.debug("[{}] Received PartitionMetadataLoo...
@Test(expectedExceptions = IllegalArgumentException.class) public void shouldFailHandlePartitionMetadataRequest() throws Exception { ServerCnx serverCnx = mock(ServerCnx.class, CALLS_REAL_METHODS); Field stateUpdater = ServerCnx.class.getDeclaredField("state"); stateUpdater.setAccessible(tru...
public static String cvssV2ScoreToSeverity(Double score) { if (score != null) { if (ZERO.compareTo(score) <= 0 && FOUR.compareTo(score) > 0) { return LOW; } else if (FOUR.compareTo(score) <= 0 && SEVEN.compareTo(score) > 0) { return MEDIUM; } e...
@Test public void testCvssV2ScoreToSeverity() { Double score = -1.0; String expResult = "UNKNOWN"; String result = CvssUtil.cvssV2ScoreToSeverity(score); assertEquals(expResult, result); score = 0.0; expResult = "LOW"; result = CvssUtil.cvssV2ScoreToSeverity(...
public static String encode(CharSequence input) throws UtilException { return encode(input, false); }
@Test public void encodeDecodeTest2(){ // 无需编码和解码 final String text = "Hutool"; final String strPunyCode = PunyCode.encode(text); assertEquals("Hutool", strPunyCode); }
@Override public Map<TopicPartition, Long> changelogOffsets() { return Collections.unmodifiableMap(stateMgr.changelogOffsets()); }
@Test public void shouldReturnStateManagerChangelogOffsets() { when(stateManager.changelogOffsets()).thenReturn(Collections.singletonMap(partition, 50L)); task = createStandbyTask(); assertEquals(Collections.singletonMap(partition, 50L), task.changelogOffsets()); }
public static <T> Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress) { return DiffUtils.diff(original, revised, DEFAULT_DIFF.create(), progress); }
@Test public void testDiff_Delete() { final Patch<String> patch = DiffUtils.diff(Arrays.asList("ddd", "fff", "ggg"), Arrays. asList("ggg")); assertNotNull(patch); assertEquals(1, patch.getDeltas().size()); final AbstractDelta<String> delta = patch.getDeltas().get(0); ...
public static TimestampExtractionPolicy create( final KsqlConfig ksqlConfig, final LogicalSchema schema, final Optional<TimestampColumn> timestampColumn ) { if (!timestampColumn.isPresent()) { return new MetadataTimestampExtractionPolicy(getDefaultTimestampExtractor(ksqlConfig)); } ...
@Test public void shouldThrowIfTimestampTypeAndFormatIsSupplied() { // Given: final String timestamp = "timestamp"; final LogicalSchema schema = schemaBuilder2 .valueColumn(ColumnName.of(timestamp.toUpperCase()), SqlTypes.TIMESTAMP) .build(); // When: assertThrows( KsqlExc...
@Override public long memoryAddress() { if (hasMemoryAddress()) { return EMPTY_BYTE_BUFFER_ADDRESS; } else { throw new UnsupportedOperationException(); } }
@Test public void testMemoryAddress() { EmptyByteBuf empty = new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT); if (empty.hasMemoryAddress()) { assertThat(empty.memoryAddress(), is(not(0L))); } else { try { empty.memoryAddress(); fail(...
public CompactOperator( SupplierWithException<FileSystem, IOException> fsFactory, CompactReader.Factory<T> readerFactory, CompactWriter.Factory<T> writerFactory) { this.fsFactory = fsFactory; this.readerFactory = readerFactory; this.writerFactory = writerFacto...
@Test void testCompactOperator() throws Exception { AtomicReference<OperatorSubtaskState> state = new AtomicReference<>(); Path f0 = newFile(".uncompacted-f0", 3); Path f1 = newFile(".uncompacted-f1", 2); Path f2 = newFile(".uncompacted-f2", 2); Path f3 = newFile(".uncompacte...
@Override public void check(final SQLStatementContext sqlStatementContext, final List<Object> params, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database) { if (sqlStatementContext.getSqlStatement() instanceof DMLStatement) { ShardingRule rule = database.getRuleMetaData(...
@Test void assertNotDMLStatementCheck() { when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DDLStatement.class)); shardingAuditAlgorithm.check(sqlStatementContext, Collections.emptyList(), mock(RuleMetaData.class), database); verify(database, times(0)).getRuleMetaData(); }
@ApiOperation(value = "Save or update entity view (saveEntityView)", notes = ENTITY_VIEW_DESCRIPTION + MODEL_DESCRIPTION + "Remove 'id', 'tenantId' and optionally 'customerId' from the request body example (below) to create new Entity View entity." + TENANT_OR_CUSTOME...
@Test public void testSaveEntityView() throws Exception { String name = "Test entity view"; Mockito.reset(tbClusterService, auditLogService); EntityView savedView = getNewSavedEntityView(name); Assert.assertNotNull(savedView); Assert.assertNotNull(savedView.getId()); ...
public static void checkAtLeastOneChar(final Properties props, final String propKey, final MaskAlgorithm<?, ?> algorithm) { checkRequired(props, propKey, algorithm); ShardingSpherePreconditions.checkNotEmpty(props.getProperty(propKey), () -> new AlgorithmInitializationException(algorithm, "%s's length m...
@Test void assertCheckAtLeastOneCharSuccess() { Properties props = PropertiesBuilder.build(new Property("key", "1")); assertDoesNotThrow(() -> MaskAlgorithmPropertiesChecker.checkAtLeastOneChar(props, "key", mock(MaskAlgorithm.class))); }
@Nonnull @Override public CreatedAggregations<AggregationBuilder> doCreateAggregation(Direction direction, String name, Pivot pivot, Time timeSpec, OSGeneratedQueryContext queryContext, Query query) { AggregationBuilder root = null; AggregationBuilder leaf = null; final Interval interval...
@Test public void timeSpecIntervalIsCalculatedOnPivotTimerangeIfOverridden() throws InvalidRangeParametersException { final ArgumentCaptor<TimeRange> timeRangeCaptor = ArgumentCaptor.forClass(TimeRange.class); when(interval.toDateInterval(timeRangeCaptor.capture())).thenReturn(DateInterval.days(1));...
public String getFingerprint() { try { return Base64.getEncoder().encodeToString(DigestUtils.sha256(Objects.requireNonNull(getX509Certificate()).getEncoded())); } catch (CertificateEncodingException e) { return null; } }
@Test void getFingerprints() { assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", getSslCertificateDigiDDomain().getFingerprint()); assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", getSslCertificateEidDomain().getFingerprint()); }
@Override protected void prepare(MessageTuple item) { channel.write(item.originMessage, item.channelPromise); }
@Test public void testPrepare() { Object message = new Object(); NettyBatchWriteQueue.MessageTuple messageTuple = new NettyBatchWriteQueue.MessageTuple(message, mockChannelPromise); nettyBatchWriteQueue.prepare(messageTuple); Mockito.verify(mockChannel).write(eq(message)...
@Override public ScheduleResult schedule() { List<RemoteTask> newTasks = IntStream.range(0, partitionToNode.size()) .mapToObj(partition -> taskScheduler.scheduleTask(partitionToNode.get(partition), partition)) .filter(Optional::isPresent) .map(Optional::ge...
@Test public void testSingleNode() { FixedCountScheduler nodeScheduler = new FixedCountScheduler( (node, partition) -> Optional.of(taskFactory.createTableScanTask( new TaskId("test", 1, 0, 1, 0), node, ImmutableList.of(), ...
@Override public ByteBuffer getHashValue(Type type) { ByteBuffer buffer; // no need to consider the overflow when cast decimal to other type, because this func only be used when querying, not storing. // e.g. For column A with type INT, the data stored certainly no overflow. switch (...
@Test public void testGetHashValueOfDecimal128p27s9() throws AnalysisException { String[] testCases = new String[] { "0.0", Strings.repeat("9", 18) + "." + Strings.repeat("9", 9), "+" + Strings.repeat("9", 18) + "." + Strings.repeat("9", 9), "0...
@Override public boolean nextConfig(long timeout) { file.validateFile(); if (checkReloaded()) { log.log(FINE, () -> "User forced config reload at " + System.currentTimeMillis()); // User forced reload setConfigIfChanged(updateConfig()); ConfigState<T> ...
@Test public void require_that_new_config_is_detected_on_reload() throws IOException { writeConfig("intval", "23"); ConfigSubscription<SimpletypesConfig> sub = new FileConfigSubscription<>( new ConfigKey<>(SimpletypesConfig.class, ""), new FileSource(TEST_TYPES_FILE))...
@Override public String getString(int rowIndex, int columnIndex) { JsonNode jsonValue = _resultsArray.get(rowIndex).get(columnIndex); if (jsonValue.isTextual()) { return jsonValue.textValue(); } else { return jsonValue.toString(); } }
@Test public void testGetString() { // Run the test final String result = _selectionResultSetUnderTest.getString(0, 0); // Verify the results assertEquals("r1c1", result); }
@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 shouldThrowIfRangeScanAndKeysEmpty() { // Given: getEmtpyMetadata(); // When: final Exception e = assertThrows( IllegalStateException.class, () -> locator.locate(Collections.emptyList(), routingOptions, routingFilterFactoryActive, true) ); // Then: assertTha...
@Override public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) { Map<String, List<TopicPartition>> assignment = new HashMap(); Iterator subIter = subscriptions.keySet().iterator(); //initialize subscription mapping...
@Test public void assignmentWorksWithMultipleConsumers() { String topic = "testTopic"; List<String> topicList = new ArrayList<String>(); topicList.add(topic); String consumerId1 = "testConsumer1"; String consumerId2 = "testConsumer2"; Map<String, Integer> partitionsPe...
public void validate(ProjectReactor reactor) { List<String> validationMessages = new ArrayList<>(); for (ProjectDefinition moduleDef : reactor.getProjects()) { validateModule(moduleDef, validationMessages); } if (isBranchFeatureAvailable()) { branchParamsValidator.validate(validationMessag...
@Test void fail_when_pull_request_base_specified_but_branch_plugin_not_present() { ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo"); ProjectReactor reactor = new ProjectReactor(def); when(settings.get(ScannerProperties.PULL_REQUEST_BASE)).thenRetu...
@Override public boolean checkIndexExists( Database database, String schemaName, String tableName, String[] idxFields ) throws KettleDatabaseException { String tablename = database.getDatabaseMeta().getQuotedSchemaTableCombination( schemaName, tableName ); boolean[] exists = new boolean[ idxFields.length]; ...
@Test public void testCheckIndexExists() throws Exception { Database db = Mockito.mock( Database.class ); ResultSet rs = Mockito.mock( ResultSet.class ); DatabaseMetaData dmd = Mockito.mock( DatabaseMetaData.class ); DatabaseMeta dm = Mockito.mock( DatabaseMeta.class ); Mockito.when( dm.getQuoted...
@Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (UrlUtils.isRegistry(url)) { return protocol.refer(type, url); } Invoker<T> invoker = protocol.refer(type, url); if (StringUtils.isEmpty(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY))) {...
@Test void testLoadingListenerForRemoteReference() { // verify that no listener is loaded by default URL urlWithoutListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()); AbstractInvoker<DemoService> invokerWith...
public void addCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener) { addCoinsReceivedEventListener(Threading.USER_THREAD, listener); }
@Test public void exceptionsDoNotBlockAllListeners() { // Check that if a wallet listener throws an exception, the others still run. wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> { log.info("onCoinsReceived 1"); throw new RuntimeException("barf...
@Override public void write(int b) throws IOException { filePosition++; super.write(b); }
@Test public void testWriteByte() throws IOException { byte[] arr = new byte[257]; for (int i=0; i<256; i++) { arr[i] = (byte)i; writer.write(i); } arr[256] = (byte)0x80; writer.write(0x180); expectData(arr); }
@Override public Long createConfig(ConfigSaveReqVO createReqVO) { // 校验参数配置 key 的唯一性 validateConfigKeyUnique(null, createReqVO.getKey()); // 插入参数配置 ConfigDO config = ConfigConvert.INSTANCE.convert(createReqVO); config.setType(ConfigTypeEnum.CUSTOM.getType()); configM...
@Test public void testCreateConfig_success() { // 准备参数 ConfigSaveReqVO reqVO = randomPojo(ConfigSaveReqVO.class) .setId(null); // 防止 id 被赋值,导致唯一性校验失败 // 调用 Long configId = configService.createConfig(reqVO); // 断言 assertNotNull(configId); // 校验...
public static String humanReadableBytes(Locale locale, long bytes) { int unit = 1024; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = String.valueOf("KMGTPE".charAt(exp - 1)); return String.format(loc...
@Test public void testHumanReadableBytes() { assertEquals("0 B", StringHelper.humanReadableBytes(Locale.ENGLISH, 0)); assertEquals("32 B", StringHelper.humanReadableBytes(Locale.ENGLISH, 32)); assertEquals("1.0 KB", StringHelper.humanReadableBytes(Locale.ENGLISH, 1024)); assertEquals...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final String prefix = containerService.isContainer(directory) ? StringUtils.EMPTY : containerService.getKey(directory) + Path.DELIMITER; return this.list(directory, list...
@Test(expected = NotfoundException.class) public void testListNotfoundContainer() throws Exception { final Path container = new Path("notfound.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); new SwiftObjectListService(session).list(container, new DisabledListProgressListener()); ...
@Override protected void respondAsLeader( ChannelHandlerContext ctx, RoutedRequest routedRequest, T gateway) { HttpRequest httpRequest = routedRequest.getRequest(); if (log.isTraceEnabled()) { log.trace("Received request " + httpRequest.uri() + '.'); } FileUp...
@Test void testFileCleanup(@TempDir File temporaryFolder) throws Exception { final Path dir = temporaryFolder.toPath(); final Path file = dir.resolve("file"); Files.createFile(file); RestfulGateway mockRestfulGateway = new TestingRestfulGateway.Builder().build(); final Gate...
@Override public ExecuteContext after(ExecuteContext context) { DefaultLitePullConsumerWrapper wrapper = RocketMqPullConsumerController .getPullConsumerWrapper((DefaultLitePullConsumer) context.getObject()); if (wrapper == null) { PullConsumerLocalInfoUtils.setSubscriptio...
@Test public void testAfter() { // Wrapper is null interceptor.after(context); Assert.assertEquals(PullConsumerLocalInfoUtils.getSubscriptionType().name(), "SUBSCRIBE"); PullConsumerLocalInfoUtils.removeSubscriptionType(); // Wrapper is not null pullConsumerWrapper.s...
public static Map<String, String> parseParameters(URI uri) throws URISyntaxException { if (!isCompositeURI(uri)) { return uri.getQuery() == null ? emptyMap() : parseQuery(stripPrefix(uri.getQuery(), "?")); } else { CompositeData data = URISupport.parseComposite(uri); ...
@Test public void testParsingParams() throws Exception { URI uri = new URI("static:(http://localhost:61617?proxyHost=jo&proxyPort=90)?proxyHost=localhost&proxyPort=80"); Map<String,String>parameters = URISupport.parseParameters(uri); verifyParams(parameters); uri = new URI("static://...
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) { AnalyzerContext context = new AnalyzerContext(); int treeSize = aggregatePredicateStatistics(predicate, false, context); int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.h...
@Test void require_that_featureconjunctions_count_as_leaf_in_subtree_calculation() { Predicate p = and( and( feature("grault").inRange(0, 10), feature("waldo").inRange(0, 10)), con...
@Override public String grantAuthorizationCodeForCode(Long userId, Integer userType, String clientId, List<String> scopes, String redirectUri, String state) { return oauth2CodeService.createAuthorizationCode(user...
@Test public void testGrantAuthorizationCodeForCode() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); String clientId = randomString(); List<String> scopes = Lists.newArrayList("read", "write"); String redirectUr...
public static <T> Serde<Windowed<T>> sessionWindowedSerdeFrom(final Class<T> type) { return new SessionWindowedSerde<>(Serdes.serdeFrom(type)); }
@Test public void testSessionWindowedSerdeFrom() { final Windowed<Integer> sessionWindowed = new Windowed<>(10, new SessionWindow(0, 1)); final Serde<Windowed<Integer>> sessionWindowedSerde = WindowedSerdes.sessionWindowedSerdeFrom(Integer.class); final byte[] bytes = sessionWindowedSerde.se...
public static Message parseMessage(XmlPullParser parser) throws XmlPullParserException, IOException, SmackParsingException { return parseMessage(parser, XmlEnvironment.EMPTY); }
@Test public void invalidMessageBodyContainingTagTest() throws Exception { String control = XMLBuilder.create("message") .namespace(StreamOpen.CLIENT_NAMESPACE) .a("from", "romeo@montague.lit/orchard") .a("to", "juliet@capulet.lit/balcony") .a("id", "zid615d9"...
public static void setMaskedSqlIfNeeded(final KsqlRequest request) { try { request.getMaskedKsql(); } catch (final Exception e) { ApiServerUtils.setMaskedSql(request); } }
@Test public void shouldMaskKsqlRequestQuery() throws ExecutionException, InterruptedException { // Given final String query = "--this is a comment. \n" + "CREATE SOURCE CONNECTOR `test-connector` WITH (" + " \"connector.class\" = 'PostgresSource', \n" + " 'connection.url' = 'jdb...
@Override public long getPos() throws IOException { // The starting position is not determined until a physical file has been assigned, so // we return the relative value to the starting position in this method return bufferPos + curPosRelative; }
@Test public void testGetPos() throws Exception { FileMergingCheckpointStateOutputStream stream = getNewStream(); // write one byte one time for (int i = 0; i < 64; ++i) { assertThat(stream.getPos()).isEqualTo(i); stream.write(0x42); } stream.closeAn...
public static void addSystemTopic(String systemTopic) { SYSTEM_TOPIC_SET.add(systemTopic); }
@Test public void testAddSystemTopic() { String topic = "SYSTEM_TOPIC_TEST"; TopicValidator.addSystemTopic(topic); assertThat(TopicValidator.getSystemTopicSet()).contains(topic); }
@Override public GetContainerReportResponse getContainerReport( GetContainerReportRequest request) throws YarnException, IOException { ContainerId containerId = request.getContainerId(); if (containerId == null) { throw new ContainerNotFoundException("Invalid container id: null"); } Applic...
@Test public void testGetContainerReport() throws YarnException, IOException { ClientRMService rmService = createRMService(); GetContainerReportRequest request = recordFactory .newRecordInstance(GetContainerReportRequest.class); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance( ...
public void poolingRowChange( int idx ) { if ( idx != -1 ) { if ( idx >= BaseDatabaseMeta.poolingParameters.length ) { idx = BaseDatabaseMeta.poolingParameters.length - 1; } if ( idx < 0 ) { idx = 0; } poolingDescription.setValue( BaseDatabaseMeta.poolingParameters[ i...
@Test public void testPoolingRowChange() throws Exception { }
public void handleWatchTopicList(NamespaceName namespaceName, long watcherId, long requestId, Pattern topicsPattern, String topicsHash, Semaphore lookupSemaphore) { if (!enableSubscriptionPatternEvaluation || topicsPattern.pattern().length() > maxSubscriptionPatternLength) ...
@Test public void testCommandWatchSuccessResponse() { topicListService.handleWatchTopicList( NamespaceName.get("tenant/ns"), 13, 7, Pattern.compile("persistent://tenant/ns/topic\\d"), null, lookupSemaphore); ...
@Override public InetSocketAddress resolve(ServerWebExchange exchange) { List<String> xForwardedValues = extractXForwardedValues(exchange); if (!xForwardedValues.isEmpty()) { int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex); return new InetSocketAddress(xForwardedValues.get(index), 0); } ...
@Test public void trustAllReturnsFirstForwardedIp() { ServerWebExchange exchange = buildExchange(oneTwoThreeBuilder()); InetSocketAddress address = trustAll.resolve(exchange); assertThat(address.getHostName()).isEqualTo("0.0.0.1"); }
@Override public boolean dropTable(TableIdentifier identifier, boolean purge) { if (!isValidIdentifier(identifier)) { return false; } String database = identifier.namespace().level(0); TableOperations ops = newTableOps(identifier); TableMetadata lastMetadata = null; if (purge) { ...
@Test public void testSetCurrentSchema() throws Exception { Schema schema = getTestSchema(); TableIdentifier tableIdent = TableIdentifier.of(DB_NAME, "tbl"); try { Table table = catalog.buildTable(tableIdent, schema).create(); assertThat(hmsTableParameters()) .containsEntry(CURRENT...
public String send() throws MailException { try { return doSend(); } catch (MessagingException e) { if (e instanceof SendFailedException) { // 当地址无效时,显示更加详细的无效地址信息 final Address[] invalidAddresses = ((SendFailedException) e).getInvalidAddresses(); final String msg = StrUtil.format("Invalid Address...
@Test @Disabled public void sendWithLongNameFileTest() { //附件名长度大于60时的测试 JakartaMailUtil.send("hutool@foxmail.com", "测试", "<h1>邮件来自Hutool测试</h1>", true, FileUtil.file("d:/6-LongLong一阶段平台建设周报2018.3.12-3.16.xlsx")); }
@Override @CacheEvict(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#id") public void deleteMailAccount(Long id) { // 校验是否存在账号 validateMailAccountExists(id); // 校验是否存在关联模版 if (mailTemplateService.getMailTemplateCountByAccountId(id) > 0) { throw exception(MAIL_ACCOUNT...
@Test public void testDeleteMailAccount_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> mailAccountService.deleteMailAccount(id), MAIL_ACCOUNT_NOT_EXISTS); }
@Override public ConfigInfoStateWrapper findConfigInfoState(final String dataId, final String group, final String tenant) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; try { return this.jt.queryForObject( "SELECT id,data_id,group_id,te...
@Test void testFindConfigInfoState() { String dataId = "dataId1324"; String group = "group23546"; String tenant = "tenant13245"; //mock select config state ConfigInfoStateWrapper mockedConfig = new ConfigInfoStateWrapper(); mockedConfig.setLastModifi...
@Override public byte readByte() { checkReadableBytes0(1); int i = readerIndex; byte b = _getByte(i); readerIndex = i + 1; return b; }
@Test public void testReadByteAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().readByte(); } }); }
public static boolean isPlainHttp(NetworkService networkService) { checkNotNull(networkService); var isWebService = isWebService(networkService); var isKnownServiceName = IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey( Ascii.toLowerCase(networkService.getServiceName())); var doesNotSup...
@Test public void isPlainHttp_whenRadanHttpService_returnsTrue() { assertThat( NetworkServiceUtils.isPlainHttp( NetworkService.newBuilder().setServiceName("radan-http").build())) .isTrue(); }
public T getRecordingProxy() { return _templateProxy; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testSimpleSetRemoveOptionalIfNullOnRequiredFieldFail() { makeOne().getRecordingProxy().setFooRequired(null, SetMode.REMOVE_OPTIONAL_IF_NULL); }
@Operation(summary = "release", description = "RELEASE_PROCESS_DEFINITION_NOTES") @Parameters({ @Parameter(name = "name", description = "PROCESS_DEFINITION_NAME", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "code", description = "PROCESS_DEFINITION_CO...
@Test public void testReleaseProcessDefinition() { long projectCode = 1L; long id = 1L; Map<String, Object> result = new HashMap<>(); putMsg(result, Status.SUCCESS); Mockito.doNothing().when(processDefinitionService) .offlineWorkflowDefinition(user, projectCo...
public String getAuthUuid() { if (Qualifiers.SUBVIEW.equals(qualifier)) { return authUuid; } return uuid; }
@Test void getAuthUuid_whenEntityIsSubportfolio_shouldReturnAuthUuid() { PortfolioDto portfolioDto = new PortfolioDto(); portfolioDto.qualifier = Qualifiers.SUBVIEW; portfolioDto.authUuid = "authUuid"; portfolioDto.setUuid("uuid"); String authUuid = portfolioDto.getAuthUuid(); assertThat(aut...
@Nonnull public static <T extends GeneratedMessageV3> ProtobufSerializer<T> from(@Nonnull Class<T> clazz, int typeId) { return new ProtobufSerializer<>(clazz, typeId) { }; }
@Test public void when_serializes_then_isAbleToDeserialize() { // Given Person original = Person.newBuilder().setName("Joe").setAge(18).build(); StreamSerializer<Person> serializer = ProtobufSerializer.from(Person.class, 1); // When Person transformed = deserialize(serialize...
@SuppressWarnings("unchecked") public static <T> T[] tail(final T[] elements) { checkNotNull(elements); if (elements.length <= 1) { return (T[]) Array.newInstance(elements.getClass().getComponentType(), 0); } return Arrays.copyOfRange(elements, 1, elements.length); ...
@Test public void should_get_tail() { assertThat(Iterables.tail(new Integer[]{1, 2}), is(new Integer[] {2})); assertThat(Iterables.tail(new Integer[1]), is(new Integer[0])); assertThat(Iterables.tail(new Integer[0]), is(new Integer[0])); assertThrows(NullPointerException.class, () ->...
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat( String groupId, String memberId, int memberEpoch, String instanceId, String rackId, int rebalanceTimeoutMs, String clientId, String clientHost, ...
@Test public void testUpdatingSubscriptionTriggersNewTargetAssignment() { String groupId = "fooup"; // Use a static member id as it makes the test easier. String memberId = Uuid.randomUuid().toString(); Uuid fooTopicId = Uuid.randomUuid(); String fooTopicName = "foo"; ...
@Override public String getProperty(String key) { String answer = super.getProperty(key); if (answer == null) { answer = super.getProperty(StringHelper.dashToCamelCase(key)); } if (answer == null) { answer = super.getProperty(StringHelper.camelCaseToDash(key))...
@Test public void testOrdered() { Properties prop = new CamelCaseOrderedProperties(); prop.setProperty("hello-world", "Hi Camel"); prop.setProperty("camel.main.stream-caching-enabled", "true"); assertEquals(2, prop.size()); Iterator it = prop.keySet().iterator(); as...
public boolean statsHaveChanged() { if (!aggregatedStats.hasUpdatesFromAllDistributors()) { return false; } for (ContentNodeStats contentNodeStats : aggregatedStats.getStats()) { int nodeIndex = contentNodeStats.getNodeIndex(); boolean currValue = mayHaveMerge...
@Test void stats_have_not_changed_if_no_nodes_have_changed_state() { Fixture f = Fixture.fromStats(stats().bucketsPending(0).bucketsPending(1)); f.newAggregatedStats(stats().bucketsPending(0).bucketsPending(1)); assertFalse(f.statsHaveChanged()); }
@Override public Map<String, String> getDefaultOptions() { Map<String, String> defaultOptions = new HashMap<>(); defaultOptions.put( getPluginId() + ".defaultFetchSize", "500" ); defaultOptions.put( getPluginId() + ".useCursorFetch", "true" ); return defaultOptions; }
@Test public void testGetDefaultOptions() { MySQLDatabaseMeta mySQLDatabaseMeta = new MySQLDatabaseMeta(); mySQLDatabaseMeta.setPluginId( "foobar" ); Map<String, String> map =mySQLDatabaseMeta.getDefaultOptions(); assertNotNull( map ); assertEquals( 2, map.size() ); for ( String key : map.keyS...
public static int sizeOfUnsignedVarint(int value) { // Protocol buffers varint encoding is variable length, with a minimum of 1 byte // (for zero). The values themselves are not important. What's important here is // any leading zero bits are dropped from output. We can use this leading zero ...
@Test public void testSizeOfUnsignedVarint() { // The old well-known implementation for sizeOfUnsignedVarint IntFunction<Integer> simpleImplementation = (int value) -> { int bytes = 1; while ((value & 0xffffff80) != 0L) { bytes += 1; value >>>=...
@Override public void onMetadataUpdate( MetadataDelta delta, MetadataImage newImage, LoaderManifest manifest ) { switch (manifest.type()) { case LOG_DELTA: try { publishDelta(delta); } catch (Throwable e) { ...
@Test public void testLoadSnapshot() { try (TestEnv env = new TestEnv()) { MetadataDelta delta = new MetadataDelta(MetadataImage.EMPTY); ImageReWriter writer = new ImageReWriter(delta); IMAGE1.write(writer, new ImageWriterOptions.Builder(). setMetadata...
@Override public Status unwrap() { return status; }
@Test void unwrap() { assertThat(response.unwrap()).isSameAs(status); }
@Override public Result invoke(Invocation invocation) throws RpcException { Result result; String value = getUrl().getMethodParameter( RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()) .trim(); if (ConfigUtils.isEmpty(value)) { ...
@SuppressWarnings("unchecked") @Test void testMockInvokerFromOverride_Invoke_check_ListString() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService...
@Override public byte[] serialize() { byte[] optionsData = null; if (this.options.hasOptions()) { optionsData = this.options.serialize(); } int optionsLength = 0; if (optionsData != null) { optionsLength = optionsData.length; } final ...
@Test public void testSerialize() { RouterAdvertisement ra = new RouterAdvertisement(); ra.setCurrentHopLimit((byte) 3); ra.setMFlag((byte) 1); ra.setOFlag((byte) 1); ra.setRouterLifetime((short) 0x258); ra.setReachableTime(0x3e8); ra.setRetransmitTimer(0x1f4)...
public static Read<String> readStrings() { return Read.newBuilder( (PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8)) .setCoder(StringUtf8Coder.of()) .build(); }
@Test public void testFailedParseWithDeadLetterConfigured() { ByteString data = ByteString.copyFrom("Hello, World!".getBytes(StandardCharsets.UTF_8)); RuntimeException exception = new RuntimeException("Some error message"); ImmutableList<IncomingMessage> expectedReads = ImmutableList.of( ...
void handleJobLevelCheckpointException( CheckpointProperties checkpointProperties, CheckpointException exception, long checkpointId) { if (!checkpointProperties.isSavepoint()) { checkFailureAgainstCounter(exception, checkpointId, failureCallback::failJob); ...
@Test void testIgnoreOneCheckpointRepeatedlyCountMultiTimes() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(2, callback); CheckpointProperties checkpointProperties = forCheckpoint(NEVER_RETAIN_AFTER_TERMINAT...
public static Builder builder(final SqlStruct schema) { return new Builder(schema); }
@Test public void shouldThrowOnSettingNegativeFieldIndex() { // When: final DataException e = assertThrows( DataException.class, () -> KsqlStruct.builder(SCHEMA) .set(-1, Optional.empty()) ); // Then: assertThat(e.getMessage(), containsString("Invalid field index: -1")...
@Override public Hedge hedge(final String name) { return hedge(name, getDefaultConfig(), emptyMap()); }
@Test public void hedgeNewWithNullNameAndNonDefaultConfig() { exception.expect(NullPointerException.class); exception.expectMessage(NAME_MUST_NOT_BE_NULL); HedgeRegistry registry = HedgeRegistry.builder().withDefaultConfig(config).build(); registry.hedge(null, config); }
@Override public PurgeCurrentExecutionFiles.Output run(RunContext runContext) throws Exception { return Output.builder() .uris(runContext.storage().deleteExecutionFiles()) .build(); }
@Test void run() throws Exception { // create a file var flow = Flow.builder() .namespace("namespace") .id("flowId") .build(); var runContext = runContextFactory.of(flow, Map.of( "execution", Map.of("id", "executionId"), "task", Ma...
@Override public Client getClient(String clientId) { return getClientManagerById(clientId).getClient(clientId); }
@Test void testChooseConnectionClient() { delegate.getClient(connectionId); verify(connectionBasedClientManager).getClient(connectionId); verify(ephemeralIpPortClientManager, never()).getClient(connectionId); verify(persistentIpPortClientManager, never()).getClient(connectionId); ...
Map<HoodieFileGroupId, List<Integer>> getFileGroupToPartitions() { return fileGroupToPartitions; }
@Test public void testAssignmentCorrectness() { HoodieFileGroupId fg1 = new HoodieFileGroupId("p1", "f1"); HoodieFileGroupId fg2 = new HoodieFileGroupId("p1", "f2"); HoodieFileGroupId fg3 = new HoodieFileGroupId("p1", "f3"); Map<HoodieFileGroupId, Long> fileToComparisons = new HashMap<HoodieFileGroup...
@Override public double calcMinWeightPerDistance() { return 1d / (maxSpeedCalc.calcMax() / SPEED_CONV) / maxPrioCalc.calcMax() + distanceInfluence; }
@Test public void testMaxPriority() { double maxSpeed = 155; assertEquals(maxSpeed, avSpeedEnc.getMaxOrMaxStorableDecimal(), 0.1); assertEquals(1d / maxSpeed / 0.5 * 3.6, createWeighting(createSpeedCustomModel(avSpeedEnc). addToPriority(If("true", MULTIPLY, "0.5"))).calcMinWe...
@Override public long footprint() { return footprint; }
@Test public void testFootprint() { MerkleTree merkleTree1 = new ArrayMerkleTree(3); MerkleTree merkleTree2 = new ArrayMerkleTree(3); for (int i = 0; i < 10; i++) { merkleTree1.updateAdd(i, i); } for (int i = 0; i < 100; i++) { merkleTree2.updateAdd(...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testPersonalBestNoTrailingPeriod() { final String FIGHT_DURATION = "Fight duration: <col=ff0000>0:59</col>. Personal best: 0:55"; final String FIGHT_DURATION_PRECISE = "Fight duration: <col=ff0000>0:59.20</col>. Personal best: 0:55.40"; // This sets lastBoss ChatMessage chatMessage = new Ch...
public static String serializeAwsCredentialsProvider(AwsCredentialsProvider credentialsProvider) { return serialize(credentialsProvider); }
@Test(expected = IllegalArgumentException.class) public void testFailOnAwsCredentialsProviderSerialization() { AwsCredentialsProvider awsCredentialsProvider = new UnknownAwsCredentialsProvider(); AwsSerializableUtils.serializeAwsCredentialsProvider(awsCredentialsProvider); }
@OnlyForTest protected static ThreadPoolExecutor getExecutor(String groupId) { return GROUP_THREAD_POOLS.getOrDefault(groupId, GlobalThreadPoolHolder.INSTANCE); }
@Test public void testInvalidGroup() { ThreadPoolExecutor executor1 = ThreadPoolsFactory.getExecutor(GROUP_ID_001); ThreadPoolExecutor executor = ThreadPoolsFactory.getExecutor("test"); Assert.assertEquals(executor1, executor); }
public void withLock(final List<String> e164s, final Runnable task, final Executor lockAcquisitionExecutor) { if (e164s.isEmpty()) { throw new IllegalArgumentException("List of e164s to lock must not be empty"); } final List<LockItem> lockItems = new ArrayList<>(e164s.size()); try { // Off...
@Test void withLockEmptyList() { final Runnable task = mock(Runnable.class); assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptyList(), () -> {}, executor)); verify(task, never()).run(); }
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) { if ( from == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));...
@Test void invokeNumberWithGroupAndDecimalChar() { FunctionTestUtil.assertResult(numberFunction.invoke("9 876.124", " ", "."), BigDecimal.valueOf(9876.124)); FunctionTestUtil.assertResult(numberFunction.invoke("9 876 000.124", " ", "."), BigDecimal.valueOf(98760...
public String getQualifiedName() { String column = identifier.getValueWithQuoteCharacters(); if (null != nestedObjectAttributes && !nestedObjectAttributes.isEmpty()) { column = String.join(".", column, nestedObjectAttributes.stream().map(IdentifierValue::getValueWithQuoteCharacters).collect(...
@Test void assertGetQualifiedNameWithOwner() { ColumnSegment actual = new ColumnSegment(0, 0, new IdentifierValue("col")); actual.setOwner(new OwnerSegment(0, 0, new IdentifierValue("tbl"))); assertThat(actual.getQualifiedName(), is("tbl.col")); }
@Override protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getChannelHandlers(MessageInput input) { final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>(super.getChannelHandlers(input)); // Replace the default "codec-aggregator" handler w...
@Test public void getChildChannelHandlersContainsCustomCodecAggregator() throws Exception { final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = transport.getChannelHandlers(mock(MessageInput.class)); assertThat(handlers) .containsKey("codec-aggregator") ...
Collection<OutputFile> compile() { List<OutputFile> out = new ArrayList<>(queue.size() + 1); for (Schema schema : queue) { out.add(compile(schema)); } if (protocol != null) { out.add(compileInterface(protocol)); } return out; }
@Test void logicalTypesWithMultipleFields() throws Exception { Schema logicalTypesWithMultipleFields = new Schema.Parser() .parse(new File("src/test/resources/logical_types_with_multiple_fields.avsc")); assertCompilesWithJavaCompiler(new File(OUTPUT_DIR, "testLogicalTypesWithMultipleFields"), ...
@Override public int compareTo(ID o) { TaskID that = (TaskID)o; int jobComp = this.jobId.compareTo(that.jobId); if(jobComp == 0) { if(this.type == that.type) { return this.id - that.id; } else { return this.type.compareTo(that.type); } } else return jobComp;...
@Test public void testCompareTo() { JobID jobId = new JobID("1234", 1); TaskID taskId1 = new TaskID(jobId, TaskType.REDUCE, 0); TaskID taskId2 = new TaskID(jobId, TaskType.REDUCE, 0); assertEquals("The compareTo() method returned non-zero for two equal " + "task IDs", 0, taskId1.compareTo(tas...
RegistryEndpointProvider<Void> committer(URL location) { return new Committer(location); }
@Test public void testCommitter_getHttpMethod() { Assert.assertEquals("PUT", testBlobPusher.committer(mockUrl).getHttpMethod()); }
@Override public <PS extends Serializer<P>, P> KeyValueIterator<K, V> prefixScan(final P prefix, final PS prefixKeySerializer) { Objects.requireNonNull(prefix); Objects.requireNonNull(prefixKeySerializer); final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = n...
@Test public void shouldThrowUnsupportedOperationExceptionWhilePrefixScan() { stubOneUnderlying.put("a", "1"); stubOneUnderlying.put("b", "1"); try (final KeyValueIterator<String, String> keyValueIterator = theStore.prefixScan("a", new StringSerializer())) { assertThrows(Unsuppor...
@Override public T deserialize(@Nullable byte[] message) throws IOException { if (message == null) { return null; } checkAvroInitialized(); getInputStream().setBuffer(message); Schema writerSchema = schemaCoder.readSchema(getInputStream()); Schema readerSc...
@Test void testGenericRecordReadWithCompatibleSchema() throws IOException { RegistryAvroDeserializationSchema<GenericRecord> deserializer = new RegistryAvroDeserializationSchema<>( GenericRecord.class, SchemaBuilder.record("Address") ...
@Override public long approximateNumEntries() { final List<ReadOnlyKeyValueStore<K, V>> stores = storeProvider.stores(storeName, storeType); long total = 0; for (final ReadOnlyKeyValueStore<K, V> store : stores) { total += store.approximateNumEntries(); if (total < 0)...
@Test public void shouldThrowInvalidStoreExceptionOnApproximateNumEntriesDuringRebalance() { assertThrows(InvalidStateStoreException.class, () -> rebalancing().approximateNumEntries()); }
@Udf(description = "Converts an INT value in degrees to a value in radians") public Double radians( @UdfParameter( value = "value", description = "The value in degrees to convert to radians." ) final Integer value ) { return radians(value == null ? null : ...
@Test public void shouldHandleNegative() { assertThat(udf.radians(-180.0), closeTo(-Math.PI, 0.000000000000001)); assertThat(udf.radians(-360.0), closeTo(-2 * Math.PI, 0.000000000000001)); assertThat(udf.radians(-70.73163980890013), closeTo(-1.2345, 0.000000000000001)); assertThat(udf.radians(-114), c...
UuidGenerator loadUuidGenerator() { Class<? extends UuidGenerator> objectFactoryClass = options.getUuidGeneratorClass(); ClassLoader classLoader = classLoaderSupplier.get(); ServiceLoader<UuidGenerator> loader = ServiceLoader.load(UuidGenerator.class, classLoader); if (objectFactoryClass...
@Test void test_case_7() { Options options = () -> OtherGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.cl...
@Override public void serialize(Asn1OutputStream out, Integer obj) { out.writeInt(obj); }
@Test public void shouldSerialize() { assertArrayEquals( new byte[] { 0x31, (byte) 0xab, (byte) 0xcd, (byte) 0xef }, serialize(new IntegerConverter(), int.class, 0x31abcdef) ); }
public static String getOwner(FileDescriptor fd) throws IOException { ensureInitialized(); if (Shell.WINDOWS) { String owner = Windows.getOwner(fd); owner = stripDomain(owner); return owner; } else { long uid = POSIX.getUIDforFDOwnerforOwner(fd); CachedUid cUid = uidCache.get(u...
@Test (timeout = 30000) public void testMultiThreadedFstat() throws Exception { assumeNotWindows(); final FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testfstat")); final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>(); List<Thread> statters = new...
@Override public MutableAnalysisMetadataHolder setProject(Project project) { checkState(!this.project.isInitialized(), "Project has already been set"); this.project.setProperty(project); return this; }
@Test public void setProject_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setProject(Project.from(newPrivateProjectDto())); assertThatThrownBy(() -> underTest.setProject(Project.from(newPrivateProjectDto()))) .isI...
long parkTime(long n) { final long proposedShift = n - parkThreshold; final long allowedShift = min(maxShift, proposedShift); return proposedShift > maxShift ? maxParkPeriodNs : proposedShift < maxShift ? minParkPeriodNs << allowedShift : min(minParkPeriodNs << al...
@Test public void when_proposedShiftLessThanAllowed_then_shiftProposed() { final BackoffIdleStrategy strat = new BackoffIdleStrategy(0, 0, 1, 4); assertEquals(1, strat.parkTime(0)); assertEquals(2, strat.parkTime(1)); }
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) { return new DateTime(dateStr, dateFormat); }
@Test public void parseTest6() { final String str = "Tue Jun 4 16:25:15 +0800 2019"; final DateTime dateTime = DateUtil.parse(str); assert dateTime != null; assertEquals("2019-06-04 16:25:15", dateTime.toString()); }