focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void updateNode(OpenstackNode osNode) { checkNotNull(osNode, ERR_NULL_NODE); OpenstackNode updatedNode; OpenstackNode existingNode = osNodeStore.node(osNode.hostname()); checkNotNull(existingNode, ERR_NULL_NODE); DeviceId existDeviceId = osNodeStore.node(o...
@Test(expected = IllegalArgumentException.class) public void testUpdateNodeWithDuplicateIntgBridge() { target.updateNode(COMPUTE_2_DUP_INT); }
public final int getFlags() { return flags; }
@Test public void getFlagsOutputZero() { // Arrange final LogHeader objectUnderTest = new LogHeader(0); // Act final int actual = objectUnderTest.getFlags(); // Assert result Assert.assertEquals(0, actual); }
public TransformWatermarks getWatermarks(ExecutableT executable) { return transformToWatermarks.get(executable); }
@Test public void getWatermarkForUntouchedTransform() { TransformWatermarks watermarks = manager.getWatermarks(graph.getProducer(impulse)); assertThat(watermarks.getInputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); assertThat(watermarks.getOutputWatermark(), equalTo(BoundedWindow.TIMESTAMP_M...
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testDisplayDataArrayValue() throws Exception { ArrayOptions options = PipelineOptionsFactory.as(ArrayOptions.class); options.setDeepArray(new String[][] {new String[] {"a", "b"}, new String[] {"c"}}); options.setDeepPrimitiveArray(new int[][] {new int[] {1, 2}, new int[] {3}}); Disp...
public AbstractRequestBuilder<K, V, R> removeParam(String key) { _queryParams.remove(key); _queryParamClasses.remove(key); return this; }
@Test public void testRemoveParam() { final AbstractRequestBuilder<?, ?, ?> builder = new DummyAbstractRequestBuilder(); builder.addParam("a", "b"); Assert.assertEquals(builder.getParam("a"), Arrays.asList("b")); builder.removeParam("a"); Assert.assertFalse(builder.hasParam("a")); }
@GET @Path("{id}") @Timed @ApiOperation(value = "Get index set") @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), @ApiResponse(code = 404, message = "Index set not found"), }) public IndexSetSummary get(@ApiParam(name = "id", required = true) ...
@Test public void getDenied() { notPermitted(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Not authorized to access resource id <id>"); try { indexSetsResource.get("id"); } finally { verifyNoMoreInteractions(...
public static int levenshtein(String a, String b) { // switch parameters to use the shorter one as b to save space. if (a.length() < b.length()) { String swap = a; a = b; b = swap; } int[][] d = new int[2][b.length() + 1]; for (int j = 0; j <...
@Test public void testPlainLevenshteinSpeedTest() { System.out.println("Levenshtein speed test"); for (int i = 0; i < 100; i++) { EditDistance.levenshtein(H1N1, H1N5); } }
public static String getDataSourceUnitVersionsNode(final String databaseName, final String dataSourceName) { return String.join("/", getDataSourceUnitsNode(databaseName), dataSourceName, VERSIONS); }
@Test void assertGetDataSourceUnitVersionsNode() { assertThat(DataSourceMetaDataNode.getDataSourceUnitVersionsNode("foo_db", "foo_ds"), is("/metadata/foo_db/data_sources/units/foo_ds/versions")); }
@Override protected void rename( List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds, MoveOptions... moveOptions) throws IOException { if (moveOptions.length > 0) { throw new UnsupportedOperationException("Support for move options is not yet implemented."); ...
@Test public void testMoveWithNonExistingSrcFile() throws Exception { Path existingSrc = temporaryFolder.newFile().toPath(); Path nonExistingSrc = temporaryFolder.getRoot().toPath().resolve("non-existent-file.txt"); Path destPath1 = temporaryFolder.getRoot().toPath().resolve("nonexistentdir").resolve("de...
@Override public ObjectNode encode(Group group, CodecContext context) { checkNotNull(group, "Group cannot be null"); ObjectNode result = context.mapper().createObjectNode() // a Group id should be an unsigned integer .put(ID, Integer.toUnsignedLong(group.id().id())) ...
@Test public void codecEncodeTest() { GroupBucket bucket1 = DefaultGroupBucket.createAllGroupBucket(DefaultTrafficTreatment.emptyTreatment()); GroupBucket bucket2 = DefaultGroupBucket.createAllGroupBucket(DefaultTrafficTreatment.emptyTreatment()); GroupBucket bucket3 = DefaultGroupBucket.cre...
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testPkcs1Des3EncryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypted.key") .getFile()), "example"); assertNotNull(key); }
public Optional<DoFn.ProcessContinuation> run( PartitionRecord partitionRecord, ChangeStreamRecord record, RestrictionTracker<StreamProgress, StreamProgress> tracker, DoFn.OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, ...
@Test public void testChangeStreamMutationGc() { ByteStringRange partition = ByteStringRange.create("", ""); when(partitionRecord.getPartition()).thenReturn(partition); final Instant commitTimestamp = Instant.ofEpochMilli(1_000L); final Instant lowWatermark = Instant.ofEpochMilli(500L); ChangeStre...
public String value() { return value; }
@Test public void testConstruction() { assertThat(subject3.value(), is("Message 3")); MessageSubject serializerObject = new MessageSubject(); assertThat(serializerObject.value(), is("")); }
public static AuthorizationsCollector parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } if (!file.exists()) { LOG.warn(...
@Test public void testParseValidEndLineComment() throws ParseException { Reader conf = new StringReader("topic /weather/italy/anemometer #simple comment"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); // Verify assertTrue(authorizations.canRead(new Topic("/wea...
@PublicAPI(usage = ACCESS) public JavaCodeUnit getCodeUnitWithParameterTypes(String name, Class<?>... parameters) { return getCodeUnitWithParameterTypes(name, ImmutableList.copyOf(parameters)); }
@Test public void getCodeUnitWithParameterTypes() { JavaClass clazz = importClasses(ChildWithFieldAndMethod.class).get(ChildWithFieldAndMethod.class); assertIllegalArgumentException("childMethod", () -> clazz.getCodeUnitWithParameterTypes("childMethod")); assertIllegalArgumentException("chi...
@Override public ByteBuf readBytes(int length) { checkReadableBytes(length); if (length == 0) { return Unpooled.EMPTY_BUFFER; } ByteBuf buf = alloc().buffer(length, maxCapacity); buf.writeBytes(this, readerIndex, length); readerIndex += length; re...
@Test public void testReadBytesAfterRelease9() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() throws IOException { releasedBuffer().readBytes(new ByteArrayOutputStream(), 1); } }); }
@Override public void close() { stop(); }
@Test public void createWithNullMetricRegistry() { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); DummyReporter r = null; try { r = new DummyReporter(null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); ...
@VisibleForTesting String getRequestBodyParamsAsStr( NameValuePair[] pairs, String charset ) throws KettleException { StringBuffer buf = new StringBuffer(); try { for ( int i = 0; i < pairs.length; ++i ) { NameValuePair pair = pairs[ i ]; if ( pair.getName() != null ) { if ( i ...
@Test public void getRequestBodyParametersAsStringWithNullEncoding() throws KettleException { HTTPPOST http = mock( HTTPPOST.class ); doCallRealMethod().when( http ).getRequestBodyParamsAsStr( any( NameValuePair[].class ), nullable( String.class ) ); NameValuePair[] pairs = new NameValuePair[] { ne...
public boolean overlap(final Window other) throws IllegalArgumentException { if (getClass() != other.getClass()) { throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type " + other.getClass() + "."); } final SessionWindow ot...
@Test public void cannotCompareSessionWindowWithDifferentWindowType() { assertThrows(IllegalArgumentException.class, () -> window.overlap(timeWindow)); }
public ConvertedTime getConvertedTime(long duration) { Set<Seconds> keys = RULES.keySet(); for (Seconds seconds : keys) { if (duration <= seconds.getSeconds()) { return RULES.get(seconds).getConvertedTime(duration); } } return new TimeConverter.Ove...
@Test public void testShouldReportAbout1HourFor89Minutes29Seconds() throws Exception { assertEquals(TimeConverter.ABOUT_1_HOUR_AGO, timeConverter.getConvertedTime(89 * 60 + 29)); }
@Override public void tryStartBundle() { inconsistentStateCheck(); LOG.debug( "tryStartBundle: elementCount={}, Bundle={}", currentBundleElementCount, this.toString()); if (isBundleStarted.compareAndSet(false, true)) { LOG.debug("Starting a new bundle."); bundleStartTime.set(System.c...
@Test public void testWhen() { portableBundleManager = new PortableBundleManager<>( bundleProgressListener, 4, MAX_BUNDLE_TIME_MS, bundleTimerScheduler, TIMER_ID); portableBundleManager.tryStartBundle(); portableBundleManager.tryStartBundle(); verify(bundleProgressListener, times(...
public static String parseContextUuid(String name, Long ledgerId) { if (ledgerId == null || name == null) { return null; } int pos = name.indexOf("-ledger-" + ledgerId); if (pos <= 0) { return null; } return name.substring(0, pos); }
@Test public void parseContextUuidTest() throws Exception { UUID id = UUID.randomUUID(); long ledgerId = 123124; String key = DataBlockUtils.dataBlockOffloadKey(ledgerId, id); String keyIndex = DataBlockUtils.indexBlockOffloadKey(ledgerId, id); assertEquals(ledgerId, DataBlo...
public static ParamType getVarArgsSchemaFromType(final Type type) { return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE); }
@Test public void shouldGetBooleanSchemaForBooleanPrimitiveClassVariadic() { assertThat( UdfUtil.getVarArgsSchemaFromType(boolean.class), equalTo(ParamTypes.BOOLEAN) ); }
@Override public String getAll() { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId(); checkNotNull...
@Test public void testGetAll() throws Exception { String reply = voltConfig.getAll(); assertNotNull("Incorrect response", reply); }
@Override public void execute(Context context) { executeForBranch(treeRootHolder.getRoot()); }
@Test public void givenNoPreviousUpgradeEvents_whenStepIsExecuted_thenANewUpgradeEventIsCreated() { when(sonarQubeVersion.get()).thenReturn(Version.parse("10.3")); when(dbClient.eventDao()).thenReturn(mock()); when(dbClient.eventDao().selectSqUpgradesByMostRecentFirst(any(), any())).thenReturn(Collections...
synchronized int increaseVersion() { return ++version; }
@Test void increaseVersion() { Job job = anEnqueuedJob().build(); assertThat(job.getVersion()).isZero(); assertThat(job.increaseVersion()).isEqualTo(1); assertThat(job.getVersion()).isEqualTo(1); assertThat(job.increaseVersion()).isEqualTo(2); assertThat(job.getVers...
@Override protected void descendingSort(File[] matchingFileArray, Instant instant) { String regexForIndexExtreaction = createStemRegex(instant); final Pattern pattern = Pattern.compile(regexForIndexExtreaction); Arrays.sort(matchingFileArray, new Comparator<File>() { @Override ...
@Test public void smoke() { FileNamePattern fileNamePattern = new FileNamePattern("smoke-%d-%i.gz", context); SizeAndTimeBasedArchiveRemover remover = new SizeAndTimeBasedArchiveRemover(fileNamePattern, null); File[] fileArray = new File[2]; File[] expected = new File[2]; fi...
@Override public RouterFunction<ServerResponse> create(String prefix) { return RouterFunctions.route(GET(StringUtils.prependIfMissing(prefix, "/")), handlerFunction()); }
@Test void create() { String prefix = "/topics"; RouterFunction<ServerResponse> routerFunction = categoriesRouteFactory.create(prefix); WebTestClient webClient = getWebTestClient(routerFunction); when(categoryFinder.listAsTree()) .thenReturn(Flux.empty()); webCli...
public static SqlToConnectTypeConverter sqlToConnectConverter() { return SQL_TO_CONNECT_CONVERTER; }
@Test public void shouldGetLogicalForEverySqlType() { for (final Entry<SqlType, Schema> entry : SQL_TO_LOGICAL.entrySet()) { final SqlType sqlType = entry.getKey(); final Schema logical = entry.getValue(); final Schema result = SchemaConverters.sqlToConnectConverter().toConnectSchema(sqlType); ...
@Override public void rewind() throws IOException { super.rewind(); for (int i = size - 1; i >= 0; i--) { File fi = getNumberedFileName(i); if (Files.exists(Util.fileToPath(fi))) { File next = getNumberedFileName(i + 1); Files.move(Util.fileToP...
@Issue("JENKINS-16634") @Test public void deletedFolder() throws Exception { assumeFalse("Windows does not allow deleting a directory with a " + "file open, so this case should never occur", Functions.isWindows()); File dir = tmp.newFolder("dir"); File base = new File(dir, "x...
public static List<List<Expr>> candidateOfPartitionByExprs(List<List<Expr>> partitionByExprs) { if (partitionByExprs.isEmpty()) { return Lists.newArrayList(); } PermutationGenerator generator = new PermutationGenerator<Expr>(partitionByExprs); int totalCount = 0; List...
@Test public void testPermutaionsOfPartitionByExprs2() throws Exception { List<List<Expr>> slotRefs = createSlotRefArray(1, 3); for (List<Expr> refs: slotRefs) { System.out.println(slotRefsToInt(refs)); } List<List<Expr>> newSlotRefs = PlanNode.candidateOfPartitionByExprs...
public List<InputSplit> getSplits(JobContext job) throws IOException { StopWatch sw = new StopWatch().start(); long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job)); long maxSize = getMaxSplitSize(job); // generate splits List<InputSplit> splits = new ArrayList<InputSplit>(); L...
@Test public void testNumInputFilesIgnoreDirs() throws Exception { Configuration conf = getConfiguration(); conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads); conf.setBoolean(FileInputFormat.INPUT_DIR_NONRECURSIVE_IGNORE_SUBDIRS, true); Job job = Job.getInstance(conf); FileInputForm...
@Override public boolean isSchemaAvailable() { return true; }
@Test void assertIsSchemaAvailable() { assertTrue(dialectDatabaseMetaData.isSchemaAvailable()); }
public static <T extends NumericType> T decodeNumeric(String input, Class<T> type) { try { byte[] inputByteArray = Numeric.hexStringToByteArray(input); int typeLengthAsBytes = getTypeLengthInBytes(type); int valueOffset = Type.MAX_BYTE_LENGTH - typeLengthAsBytes; ...
@Test public void testUint16Max() throws Exception { assertEquals( TypeDecoder.decodeNumeric( TypeEncoder.encodeNumeric( new Uint16(BigInteger.valueOf((long) Math.pow(2, 16) - 1))), Uint16.class), ...
public static void validateConfig(Object config, Class annotationClass) { for (Field field : config.getClass().getDeclaredFields()) { Object value = null; field.setAccessible(true); try { value = field.get(config); } catch (IllegalAccessException e...
@Test public void testStringList() { TestConfig testConfig = createGoodConfig(); testConfig.stringList = testIntegerList; Exception e = expectThrows(IllegalArgumentException.class, () -> ConfigValidation.validateConfig(testConfig)); assertTrue(e.getMessage().contains("stringList")); ...
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData, TypeReference<T> responseFormat) { return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null); }
@Test public void testNullResponseType() { RestClient client = spy(new RestClient(null)); assertThrows(NullPointerException.class, () -> client.httpRequest( MOCK_URL, TEST_METHOD, null, TEST_DTO, null, MO...
@Override public LongGaugeImpl newLongGauge(String name) { checkNotNull(name, "name can't be null"); LongGaugeImpl gauge = new LongGaugeImpl(this, name); gauges.put(createDescriptor(name).lookupView(), gauge); return gauge; }
@Test public void newGauge_whenExistingMetric() { LongGaugeImpl first = metricsRegistry.newLongGauge("foo"); LongGaugeImpl second = metricsRegistry.newLongGauge("foo"); assertNotSame(first, second); }
public MethodBuilder onthrow(Object onthrow) { this.onthrow = onthrow; return getThis(); }
@Test void onthrow() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.onthrow("on-throw-object"); Assertions.assertEquals("on-throw-object", builder.build().getOnthrow()); }
@Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { try { String partitionColumn = job.get(Constants.JDBC_PARTITION_COLUMN); int numPartitions = job.getInt(Constants.JDBC_NUM_PARTITIONS, -1); String lowerBound = job.get(Constants.JDBC_LOW_BOUND); Strin...
@Test public void testIntervalSplit_Decimal() throws HiveJdbcDatabaseAccessException, IOException { JdbcInputFormat f = new JdbcInputFormat(); when(mockDatabaseAccessor.getColumnNames(any(Configuration.class))).thenReturn(Lists.newArrayList("a")); List<TypeInfo> columnTypes = Collections.singletonList(Typ...
void fail(Throwable e) { // The error must be recorded before setting the noMoreSplits marker to make sure // isFinished will observe failure instead of successful completion. // Only record the first error message. if (setIf(stateReference, State.failed(e), state -> state.getKind() ...
@Test public void testFail() { HiveSplitSource hiveSplitSource = HiveSplitSource.allAtOnce( SESSION, "database", "table", new CacheQuotaRequirement(GLOBAL, Optional.empty()), 10, 10, new DataS...
@Override public boolean syncVerifyData(DistroData verifyData, String targetServer) { if (isNoExistTarget(targetServer)) { return true; } // replace target server as self server so that can callback. verifyData.getDistroKey().setTargetServer(memberManager.getSelf().getAdd...
@Test void testSyncVerifyDataWithCallbackForMemberDisconnect() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())...
public static < X, P extends MessageQueryParameter<X>, R extends RequestBody, M extends MessageParameters> X getQueryParameter(final HandlerRequest<R> request, final Class<P> queryParameterClass) throws RestH...
@Test void testGetQueryParameterDefaultValue() throws Exception { final Boolean allowNonRestoredState = HandlerRequestUtils.getQueryParameter( HandlerRequest.resolveParametersAndCreate( EmptyRequestBody.getInstance(), ...
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); }...
@Test public void stringToConnect() { assertEquals(new SchemaAndValue(Schema.STRING_SCHEMA, "foo-bar-baz"), converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"string\" }, \"payload\": \"foo-bar-baz\" }".getBytes())); }
public static TopicMessageType getMessageType(SendMessageRequestHeader requestHeader) { Map<String, String> properties = MessageDecoder.string2messageProperties(requestHeader.getProperties()); String traFlag = properties.get(MessageConst.PROPERTY_TRANSACTION_PREPARED); TopicMessageType topicMess...
@Test public void testGetMessageTypeAsTransaction() { SendMessageRequestHeader requestHeader = new SendMessageRequestHeader(); Map<String, String> map = new HashMap<>(); map.put(MessageConst.PROPERTY_TRANSACTION_PREPARED, "true"); requestHeader.setProperties(MessageDecoder.messagePr...
@Override public void checkBeforeUpdate(final CreateBroadcastTableRuleStatement sqlStatement) { ShardingSpherePreconditions.checkNotEmpty(database.getResourceMetaData().getStorageUnits(), () -> new EmptyStorageUnitException(database.getName())); if (!sqlStatement.isIfNotExists()) { check...
@Test void assertCheckSQLStatementWithDuplicateBroadcastRule() { executor.setDatabase(mockShardingSphereDatabase()); BroadcastRule rule = mock(BroadcastRule.class); when(rule.getTables()).thenReturn(Collections.singleton("t_address")); executor.setRule(rule); CreateBroadcastT...
@Override public double read() { return gaugeSource.read(); }
@Test public void whenCreatedForDynamicLongMetricWithProvidedValue() { DoubleGaugeImplTest.SomeObject someObject = new DoubleGaugeImplTest.SomeObject(); someObject.longField = 42; metricsRegistry.registerDynamicMetricsProvider((descriptor, context) -> context.collect(descript...
@Override public PageData<Asset> findAssetsByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(assetRepository .findByTenantId( tenantId, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); ...
@Test public void testFindAssetsByTenantId() { PageLink pageLink = new PageLink(20, 0, "ASSET_"); PageData<Asset> assets1 = assetDao.findAssetsByTenantId(tenantId1, pageLink); assertEquals(20, assets1.getData().size()); pageLink = pageLink.nextPageLink(); PageData<Asset> ass...
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof TransMeta ) ) { return feedback; } TransMeta transMeta = (TransMeta) subject; String description = transMe...
@Test public void testVerifyRule_NullParameter_EnabledRule() { TransformationHasDescriptionImportRule importRule = getImportRule( 10, true ); List<ImportValidationFeedback> feedbackList = importRule.verifyRule( null ); assertNotNull( feedbackList ); assertTrue( feedbackList.isEmpty() ); }
public static ReshuffleTriggerStateMachine create() { return new ReshuffleTriggerStateMachine(); }
@Test public void testOnTimer() throws Exception { TriggerStateMachineTester<Integer, IntervalWindow> tester = TriggerStateMachineTester.forTrigger( ReshuffleTriggerStateMachine.create(), FixedWindows.of(Duration.millis(100))); IntervalWindow arbitraryWindow = new IntervalWindow(new Instan...
@Override public void gauge(String id, Supplier<Number> supplier, String... tagNameValuePairs) { Id metricId = suffixBaseId(id).withTags(tagNameValuePairs); PolledMeter.remove(registry, metricId); PolledMeter.using(registry) .withId(metricId) .monitorValue(su...
@Test public void testUnregister() { DefaultRegistry registry = new DefaultRegistry(); SpectatorMetricRegistry metricRegistry = new SpectatorMetricRegistry(registry, registry.createId("foo")); metricRegistry.gauge("bar", () -> 10); metricRegistry.gauge("bar", () -> 20); ...
public SuperTrendLowerBandIndicator(final BarSeries barSeries) { this(barSeries, new ATRIndicator(barSeries, 10), 3d); }
@Test public void testSuperTrendLowerBandIndicator() { SuperTrendLowerBandIndicator superTrendLowerBandIndicator = new SuperTrendLowerBandIndicator(data); assertNumEquals(this.numOf(15.730621000000003), superTrendLowerBandIndicator.getValue(4)); assertNumEquals(this.numOf(17.602360938100002...
@Override public String topic() { if (recordContext == null) { // This is only exposed via the deprecated ProcessorContext, // in which case, we're preserving the pre-existing behavior // of returning dummy values when the record context is undefined. // For t...
@Test public void shouldReturnTopicFromRecordContext() { assertThat(context.topic(), equalTo(recordContext.topic())); }
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("position") BigDecimal position, @ParameterName("newItem") Object newItem) { if (list == null) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", CANNO...
@Test void invokeListNull() { FunctionTestUtil.assertResultError(listReplaceFunction.invoke(null, BigDecimal.ONE, ""), InvalidParametersEvent.class); }
static String resolveEcsEndpoint(AwsConfig awsConfig, String region) { String ecsHostHeader = awsConfig.getHostHeader(); if (isNullOrEmptyAfterTrim(ecsHostHeader) || ecsHostHeader.equals("ecs") ) { ecsHostHeader = DEFAULT_ECS_HOST_HEADER; } return ecsHostH...
@Test public void resolveEcsEndpoints() { assertEquals("ecs.us-east-1.amazonaws.com", resolveEcsEndpoint(AwsConfig.builder().build(), "us-east-1")); assertEquals("ecs.us-east-1.amazonaws.com", resolveEcsEndpoint(AwsConfig.builder().setHostHeader("ecs").build(), "us-east-1")); ass...
public DMNContext populateContextForDecisionServiceWith(String decisionServiceName, Map<String, Object> json) { DecisionServiceNode dsNode = model.getDecisionServices().stream().filter(ds -> ds.getName().equals(decisionServiceName)).findFirst().orElseThrow(IllegalArgumentException::new); for (Entry<Stri...
@Test void dSBasicDS2() throws Exception { final DMNRuntime runtime = createRuntime("0004-decision-services.dmn", DMNDecisionServicesTest.class); final DMNModel dmnModel = runtime.getModel("http://www.trisotech.com/definitions/_686f58d4-4ec3-4c65-8c06-0e4fd8983def", "Decision Services"); ass...
static void addFieldTypeMapPopulation(BlockStmt body, Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) { for (Map.Entry<String, KiePMMLOriginalTypeGeneratedType> entry : fieldTypeMap.entrySet()) { KiePMMLOriginalTypeGeneratedType kiePMMLOriginalTypeGeneratedType = entry.getValue(); ...
@Test void addFieldTypeMapPopulation() { BlockStmt blockStmt = new BlockStmt(); Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = new HashMap<>(); IntStream.range(0, 3).forEach(index -> { String key = "KEY-" + index; KiePMMLOriginalTypeGeneratedType value =...
@GET @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "Get prekey count", description = "Gets the number of one-time prekeys uploaded for this device and still available") @ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", use...
@Test void testNoDevices() { when(existsAccount.getDevices()).thenReturn(Collections.emptyList()); Response result = resources.getJerseyTest() .target(String.format("/v2/keys/%s/*", EXISTS_UUID)) .request() .header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccess...
public static SortOrder buildSortOrder(Table table) { return buildSortOrder(table.schema(), table.spec(), table.sortOrder()); }
@Test public void testEmptySpecsV2() { PartitionSpec spec = PartitionSpec.unpartitioned(); SortOrder order = SortOrder.builderFor(SCHEMA).withOrderId(1).asc("id", NULLS_LAST).build(); TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, spec, order, 2); // pass PartitionSpec.unpar...
public static AuthenticationMethod getAuthenticationMethod(Configuration conf) { String value = conf.get(HADOOP_SECURITY_AUTHENTICATION, "simple"); try { return Enum.valueOf(AuthenticationMethod.class, StringUtils.toUpperCase(value)); } catch (IllegalArgumentException iae) { throw new ...
@Test public void testGetAuthenticationMethod() { Configuration conf = new Configuration(); // default is simple conf.unset(HADOOP_SECURITY_AUTHENTICATION); assertEquals(SIMPLE, SecurityUtil.getAuthenticationMethod(conf)); // simple conf.set(HADOOP_SECURITY_AUTHENTICATION, "simple"); asser...
@PostMapping public Mono<ResponseEntity<ProductReview>> createProductReview( Mono<JwtAuthenticationToken> authenticationTokenMono, @Valid @RequestBody Mono<NewProductReviewPayload> payloadMono, UriComponentsBuilder uriComponentsBuilder) { return authenticationTokenMono.fl...
@Test void createProductReview_ReturnsCreatedProductReview() { // given doReturn(Mono.just(new ProductReview(UUID.fromString("5a9ba234-cbd6-11ee-acab-5748ca6678b9"), 1, 4, "В целом норм", "5f1d5cf8-cbd6-11ee-9579-cf24d050b47c"))) .when(this.productReviewsService) ...
@Override public void initialize(String name, Map<String, String> properties) { Preconditions.checkNotNull(properties, "Invalid catalog properties: null"); String uri = properties.get(CatalogProperties.URI); Preconditions.checkNotNull(uri, "JDBC connection URI is required"); String inputWarehouseLoca...
@Test public void testEnableInitCatalogTablesOverridesDefault() throws Exception { // as this test uses different connections, we can't use memory database (as it's per // connection), but a file database instead java.nio.file.Path dbFile = Files.createTempFile("icebergInitCatalogTables", "db"); Strin...
public Tuple2<Long, Double> increase(String name, ImmutableMap<String, String> labels, Double value, long windowSize, long now) { ID id = new ID(name, labels); Queue<Tuple2<Long, Double>> window = windows.computeIfAbsent(id, unused -> new PriorityQueue<>()); synchronized (window) { w...
@Test public void testPT1M() { double[] actuals = parameters().stream().mapToDouble(e -> { Tuple2<Long, Double> increase = CounterWindow.INSTANCE.increase( "test", ImmutableMap.<String, String>builder().build(), e._2, Duration.parse("PT1M").getSeconds() * 1000, e....
@Override protected TableRecords getUndoRows() { return super.getUndoRows(); }
@Test public void getUndoRows() { Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getAfterImage()); }
public Future<Collection<Integer>> resizeAndReconcilePvcs(KafkaStatus kafkaStatus, List<PersistentVolumeClaim> pvcs) { Set<Integer> podIdsToRestart = new HashSet<>(); List<Future<Void>> futures = new ArrayList<>(pvcs.size()); for (PersistentVolumeClaim desiredPvc : pvcs) { Future<V...
@Test public void testVolumesBoundMissingStorageClass(VertxTestContext context) { List<PersistentVolumeClaim> pvcs = List.of( createPvc("data-pod-0"), createPvc("data-pod-1"), createPvc("data-pod-2") ); ResourceOperatorSupplier supplier = Res...
@Override public String telnet(Channel channel, String message) { if (StringUtils.isEmpty(message)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(mess...
@Test void testChangeCancel2() throws RemotingException { String result = change.telnet(mockChannel, "/"); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); }
@Override public Integer doCall() throws Exception { JsonObject pluginConfig = loadConfig(); JsonObject plugins = pluginConfig.getMap("plugins"); Object plugin = plugins.remove(name); if (plugin != null) { printer().printf("Plugin %s removed%n", name); saveCo...
@Test public void shouldHandleUnknownPlugin() throws Exception { PluginDelete command = new PluginDelete(new CamelJBangMain().withPrinter(printer)); command.name = "foo"; command.doCall(); Assertions.assertEquals("Plugin foo not found in configuration", printer.getOutput()); ...
public RedisConnectionFactory(final RedisConfigProperties redisConfigProperties) { lettuceConnectionFactory = createLettuceConnectionFactory(redisConfigProperties); lettuceConnectionFactory.afterPropertiesSet(); }
@Test public void redisConnectionFactoryTest() { final RedisConfigProperties redisConfigProperties = mock(RedisConfigProperties.class); when(redisConfigProperties.getMode()).thenReturn(RedisModeEnum.SENTINEL.getName()); when(redisConfigProperties.getMaster()).thenReturn("master"); wh...
@Override public Acl getPermission(final Path file) throws BackgroundException { try { final Acl acl = new Acl(); if(containerService.isContainer(file)) { final BucketAccessControls controls = session.getClient().bucketAccessControls().list( co...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); ...
@Override @MethodNotAvailable public V replace(K key, V newValue) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testReplaceWithOldValue() { adapter.replace(23, "oldValue", "newValue"); }
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test(expected=AclException.class) public void testMergeAclEntriesNamedOther() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); List<...
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 invalidParameterCounts() throws Exception { Schema invalidSchema1 = createSampleRecordSchema(SpecificCompiler.MAX_FIELD_PARAMETER_UNIT_COUNT + 1, 0); SpecificCompiler compiler = new SpecificCompiler(invalidSchema1); assertCompilesWithJavaCompiler(new File(OUTPUT_DIR, "testInvalidParameterCounts...
public static BytesInput fromZigZagVarLong(long longValue) { long zigZag = (longValue << 1) ^ (longValue >> 63); return new UnsignedVarLongBytesInput(zigZag); }
@Test public void testFromZigZagVarLong() throws IOException { long value = RANDOM.nextInt(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BytesUtils.writeZigZagVarLong(value, baos); byte[] data = baos.toByteArray(); Supplier<BytesInput> factory = () -> BytesInput.fromZigZagVarLong(va...
public static Configuration loadConfiguration() { return loadConfiguration(new Configuration()); }
@Test void testConfigurationWithStandardYAML() throws FileNotFoundException { File confFile = new File(tmpDir, GlobalConfiguration.FLINK_CONF_FILENAME); try (final PrintWriter pw = new PrintWriter(confFile)) { pw.println("Key1: "); pw.println(" Key2: v1"); pw....
@Override public void configure(Map<String, ?> configs, boolean isKey) { if (listClass != null || inner != null) { log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner); throw new ConfigException("List dese...
@Test public void testListValueDeserializerNoArgConstructorsShouldThrowConfigExceptionDueMissingInnerClassProp() { props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_TYPE_CLASS, ArrayList.class); final ConfigException exception = assertThrows( ConfigException.class, () ->...
public static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved) { StringBuilder newp = new StringBuilder(); newp.append(getPath(id, path)); boolean first = appendQuery(newp, query, true); if(approved) { appendQuery(newp, PROXY_APPROVAL_PARAM+"=true", firs...
@Test void testGetPathAndQuery() { assertEquals("/proxy/application_6384623_0005/static/app?foo=bar", ProxyUriUtils.getPathAndQuery(BuilderUtils.newApplicationId(6384623l, 5), "/static/app", "?foo=bar", false)); assertEquals("/proxy/application_6384623_0005/static/app?foo=bar&bad=good&pro...
@Override public void flushScheduled() { }
@Test public void flushScheduled() { mSensorsAPI.flushScheduled(); }
@Override public List<Namespace> listNamespaces(Namespace namespace) { SnowflakeIdentifier scope = NamespaceHelpers.toSnowflakeIdentifier(namespace); List<SnowflakeIdentifier> results; switch (scope.type()) { case ROOT: results = snowflakeClient.listDatabases(); break; case DAT...
@Test public void testListNamespaceInRoot() { assertThat(catalog.listNamespaces()) .containsExactly(Namespace.of("DB_1"), Namespace.of("DB_2"), Namespace.of("DB_3")); }
@Override public TenantDO getTenantByWebsite(String website) { return tenantMapper.selectByWebsite(website); }
@Test public void testGetTenantByWebsite() { // mock 数据 TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setWebsite("https://www.iocoder.cn")); tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据 // 调用 TenantDO result = tenantService.getTenantByWebsite("https://www.iocod...
public static String getPartitionName(String basePath, String partitionPath) { String basePathWithSlash = getPathWithSlash(basePath); String partitionPathWithSlash = getPathWithSlash(partitionPath); if (basePathWithSlash.equals(partitionPathWithSlash)) { return ""; } ...
@Test public void testGetPartition() { String base = "hdfs://hadoop01:9000/mytable"; String tableLocation = "hdfs://hadoop01:9000/mytable/"; Assert.assertTrue(getPartitionName(base, tableLocation).isEmpty()); String errorPath = "hdfs://aaa/bbb"; ExceptionChecker.expectThrows...
public synchronized boolean saveNamespace(long timeWindow, long txGap, FSNamesystem source) throws IOException { if (timeWindow > 0 || txGap > 0) { final FSImageStorageInspector inspector = storage.readAndInspectDirs( EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK), Start...
@Test public void testDigest() throws IOException { Configuration conf = new Configuration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build(); DistributedFileSystem fs = cluster.getFileSystem(); fs.setSafeMode(SafeModeAction.ENTER);...
@Override public double logp(double x) { return Math.log(p(x)); }
@Test public void testLogp() { System.out.println("logp"); KernelDensity instance = new KernelDensity(x); double expResult = -2.29044906; double result = instance.logp(3.5); assertEquals(expResult, result, 1E-8); }
@Override public void run() { try { backgroundJobServer.getJobSteward().notifyThreadOccupied(); MDCMapper.loadMDCContextFromJob(job); performJob(); } catch (Exception e) { if (isJobDeletedWhileProcessing(e)) { // nothing to do anymore a...
@Test void onConcurrentJobModificationExceptionAllIsStillOk() throws Exception { Job job = anEnqueuedJob().build(); when(storageProvider.save(job)) .thenReturn(job) .thenThrow(new ConcurrentJobModificationException(job)); mockBackgroundJobRunner(job, job1 -> ...
@Override public List<String> findConfigInfoTags(String dataId, String group, String tenant) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableC...
@Test void testFindConfigInfoTags() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; List<String> mockedTags = Arrays.asList("tags1", "tags11", "tags111"); Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, grou...
public long getEndInMs() { return this.endInMs; }
@Test void testEndInMs() { long startTime = System.currentTimeMillis(); Pane<?> pane = new Pane<>(10, startTime, new Object()); assertEquals(startTime + 10, pane.getEndInMs()); }
public TolerantDoubleComparison isNotWithin(double tolerance) { return new TolerantDoubleComparison() { @Override public void of(double expected) { Double actual = DoubleSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolera...
@Test public void isNotWithinOfZero() { assertThat(+0.0).isNotWithin(0.00001).of(+1.0); assertThat(+0.0).isNotWithin(0.00001).of(-1.0); assertThat(-0.0).isNotWithin(0.00001).of(+1.0); assertThat(-0.0).isNotWithin(0.00001).of(-1.0); assertThat(+1.0).isNotWithin(0.00001).of(+0.0); assertThat(+1...
@Override public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable) { Map<DeviceId, Link> links = new HashMap<>(); ConnectPoint egressPoint = intent.egressPoint(); final boolean allowMissingPaths = intentAllowsPartialFailure(intent); boolean hasPath...
@Test public void testSingleLongPathCompilation() { Set<FilteredConnectPoint> ingress = Sets.newHashSet(new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1))); FilteredConnectPoint egress = new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_1)); MultiP...
@Override @Nonnull public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) { throwRejectedExecutionExceptionIfShutdown(); ArrayList<Future<T>> result = new ArrayList<>(); for (Callable<T> task : tasks) { try { result.add(new Co...
@Test void testInvokeAll() { final CompletableFuture<Thread> future = new CompletableFuture<>(); testTaskSubmissionBeforeShutdown( testInstance -> testInstance.invokeAll(callableCollectionFromFuture(future))); assertThat(future).isCompletedWithValue(Thread.currentThread()); ...
public static WindowStoreIterator<ValueAndTimestamp<GenericRow>> fetch( final ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> store, final GenericKey key, final Instant lower, final Instant upper ) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWi...
@Test public void shouldThrowException_wrongStateStore() { when(provider.stores(any(), any())).thenReturn(ImmutableList.of(windowStore)); final Exception e = assertThrows( IllegalStateException.class, () -> WindowStoreCacheBypass.fetch(store, SOME_KEY, Instant.ofEpochMilli(100), I...
@Override @PublicAPI(usage = ACCESS) public String getName() { return descriptor.getFullyQualifiedClassName(); }
@Test @UseDataProvider public void test_predicate_belong_to(DescribedPredicate<JavaClass> belongToPredicate) { JavaClasses classes = new ClassFileImporter().importPackagesOf(getClass()); JavaClass outerAnonymous = getOnlyClassSettingField(classes, ClassWithNamedAndAnonymousInnerC...
public double distance(Point point) { return Math.hypot(this.x - point.x, this.y - point.y); }
@Test public void distanceTest() { Point point1 = new Point(0, 0); Point point2 = new Point(1, 1); Point point3 = new Point(0, -1); Assert.assertEquals(0, point1.distance(point1), 0); Assert.assertEquals(0, point2.distance(point2), 0); Assert.assertEquals(0, point3.d...
public void setCalendar( int recordsFilter, GregorianCalendar startDate, GregorianCalendar endDate ) throws KettleException { this.startDate = startDate; this.endDate = endDate; this.recordsFilter = recordsFilter; if ( this.startDate == null || this.endDate == null ) { throw new KettleException( B...
@Test public void testSetCalendarStartDateTooOlder() throws KettleException { SalesforceConnection connection = new SalesforceConnection( logInterface, url, username, password ); GregorianCalendar startDate = new GregorianCalendar( 2000, 3, 20 ); GregorianCalendar endDate = new GregorianCalendar( 2000, 2,...
public abstract void updateTableSchema(String dbName, String tableName, List<HCatFieldSchema> columnSchema) throws HCatException;
@Test public void testUpdateTableSchema() throws Exception { try { HCatClient client = HCatClient.create(new Configuration(hcatConf)); final String dbName = "testUpdateTableSchema_DBName"; final String tableName = "testUpdateTableSchema_TableName"; client.dropDatabase(dbName, true, HCatCl...
@Override public void check(Model model) { if (model == null) return; List<Model> appenderModels = new ArrayList<>(); deepFindAllModelsOfType(AppenderModel.class, appenderModels, model); List<Pair<Model, Model>> nestedPairs = deepFindNestedSubModelsOfType(AppenderModel....
@Test public void smoke() { TopModel topModel = new TopModel(); awasc.check(topModel); statusChecker.assertIsWarningOrErrorFree(); }
@Override public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) { traceIfNecessary(grpcRequest, true); String type = grpcRequest.getMetadata().getType(); long startTime = System.nanoTime(); //server is on starting. if (!Applicati...
@Test void testHandleRequestSuccess() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true); String ip = "1.1.1.1"; Co...
public static String evaluate(String jsonText, JsonEvaluationSpecification specification) throws JsonMappingException { // Parse json text ang get root node. JsonNode rootNode; try { ObjectMapper mapper = new ObjectMapper(); rootNode = mapper.readTree(new StringReader(jsonTe...
@Test void testRegexpOperatorDispatcher() throws Exception { DispatchCases cases = new DispatchCases(); Map<String, String> dispatchCases = new HashMap<>(); dispatchCases.put(".*[Aa][Ll][Ee].*", "OK"); dispatchCases.put("default", "Bad"); cases.putAll(dispatchCases); JsonEvaluati...
@Override @Deprecated public JSONObject put(String key, Object value) throws JSONException { return set(key, value); }
@Test public void floatTest() { final Map<String, Object> map = new HashMap<>(); map.put("c", 2.0F); final String s = JSONUtil.toJsonStr(map); assertEquals("{\"c\":2}", s); }
@Override public void replay(AlterJobV2 replayedJob) { RollupJobV2 replayedRollupJob = (RollupJobV2) replayedJob; switch (replayedJob.jobState) { case PENDING: replayPending(replayedRollupJob); break; case WAITING_TXN: replayWai...
@Test public void testReplayPendingRollupJob() throws Exception { MaterializedViewHandler materializedViewHandler = GlobalStateMgr.getCurrentState().getRollupHandler(); ArrayList<AlterClause> alterClauses = new ArrayList<>(); alterClauses.add(clause); Database db = GlobalStateMgr.get...
public static int triCodeToDubboCode(Code triCode) { int code; switch (triCode) { case DEADLINE_EXCEEDED: code = TIMEOUT_EXCEPTION; break; case PERMISSION_DENIED: code = FORBIDDEN_EXCEPTION; break; case U...
@Test void triCodeToDubboCode() { Assertions.assertEquals(TIMEOUT_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.DEADLINE_EXCEEDED)); Assertions.assertEquals(FORBIDDEN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.PERMISSION_DENIED)); Assertions.assertEquals(METHOD_NOT_FOUND, TriRpcStatus...
public MapConfig setMaxIdleSeconds(int maxIdleSeconds) { this.maxIdleSeconds = maxIdleSeconds; return this; }
@Test public void testSetMaxIdleSeconds() { assertEquals(1234, new MapConfig().setMaxIdleSeconds(1234).getMaxIdleSeconds()); }
public void setMaxShare(Resource resource) { maxShareMB.set(resource.getMemorySize()); maxShareVCores.set(resource.getVirtualCores()); if (customResources != null) { customResources.setMaxShare(resource); } }
@Test public void testSetMaxShare() { FSQueueMetrics metrics = setupMetrics(RESOURCE_NAME); Resource res = Resource.newInstance(2048L, 4, ImmutableMap.of(RESOURCE_NAME, 20L)); metrics.setMaxShare(res); assertEquals(getErrorMessage("maxShareMB"), 2048L, metrics.getMaxShareMB()); a...