focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Optional<Track<T>> clean(Track<T> track) { NavigableSet<Point<T>> points = newTreeSet(track.points()); Set<Point<T>> badPoints = findPointsWithoutEnoughTimeSpacing(track); points.removeAll(badPoints); return (points.isEmpty()) ? Optional.empty() ...
@Test public void testCleaning_obliterate() { Track<NopHit> testTrack = createTrackFromResource( HighFrequencyPointRemover.class, "highFrequencyPoints_example1.txt" ); Duration MIN_ALLOWABLE_SPACING = Duration.ofSeconds(10); DataCleaner<Track<NopHit>> smoot...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testParseInvalidRecordBatch() { buildFetcher(); MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, Compression.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new S...
public static Object construct(Object something) throws Exception { if (something instanceof String) { return Class.forName((String)something).getConstructor().newInstance(); } else if (something instanceof Map) { // keys are the class name, values are the parameters. ...
@Test public void classWithoutGivenParam_constructed_ignoresParam() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("hello", "howdy"); params.put("name", "nick"); Map<String, Object> constructMap = new HashMap<>(); constructMap.put("com.networknt.s...
@Override public MapTileList computeFromSource(final MapTileList pSource, final MapTileList pReuse) { final MapTileList out = pReuse != null ? pReuse : new MapTileList(); for (int i = 0; i < pSource.getSize(); i++) { final long sourceIndex = pSource.get(i); final int zoom = M...
@Test public void testOnePointModuloInclude() { final MapTileList source = new MapTileList(); final MapTileList dest = new MapTileList(); final Set<Long> set = new HashSet<>(); final int border = 2; final MapTileListBorderComputer computer = new MapTileListBorderComputer(bord...
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword) throws IOException, GeneralSecurityException { PrivateKey key; try { key = createPrivateKey(privateKeyFile, keyPassword); } catch (OperatorCreationException | IOExcepti...
@Test void testParsingPKCS1WithWrongPassword() throws IOException, GeneralSecurityException { assertThrows(GeneralSecurityException.class, () -> { PEMImporter.loadKeyStore(pemCert, privkeyWithPasswordPKCS1, "nottest"); }); }
public ColumnConstraints getConstraints() { return constraints; }
@Test public void shouldReturnHeadersConstraint() { // Given: final TableElement valueElement = new TableElement(NAME, new Type(SqlTypes.STRING), HEADERS_CONSTRAINT); // Then: assertThat(valueElement.getConstraints(), is(HEADERS_CONSTRAINT)); }
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testExchangeModeHybridSelective() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); // fromElements -> Map -> Print DataStream<Integer> sourceDataStream = env.fromData(1, 2, 3); ...
@PostMapping("/status") @Operation(summary = "Get the email status of an account") public DEmailStatusResult getEmailStatus(@RequestBody DAccountRequest deprecatedRequest) { AppSession appSession = validate(deprecatedRequest); var result = accountService.getEmailStatus(appSession.getAccountId()...
@Test public void validEmailStatusVerified() { DAccountRequest request = new DAccountRequest(); request.setAppSessionId("id"); EmailStatusResult result = new EmailStatusResult(); result.setStatus(Status.OK); result.setError("error"); result.setEmailStatus(EmailStatus...
@Override public ImmutableList<String> computeEntrypoint(List<String> jvmFlags) { ImmutableList.Builder<String> entrypoint = ImmutableList.builder(); entrypoint.add("java"); entrypoint.addAll(jvmFlags); entrypoint.add("-jar"); entrypoint.add(JarLayers.APP_ROOT + "/" + jarPath.getFileName().toStrin...
@Test public void testComputeEntrypoint() throws URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI()); SpringBootPackagedProcessor springBootProcessor = new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION); ImmutableList<String> actualEnt...
public CompatibilityInfoMap checkPegasusSchemaCompatibility(String prevPegasusSchemaPath, String currentPegasusSchemaPath, CompatibilityOptions.Mode compatMode) { boolean newSchemaCreated = false; boolean preSchemaRemoved = false; DataSchema preSchema = null; try { preSchema = parseSc...
@Test(dataProvider = "compatibleInputFiles") public void testCompatiblePegasusSchemaSnapshot(String prevSchema, String currSchema, CompatibilityLevel compatLevel, CompatibilityOptions.Mode mode) { PegasusSchemaSnapshotCompatibilityChecker checker = new PegasusSchemaSnapshotCompatibilityChecker(); Compatibil...
@Override public boolean shouldRescale( VertexParallelism currentParallelism, VertexParallelism newParallelism) { for (JobVertexID vertex : currentParallelism.getVertices()) { int parallelismChange = newParallelism.getParallelism(vertex) ...
@Test void testNoScaleOnSameParallelism() { final RescalingController rescalingController = new EnforceMinimalIncreaseRescalingController(2); assertThat(rescalingController.shouldRescale(forParallelism(2), forParallelism(2))) .isFalse(); }
@Override public void execute(final List<String> args, final PrintWriter terminal) { CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP); if (args.isEmpty()) { terminal.println(restClient.getServerAddress()); return; } else { final String serverAddress = args.get(0); restClient.setS...
@Test public void shouldSetRestClientServerAddressWhenNonEmptyStringArg() { // When: command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal); // Then: verify(restClient).setServerAddress(VALID_SERVER_ADDRESS); }
@Override public Messages process(Messages messages) { try (Timer.Context ignored = executionTime.time()) { final State latestState = stateUpdater.getLatestState(); if (latestState.enableRuleMetrics()) { return process(messages, new RuleMetricsListener(metricRegistry)...
@Test public void process_ruleConditionEvaluationErrorConvertedIntoMessageProcessingError() throws Exception { // given when(ruleService.loadAll()).thenReturn(ImmutableList.of(RuleDao.create("broken_condition", "broken_condition", "broken_condition", "rule \"broken_co...
@Override public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListener listener) throws Http2Exception { if (readError) { input.skipBytes(input.readableBytes()); return; } try { do { if (readingHeaders && !...
@Test public void failedWhenConnectionWindowUpdateFrameWithZeroDelta() throws Http2Exception { final ByteBuf input = Unpooled.buffer(); try { writeFrameHeader(input, 4, WINDOW_UPDATE, new Http2Flags(), 0); input.writeInt(0); Http2Exception ex = assertThrows(Http2E...
public synchronized boolean tryWriteLock() { if (!isFree()) { return false; } else { status = -1; return true; } }
@Test void testDoubleWriteLock() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryWriteLock()); assertFalse(lock.tryWriteLock()); }
@Override public void register(ApplicationId appId) { }
@Test public void testRegister() { assertTrue(store.registerApplication(appId)); }
public void validateUrl(String serverUrl) { HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos"); doGet("", url, body -> buildGson().fromJson(body, RepositoryList.class)); }
@Test public void fail_validate_url_when_body_is_empty() { server.enqueue(new MockResponse().setResponseCode(404).setBody("")); String serverUrl = server.url("/").toString(); assertThatThrownBy(() -> underTest.validateUrl(serverUrl)) .isInstanceOf(BitbucketServerException.class) .hasMessage("...
public static String getFullElapsedTime(final long delta) { if (delta < Duration.ofSeconds(1).toMillis()) { return String.format("%d %s", delta, delta == 1 ? LocaleUtils.getLocalizedString("global.millisecond") : LocaleUtils.getLocalizedString("global.milliseconds")); } else if (delta < Dura...
@Test public void testElapsedTimeInHours() throws Exception { assertThat(StringUtils.getFullElapsedTime(Duration.ofHours(1)), is("1 hour")); assertThat(StringUtils.getFullElapsedTime(Duration.ofHours(1).plus(Duration.ofMinutes(1)).plus(Duration.ofSeconds(1)).plus(Duration.ofMillis(1))), is("1 hour, ...
public static StatementExecutorResponse execute( final ConfiguredStatement<AssertSchema> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { return AssertExecutor.execute( statement.getMaskedStat...
@Test public void shouldFailWhenSRClientFails() { // Given final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.empty(), Optional.of(222), Optional.empty(), false); final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement .of(KsqlParser.PreparedStatement.of(...
public static <T extends Throwable> void checkNotNull(final Object reference, final Supplier<T> exceptionSupplierIfUnexpected) throws T { if (null == reference) { throw exceptionSupplierIfUnexpected.get(); } }
@Test void assertCheckNotNullToThrowsException() { assertThrows(SQLException.class, () -> ShardingSpherePreconditions.checkNotNull(null, SQLException::new)); }
public ConfigCheckResult checkConfig() { Optional<Long> appId = getAppId(); if (appId.isEmpty()) { return failedApplicationStatus(INVALID_APP_ID_STATUS); } GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDe...
@Test public void checkConfig_whenAppDoesntHaveAnyPermissions_shouldReturnFailedAppJitCheck() { mockGithubConfiguration(); ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class); GsonApp githubApp = mockGithubApp(appConfigurationCaptor); ...
public static double schemaNameToScaleFactor(String schemaName) { if (TINY_SCHEMA_NAME.equals(schemaName)) { return TINY_SCALE_FACTOR; } if (!schemaName.startsWith("sf")) { return -1; } try { return Double.parseDouble(schemaName.substring...
@Test public void testColumnStatsWithConstraints() { SUPPORTED_SCHEMAS.forEach(schema -> { double scaleFactor = TpchMetadata.schemaNameToScaleFactor(schema); //Single constrained column has only one unique value testColumnStats(schema, ORDERS, ORDER_STATUS, constrain...
@Override public Iterable<FileInfo> listPrefix(String prefix) { S3URI s3uri = new S3URI(prefix, s3FileIOProperties.bucketToAccessPointMapping()); ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(s3uri.bucket()).prefix(s3uri.key()).build(); return () -> client().listObj...
@Test public void testPrefixList() { String prefix = "s3://bucket/path/to/list"; List<Integer> scaleSizes = Lists.newArrayList(1, 1000, 2500); scaleSizes .parallelStream() .forEach( scale -> { String scalePrefix = String.format("%s/%s/", prefix, scale); ...
public BackgroundJobServerConfiguration andName(String name) { if (isNullOrEmpty(name)) throw new IllegalArgumentException("The name can not be null or empty"); if (name.length() >= 128) throw new IllegalArgumentException("The length of the name can not exceed 128 characters"); this.name = name;...
@Test void ifNameIsEmptyThenExceptionIsThrown() { assertThatThrownBy(() -> backgroundJobServerConfiguration.andName("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The name can not be null or empty"); }
@Override public Object convert(String value) { if (isNullOrEmpty(value)) { return value; } if (value.contains("=")) { final Map<String, String> fields = new HashMap<>(); Matcher m = PATTERN.matcher(value); while (m.find()) { ...
@Test public void testFilterRetainsWhitespaceInSingleQuotedValues() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("otters in k1= v1 k2=' v2' k3=' v3 ' more otters");...
@Override public boolean isNodeVersionCompatibleWith(Version clusterVersion) { Preconditions.checkNotNull(clusterVersion); return node.getVersion().asVersion().equals(clusterVersion); }
@Test public void test_nodeVersionNotCompatibleWith_otherMajorVersion() { MemberVersion currentVersion = getNode(hazelcastInstance).getVersion(); Version majorPlusOne = Version.of(currentVersion.getMajor() + 1, currentVersion.getMinor()); assertFalse(nodeExtension.isNodeVersionCompatibleWith...
@Override public <T> T convert(DataTable dataTable, Type type) { return convert(dataTable, type, false); }
@Test void convert_to_object__too_wide__throws_exception() { DataTable table = parse("", "| ♘ | ♝ |"); registry.defineDataTableType(new DataTableType(Piece.class, PIECE_TABLE_CELL_TRANSFORMER)); CucumberDataTableException exception = assertThrows( CucumberDataTableE...
public int doWork() { final long nowNs = nanoClock.nanoTime(); cachedNanoClock.update(nowNs); dutyCycleTracker.measureAndUpdate(nowNs); final int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT); final long shortSendsBefore = shortSen...
@Test void shouldSendHeartbeatsEvenIfSendingPeriodicSetupFrames() { final StatusMessageFlyweight msg = mock(StatusMessageFlyweight.class); when(msg.consumptionTermId()).thenReturn(INITIAL_TERM_ID); when(msg.consumptionTermOffset()).thenReturn(0); when(msg.receiverWindowLength())....
@Override public Acl getPermission(final Path file) throws BackgroundException { try { if(file.getType().contains(Path.Type.upload)) { // Incomplete multipart upload has no ACL set return Acl.EMPTY; } final Path bucket = containerService.ge...
@Test public void testReadContainer() throws Exception { final Path container = new Path("test-acl-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Acl acl = new S3AccessControlListFeature(session).getPermission(container); assertTrue(acl.containsKey(new Acl.Gr...
public static byte[] compress(String urlString) throws MalformedURLException { byte[] compressedBytes = null; if (urlString != null) { // Figure the compressed bytes can't be longer than the original string. byte[] byteBuffer = new byte[urlString.length()]; int byteBu...
@Test public void testCompressURL() throws MalformedURLException { String testURL = "http://www.radiusnetworks.com"; byte[] expectedBytes = {0x00, 'r', 'a', 'd', 'i', 'u', 's', 'n', 'e', 't', 'w', 'o', 'r', 'k', 's', 0x07}; assertTrue(Arrays.equals(expectedBytes, UrlBeaconUrlCompressor.compr...
@Override public Integer getIntAndRemove(K name) { return null; }
@Test public void testGetIntAndRemoveDefault() { assertEquals(1, HEADERS.getIntAndRemove("name1", 1)); }
private CompletionStage<RestResponse> info(RestRequest request) { return asJsonResponseFuture(invocationHelper.newResponse(request), SERVER_INFO.toJson(), isPretty(request)); }
@Test public void testServerInfo() { CompletionStage<RestResponse> response = client.server().info(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).containsReturnedText(Version.printVersion()); }
public ConcurrentMap<String, ConcurrentMap<Integer, Long>> getOffsetTable() { return offsetTable; }
@Test public void testOffsetPersistInMemory() { ConcurrentMap<String, ConcurrentMap<Integer, Long>> offsetTable = consumerOffsetManager.getOffsetTable(); ConcurrentMap<Integer, Long> table = new ConcurrentHashMap<>(); table.put(0, 1L); table.put(1, 3L); String group = "G1"; ...
@Override public EntityExcerpt createExcerpt(GrokPattern grokPattern) { return EntityExcerpt.builder() .id(ModelId.of(grokPattern.id())) .type(ModelTypes.GROK_PATTERN_V1) .title(grokPattern.name()) .build(); }
@Test public void createExcerpt() { final GrokPattern grokPattern = GrokPattern.create("01234567890", "name", "pattern", null); final EntityExcerpt excerpt = facade.createExcerpt(grokPattern); assertThat(excerpt.id()).isEqualTo(ModelId.of("01234567890")); assertThat(excerpt.type())....
@Override public long computePullFromWhereWithException(MessageQueue mq) throws MQClientException { ConsumeFromWhere consumeFromWhere = litePullConsumerImpl.getDefaultLitePullConsumer().getConsumeFromWhere(); long result = -1; switch (consumeFromWhere) { case CONSUME_FROM_LAST_OF...
@Test public void testComputePullFromWhereWithException_eq_minus1_first() throws MQClientException { when(offsetStore.readOffset(any(MessageQueue.class), any(ReadOffsetType.class))).thenReturn(-1L); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); assertEquals(0, reb...
public static IpAddress makeMaskPrefix(Version version, int prefixLength) { byte[] mask = makeMaskPrefixArray(version, prefixLength); return new IpAddress(version, mask); }
@Test(expected = IllegalArgumentException.class) public void testInvalidMakeNegativeMaskPrefixIPv4() { IpAddress ipAddress; ipAddress = IpAddress.makeMaskPrefix(IpAddress.Version.INET, -1); }
public void create() { checkFilesAccessibility(bundledPlugins, externalPlugins); reset(); MessageDigest md5Digest = DigestUtils.getMd5Digest(); try (ZipOutputStream zos = new ZipOutputStream(new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest)))...
@Test void shouldZipTaskPluginsIntoOneZipEveryTime() throws Exception { pluginsZip.create(); assertThat(new File(expectedZipPath).exists()).as(expectedZipPath + " should exist").isTrue(); try (ZipFile zipFile = new ZipFile(expectedZipPath)) { assertThat(zipFile.getEntry("bundled...
public <InputT, OutputT, CollectionT extends PCollection<? extends InputT>> DataSet<OutputT> applyBeamPTransform( DataSet<InputT> input, PTransform<CollectionT, PCollection<OutputT>> transform) { return (DataSet) getNonNull( applyBeamPTransformInternal( ImmutableM...
@Test public void testApplySimpleTransform() throws Exception { ExecutionEnvironment env = ExecutionEnvironment.createCollectionsEnvironment(); DataSet<String> input = env.fromCollection(ImmutableList.of("a", "b", "c")); DataSet<String> result = new BeamFlinkDataSetAdapter().applyBeamPTransform(i...
public void setup(final Map<String, InternalTopicConfig> topicConfigs) { log.info("Starting to setup internal topics {}.", topicConfigs.keySet()); final long now = time.milliseconds(); final long deadline = now + retryTimeoutMs; final Map<String, Map<String, String>> streamsSideTopicCo...
@Test public void shouldCleanUpWhenCreateTopicsResultsDoNotContainTopic() { final AdminClient admin = mock(AdminClient.class); final StreamsConfig streamsConfig = new StreamsConfig(config); final InternalTopicManager topicManager = new InternalTopicManager(time, admin, streamsConfig); ...
public static String calculateMemoryWithDefaultOverhead(String memory) { long memoryMB = convertToBytes(memory) / M; long memoryOverheadMB = Math.max((long) (memoryMB * 0.1f), MINIMUM_OVERHEAD); return (memoryMB + memoryOverheadMB) + "Mi"; }
@Test void testConvert() { assertEquals("484Mi", K8sUtils.calculateMemoryWithDefaultOverhead("100m")); assertEquals("1408Mi", K8sUtils.calculateMemoryWithDefaultOverhead("1Gb")); assertEquals("4505Mi", K8sUtils.calculateMemoryWithDefaultOverhead("4Gb")); assertEquals("6758Mi", K8sUtils.calculateMemory...
public static LotteryNumbers create(Set<Integer> givenNumbers) { return new LotteryNumbers(givenNumbers); }
@Test void testEquals() { var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertEquals(numbers1, numbers2); var numbers3 = LotteryNumbers.create(Set.of(11, 12, 13, 14)); assertNotEquals(numbers1, numbers3); }
@Override public String convert(ILoggingEvent event) { Map<String, String> mdcPropertyMap = event.getMDCPropertyMap(); if (mdcPropertyMap == null) { return defaultValue; } if (key == null) { return outputMDCForAllKeys(mdcPropertyMap); } else { ...
@Test public void testConvertWithMultipleEntries() { logbackMDCAdapter.put("testKey", "testValue"); logbackMDCAdapter.put("testKey2", "testValue2"); ILoggingEvent le = createLoggingEvent(); String result = converter.convert(le); boolean isConform = result.matches("testKey2?=t...
@Override public void extendQueryProperties(final Properties props) { for (String each : toBeOverrideQueryProps.stringPropertyNames()) { props.setProperty(each, toBeOverrideQueryProps.getProperty(each)); } for (String each : completeIfMissedQueryProps.stringPropertyNames()) { ...
@Test void assertExtendQueryProperties() { Optional<JdbcQueryPropertiesExtension> extension = DatabaseTypedSPILoader.findService(JdbcQueryPropertiesExtension.class, TypedSPILoader.getService(DatabaseType.class, "MySQL")); assertTrue(extension.isPresent()); assertExtension(extension.get()); ...
Parsed parseLine(final String s) { if (s == null) { return null; } else { Parsed parsed = new Parsed(++row); int length = s.length(); // Trim any space at the end of the line while (length > 0 && s.charAt(length - 1) == ' ') length--; int state = 0; // 0...
@Test public void testLine() { YamlConfigurationReader yaml = new YamlConfigurationReader(new StringReader(""), new URLConfigurationResourceResolver(null), new Properties(), PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE); YamlConfigurationReader.Parsed p = yaml.parseLine(" key: value"); as...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void testBuildWithIllegalMaxCoreThreads() { ThreadPoolBulkheadConfig.custom() .maxThreadPoolSize(1) .coreThreadPoolSize(2) .build(); }
public boolean cleanTable() { boolean allRemoved = true; Set<String> removedPaths = new HashSet<>(); for (PhysicalPartition partition : table.getAllPhysicalPartitions()) { try { WarehouseManager manager = GlobalStateMgr.getCurrentState().getWarehouseMgr(); ...
@Test public void testNoTablet(@Mocked LakeTable table, @Mocked PhysicalPartition partition, @Mocked MaterializedIndex index, @Mocked LakeTablet tablet, @Mocked LakeService lakeService) { Lake...
Optional<TextRange> mapRegion(@Nullable Region region, InputFile file) { if (region == null) { return Optional.empty(); } int startLine = Objects.requireNonNull(region.getStartLine(), "No start line defined for the region."); int endLine = Optional.ofNullable(region.getEndLine()).orElse(startLine)...
@Test public void mapRegion_whenStartEndLinesDefinedAndEndColumn() { Region fullRegion = mockRegion(null, 8, 3, 8); Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE); assertThat(optTextRange).isPresent(); TextRange textRange = optTextRange.get(); assertThat(textRa...
public static URL urlForResource(String location) throws MalformedURLException, FileNotFoundException { if (location == null) { throw new NullPointerException("location is required"); } URL url = null; if (!location.matches(SCHEME_PATTERN)) { url = Loader.getResourceBySelfClassLoader(l...
@Test public void testExplicitClasspathUrl() throws Exception { URL url = LocationUtil.urlForResource( LocationUtil.CLASSPATH_SCHEME + TEST_CLASSPATH_RESOURCE); validateResource(url); }
@SuppressWarnings("unchecked") // safe because we only read, not write /* * non-final because it's overridden by MultimapWithProtoValuesSubject. * * If we really, really wanted it to be final, we could investigate whether * MultimapWithProtoValuesFluentAssertion could provide its own valuesForKey method. ...
@Test public void valuesForKeyListMultimap() { ImmutableListMultimap<Integer, String> multimap = ImmutableListMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); assertThat(multimap).valuesForKey(4).isInStrictOrder(); }
@SuppressWarnings("unchecked") public final void isGreaterThan(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) <= 0) { failWithActual("expected to be greater than", other); } }
@Test public void isGreaterThan_failsSmaller() { expectFailureWhenTestingThat(3).isGreaterThan(4); assertFailureValue("expected to be greater than", "4"); }
private static int getErrorCode(final int kernelCode, final int errorCode) { Preconditions.checkArgument(kernelCode >= 0 && kernelCode < 10, "The value range of kernel code should be [0, 10)."); Preconditions.checkArgument(errorCode >= 0 && errorCode < 1000, "The value range of error code should be [0, ...
@Test void assertToSQLExceptionWithCause() { Exception cause = new RuntimeException("test"); SQLException actual = new KernelSQLException(XOpenSQLState.GENERAL_ERROR, 1, 1, cause, "reason") { }.toSQLException(); assertThat(actual.getSQLState(), is(XOpenSQLState.GENERAL_ERROR.getValue...
@Override @SuppressWarnings("unchecked") public <K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType) { requireNonNull(dataTable, "dataTable may not be null"); requireNonNull(keyType, "keyType may not be null"); requireNonNull(valueType, "valueType may not be n...
@Test void to_maps_of_unknown_value_type__throws_exception__register_table_cell_transformer() { DataTable table = parse("", "| ♙ | ♟ |", "| a2 | a7 |", "| b2 | b7 |", "| c2 | c7 |", "| d2 | d7 |", "| e2 | e7 |", "| f2 | f7...
@Override public DataTableType dataTableType() { return dataTableType; }
@Test void can_define_data_table_converter() throws NoSuchMethodException { Method method = JavaDataTableTypeDefinitionTest.class.getMethod("convert_data_table_to_string", DataTable.class); JavaDataTableTypeDefinition definition = new JavaDataTableTypeDefinition(method, lookup, new Strin...
public Optional<InstantAndValue<T>> getAndSet(MetricKey metricKey, Instant now, T value) { InstantAndValue<T> instantAndValue = new InstantAndValue<>(now, value); InstantAndValue<T> valueOrNull = counters.put(metricKey, instantAndValue); // there wasn't already an entry, so return empty. ...
@Test public void testGetAndSetDouble() { LastValueTracker<Double> lastValueTracker = new LastValueTracker<>(); Optional<InstantAndValue<Double>> result = lastValueTracker.getAndSet(METRIC_NAME, instant1, 1d); assertFalse(result.isPresent()); }
@Override public void batchWriteBegin() throws InterruptedException, JournalException { if (currentTransaction != null) { throw new JournalException(String.format( "failed to begin batch write because has running txn = %s", currentTransaction)); } JournalExce...
@Test public void testBatchWriteBeginRetry( @Mocked CloseSafeDatabase database, @Mocked BDBEnvironment environment, @Mocked Database rawDatabase, @Mocked Environment rawEnvironment, @Mocked Transaction txn) throws Exception { BDBJEJournal journal =...
@Override public TypedResult<List<RowData>> retrieveChanges() { synchronized (resultLock) { // retrieval thread is alive return a record if available // but the program must not have failed if (isRetrieving() && executionException.get() == null) { if (chan...
@Test void testRetrieveChanges() throws Exception { int totalCount = ChangelogCollectResult.CHANGE_RECORD_BUFFER_SIZE * 2; CloseableIterator<RowData> data = CloseableIterator.adapterForIterator( IntStream.range(0, totalCount) .m...
@Override @DataPermission(enable = false) // 禁用数据权限,避免建立不正确的缓存 @Cacheable(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST, key = "#id") public Set<Long> getChildDeptIdListFromCache(Long id) { List<DeptDO> children = getChildDeptList(id); return convertSet(children, DeptDO::getId); }
@Test public void testGetChildDeptListFromCache() { // mock 数据(1 级别子节点) DeptDO dept1 = randomPojo(DeptDO.class, o -> o.setName("1")); deptMapper.insert(dept1); DeptDO dept2 = randomPojo(DeptDO.class, o -> o.setName("2")); deptMapper.insert(dept2); // mock 数据(2 级子节点) ...
public ProtocolBuilder port(Integer port) { this.port = port; return getThis(); }
@Test void port() { ProtocolBuilder builder = new ProtocolBuilder(); builder.port(8080); Assertions.assertEquals(8080, builder.build().getPort()); }
public static KeyedPValueTrackingVisitor create() { return new KeyedPValueTrackingVisitor(); }
@Test public void traverseMultipleTimesThrows() { p.apply( Create.of(KV.of(1, (Void) null), KV.of(2, (Void) null), KV.of(3, (Void) null)) .withCoder(KvCoder.of(VarIntCoder.of(), VoidCoder.of()))) .apply(GroupByKey.create()) .apply(Keys.create()); p.traverseTopologi...
@Override public TenantId getTenantId(NetworkId networkId) { VirtualNetwork virtualNetwork = getVirtualNetwork(networkId); checkNotNull(virtualNetwork, "The network does not exist."); return virtualNetwork.tenantId(); }
@Test public void testGetTenantIdForRegisteredVirtualNetwork() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(tenantIdValue1); TenantId tenantId = manager.getTenantId(virtualNetwork.id()); assertThat(tenantId.toString(), is(tenantIdValue1)); }
public boolean visibleForTransaction(long txnId) { return state == IndexState.NORMAL || visibleTxnId <= txnId; }
@Test public void testVisibleForTransaction() throws Exception { index = new MaterializedIndex(10); Assert.assertEquals(IndexState.NORMAL, index.getState()); Assert.assertTrue(index.visibleForTransaction(0)); Assert.assertTrue(index.visibleForTransaction(10)); index = new Ma...
public void updateFromOther(FeedItem other) { if (other.imageUrl != null) { this.imageUrl = other.imageUrl; } if (other.title != null) { title = other.title; } if (other.getDescription() != null) { description = other.getDescription(); ...
@Test public void testUpdateFromOther_feedItemImageDownloadUrlChanged() { setNewFeedItemImageDownloadUrl(); original.updateFromOther(changedFeedItem); assertFeedItemImageWasUpdated(); }
@NonNull @Override public HealthResponse healthResponse(final Map<String, Collection<String>> queryParams) { final String type = queryParams.getOrDefault(CHECK_TYPE_QUERY_PARAM, Collections.emptyList()) .stream() .findFirst() .orElse(null); final Collection<H...
@Test void shouldHandleMultipleHealthStateViewsCorrectly() throws IOException { // given final HealthStateView fooView = new HealthStateView("foo", true, HealthCheckType.READY, true); final HealthStateView barView = new HealthStateView("bar", true, HealthCheckType.ALIVE, true); final...
@Override public void process(Exchange exchange) throws Exception { JsonElement json = getBodyAsJsonElement(exchange); String operation = exchange.getIn().getHeader(CouchDbConstants.HEADER_METHOD, String.class); if (ObjectHelper.isEmpty(operation)) { Response<DocumentResult> save...
@Test void testDeleteResponse() throws Exception { String id = UUID.randomUUID().toString(); String rev = UUID.randomUUID().toString(); Document doc = new Document.Builder() .id(id) .add("_rev", rev) .build(); DocumentResult documentR...
public void setCookie(String name, String value) { Cookie cookie = new Cookie(name, value); setCookies(List.of(cookie)); }
@Test void testSetCookie() { URI uri = URI.create("http://example.com/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); HttpResponse httpResp = newResponse(httpReq, 200); DiscFilterResponse response = new DiscFilterResponse(httpResp)...
public static <T> T convert(Class<T> type, Object value) throws ConvertException { return convert((Type) type, value); }
@Test public void toSqlDateTest() { final java.sql.Date date = Convert.convert(java.sql.Date.class, DateUtil.parse("2021-07-28")); assertEquals("2021-07-28", date.toString()); }
@Override public void write(final MySQLPacketPayload payload, final Object value) { if (value instanceof byte[]) { payload.writeBytesLenenc((byte[]) value); } else { payload.writeStringLenenc(value.toString()); } }
@Test void assertWriteByteArray() { new MySQLStringLenencBinaryProtocolValue().write(payload, new byte[]{}); verify(payload).writeBytesLenenc(new byte[]{}); }
public List<IssueDto> sort() { String sort = query.sort(); Boolean asc = query.asc(); if (sort != null && asc != null) { return getIssueProcessor(sort).sort(issues, asc); } return issues; }
@Test public void should_fail_to_sort_with_unknown_sort() { IssueQuery query = mock(IssueQuery.class); when(query.sort()).thenReturn("unknown"); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(null, query); try { issuesFinderSort.sort(); } catch (Exception e) { assertThat(e).i...
@Transactional public long createReview(CreateReviewRequest request) { ReviewGroup reviewGroup = validateReviewGroupByRequestCode(request.reviewRequestCode()); Template template = templateRepository.findById(reviewGroup.getTemplateId()) .orElseThrow(() -> new TemplateNotFoundByReview...
@Test void 적정_글자수인_텍스트_응답인_경우_정상_저장된다() { // given String reviewRequestCode = "0000"; reviewGroupRepository.save(new ReviewGroup("리뷰어", "프로젝트", reviewRequestCode, "12341234")); Section section = sectionRepository.save(new Section(VisibleType.ALWAYS, List.of(1L), 1L, "섹션명", "말머리", 1))...
public void createTask(CreateTaskRequest request) throws Throwable { taskManager.createTask(request.id(), request.spec()); }
@Test public void testNetworkPartitionFault() throws Exception { CapturingCommandRunner runner = new CapturingCommandRunner(); MockTime time = new MockTime(0, 0, 0); Scheduler scheduler = new MockScheduler(time); try (MiniTrogdorCluster cluster = new MiniTrogdorCluster.Builder(). ...
public static String prepareMillisCheckFailMsgPrefix(final Object value, final String name) { return format(MILLISECOND_VALIDATION_FAIL_MSG_FRMT, name, value); }
@Test public void shouldContainsNameAndValueInFailMsgPrefix() { final String failMsgPrefix = prepareMillisCheckFailMsgPrefix("someValue", "variableName"); assertThat(failMsgPrefix, containsString("variableName")); assertThat(failMsgPrefix, containsString("someValue")); }
private void updateServiceInstance(ExecuteContext context) { final Object result = context.getResult(); if (result instanceof Optional) { Optional<?> serverInstanceOption = (Optional<?>) result; if (!serverInstanceOption.isPresent()) { return; } ...
@Test public void testBefore() throws Exception { final Interceptor interceptor = getInterceptor(); final ExecuteContext context = interceptor.before(TestHelper.buildDefaultContext()); assertNull(context.getResult()); final RetryRule retryRule = new RetryRule(); retryRule.set...
public static boolean containsUrl(String text) { return CONTAINS_URL_TEST.matcher(text).matches(); }
@Test public void testContainsUrl() { String text = "Test of https://github.com"; assertTrue(UrlStringUtils.containsUrl(text)); text = "Test of github.com"; assertFalse(UrlStringUtils.containsUrl(text)); }
@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 shouldHandleZero() { assertThat(udf.radians(0), closeTo(0.0, 0.000000000000001)); assertThat(udf.radians(0L), closeTo(0.0, 0.000000000000001)); assertThat(udf.radians(0.0), closeTo(0.0, 0.000000000000001)); }
@Override public boolean containsGangs() { return hasGang; }
@Test public void testZeroAlloaction() { ReservationId reservationID = ReservationId.newInstance(rand.nextLong(), rand.nextLong()); int[] alloc = {}; long start = 0; ReservationDefinition rDef = ReservationSystemTestUtil.createSimpleReservationDefinition( start, start + all...
public BigDecimal calculateTDEE(ActiveLevel activeLevel) { if(activeLevel == null) return BigDecimal.valueOf(0); BigDecimal multiplayer = BigDecimal.valueOf(activeLevel.getMultiplayer()); return multiplayer.multiply(BMR).setScale(2, RoundingMode.HALF_DOWN); }
@Test void calculateTDEE_null() { BigDecimal TDEE = bmrCalculator.calculate(attributes).calculateTDEE(null); assertEquals(new BigDecimal("0"), TDEE); }
public boolean isUnqualifiedShorthandProjection() { if (1 != projections.size()) { return false; } Projection projection = projections.iterator().next(); return projection instanceof ShorthandProjection && !((ShorthandProjection) projection).getOwner().isPresent(); }
@Test void assertUnqualifiedShorthandProjectionWithEmptyItems() { ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.emptySet()); assertFalse(projectionsContext.isUnqualifiedShorthandProjection()); }
public void addAuditMessage(int messageIndex, String decisionOrRuleName, String result) { auditLogLines.add(new AuditLogLine(scenarioWithIndex.getIndex(), scenarioWithIndex.getScesimData().getDescription(), messageIndex, decisionOrRuleName, result)); }
@Test public void addAuditMessage() { scenarioResultMetadata.addAuditMessage(1, "decisionName", SUCCEEDED.toString()); assertThat(scenarioResultMetadata.getAuditLogLines()).hasSize(1); commonCheckAuditLogLine(scenarioResultMetadata.getAuditLogLines().get(0), "decisionName", SUCCEEDE...
@VisibleForTesting static UTypeParameter create(CharSequence name, UExpression... bounds) { return create(name, ImmutableList.copyOf(bounds), ImmutableList.<UAnnotation>of()); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UTypeParameter.create("T")) .addEqualityGroup(UTypeParameter.create("E")) .addEqualityGroup(UTypeParameter.create("T", UClassIdent.create("java.lang.CharSequence"))) .addEqualityGroup(UTypeParameter.create("T", UCl...
public static WhitelistConfig load() { return new WhitelistConfig(); }
@Test public void testConfigJsonFormat() { WhitelistConfig config = WhitelistConfig.load("whitelist-json"); System.out.println(config); }
public SubscriptionStatsImpl add(SubscriptionStatsImpl stats) { Objects.requireNonNull(stats); this.msgRateOut += stats.msgRateOut; this.msgThroughputOut += stats.msgThroughputOut; this.bytesOutCounter += stats.bytesOutCounter; this.msgOutCounter += stats.msgOutCounter; t...
@Test public void testAdd_EarliestMsgPublishTimeInBacklogs_Zero() { SubscriptionStatsImpl stats1 = new SubscriptionStatsImpl(); stats1.earliestMsgPublishTimeInBacklog = 0L; SubscriptionStatsImpl stats2 = new SubscriptionStatsImpl(); stats2.earliestMsgPublishTimeInBacklog = 0L; ...
public String getText(final Entry entry) { if (entry.getAttribute(TEXT) != null) return (String) entry.getAttribute(TEXT); else { final String textKey = (String) entry.getAttribute(TEXT_KEY); if (textKey != null) return resourceAccessor.getRawText(textKey); else { final AFreeplaneAction action =...
@Test public void getsTextFromEntryAttributeText() throws Exception { entry.setAttribute("text", "entry text"); final String entryText = entryAccessor.getText(entry); assertThat(entryText, equalTo("entry text")); }
public Account changeNumber(final Account account, final String number, @Nullable final IdentityKey pniIdentityKey, @Nullable final Map<Byte, ECSignedPreKey> deviceSignedPreKeys, @Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys, @Nullable final List<IncomingMessage> deviceMes...
@Test void changeNumberSetPrimaryDevicePrekey() throws Exception { Account account = mock(Account.class); when(account.getNumber()).thenReturn("+18005551234"); final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair(); final IdentityKey pniIdentityKey = new IdentityKey(Curve.generateKeyPair().getPu...
public static Object applyLogicalType(Schema.Field field, Object value) { if (field == null || field.schema() == null) { return value; } Schema fieldSchema = resolveUnionSchema(field.schema()); return applySchemaTypeLogic(fieldSchema, value); }
@Test public void testLogicalTypesWithUnionSchema() { String valString1 = "125.24350000"; ByteBuffer amount1 = decimalToBytes(new BigDecimal(valString1), 8); // union schema for the logical field with "null" and "decimal" as types String fieldSchema1 = "{\"type\":\"record\",\"name\":\"Event\",\"fields...
@Override public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) { if (param.getDeliveryType() == null) { return; } if (DeliveryTypeEnum.PICK_UP.getType().equals(param.getDeliveryType())) { calculateByPickUp(param); } else if (...
@Test @DisplayName("按件计算运费不包邮的情况") public void testCalculate_expressTemplateCharge() { // SKU 1 : 100 * 2 = 200 // SKU 2 :200 * 10 = 2000 // 运费 首件 1000 + 续件 2000 = 3000 // mock 方法 when(deliveryExpressTemplateService.getExpressTemplateMapByIdsAndArea(eq(asSet(1L)), eq(1...
public Future<Void> reconcile(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets, Clock clock) { return serviceAccount() .compose(i -> entityOperatorRole()) .compose(i -> topicOperatorRole()) .compose(i -> userOper...
@Test public void reconcileWithoutUoAndTo(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false); DeploymentOperator mockDepOps = supplier.deploymentOperations; SecretOperator mockSecretOps = supplier.secretOperations; ServiceAccountOpe...
public static Builder forMagic(byte magic, ProduceRequestData data) { // Message format upgrades correspond with a bump in the produce request version. Older // message format versions are generally not supported by the produce request versions // following the bump. final short minVers...
@Test public void testMixedTransactionalData() { final long producerId = 15L; final short producerEpoch = 5; final int sequence = 10; final MemoryRecords nonTxnRecords = MemoryRecords.withRecords(Compression.NONE, new SimpleRecord("foo".getBytes())); final Me...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test public void testDoubleParen() { final Predicate parsed = PredicateExpressionParser.parse("((com.linkedin.data.it.AlwaysTruePredicate))"); Assert.assertEquals(parsed.getClass(), AlwaysTruePredicate.class); }
public Future<KafkaCluster> prepareKafkaCluster( Kafka kafkaCr, List<KafkaNodePool> nodePools, Map<String, Storage> oldStorage, Map<String, List<String>> currentPods, KafkaVersionChange versionChange, KafkaStatus kafkaStatus, boolean tr...
@Test public void testCorrectRoleChangeWithKRaft(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false); // Mock brokers-in-use check BrokersInUseCheck brokersInUseOps = supplier.brokersInUseCheck; when(brokersInUseOps.brokersInUse(any...
public Collection<V> remove(K key) { List<V> removed = data.remove(key); if (removed != null) { for (V val : removed) { inverse.remove(val); } } return removed; }
@Test public void testRemoveValue() { boolean rc = map.remove(42); assertThat(rc, is(true)); assertSize(0); }
@Override public void write(Message message) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Writing message id to [{}]: <{}>", NAME, message.getId()); } writeMessageEntries(List.of(DefaultFilteredMessage.forDestinationKeys(message, Set.of(FILTER_KEY)))); }
@Test public void writeListWithMultipleStreams() throws Exception { final List<Message> messageList = buildMessages(4); // The bulkIndex method should receive a separate message per stream/index-set. If a message has two streams // with two different index sets, we should see the same messa...
public static void clean( Object func, ExecutionConfig.ClosureCleanerLevel level, boolean checkSerializable) { clean(func, level, checkSerializable, Collections.newSetFromMap(new IdentityHashMap<>())); }
@Test void testSerializable() throws Exception { MapCreator creator = new SerializableMapCreator(1); MapFunction<Integer, Integer> map = creator.getMap(); ClosureCleaner.clean(map, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true); int result = map.map(3); assertThat(res...
@Override public double score(int[] truth, int[] prediction) { return of(truth, prediction, strategy); }
@Test public void testMicro() { System.out.println("Micro-Recall"); int[] truth = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
@Override public ByteBuf slice() { return newSharedLeakAwareByteBuf(super.slice()); }
@Test public void testWrapSlice() { assertWrapped(newBuffer(8).slice()); }
public RulesDefinition.Context load() { RulesDefinition.Context context = new RulesDefinitionContext(); for (RulesDefinition pluginDefinition : pluginDefs) { context.setCurrentPluginKey(serverPluginRepository.getPluginKey(pluginDefinition)); pluginDefinition.define(context); } context.setCur...
@Test public void load_definitions() { RulesDefinition.Context context = new RuleDefinitionsLoader(mock(ServerPluginRepository.class), new RulesDefinition[] { new FindbugsDefinitions(), new JavaDefinitions() }).load(); assertThat(context.repositories()).hasSize(2); assertThat(context....
public static Storage.Builder newStorageClient(GcsOptions options) { String applicationName = String.format( "%sapache-beam/%s (GPN:Beam)", isNullOrEmpty(options.getAppName()) ? "" : options.getAppName() + " ", ReleaseInfo.getReleaseInfo().getSdkVersion()); String se...
@Test public void testUserAgentAndCustomAuditInGcsRequestHeaders() throws IOException { GcsOptions gcsOptions = PipelineOptionsFactory.as(GcsOptions.class); gcsOptions.setGcpCredential(new TestCredential()); gcsOptions.setJobName("test-job"); gcsOptions.setAppName("test-app"); Storage storageClie...
@Override public void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { // Charset is a global setting on Oracle, it can't be set on a specified schema with a // different value. To not block users who already have a SonarQube schema, charset // is verified only on fr...
@Test public void fresh_install_supports_al32utf8() throws Exception { answerCharset("AL32UTF8"); underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL); }
@Override public MergeAppend appendFile(DataFile file) { add(file); return this; }
@TestTemplate public void testDataSpecThrowsExceptionIfDataFilesWithDifferentSpecsAreAdded() { assertThat(listManifestFiles()).as("Table should start empty").isEmpty(); TableMetadata base = readMetadata(); assertThat(base.currentSnapshot()).as("Should not have a current snapshot").isNull(); assertTha...
@Override public String toString() { if (this.equals(UNKNOWN)) { return "ResourceProfile{UNKNOWN}"; } if (this.equals(ANY)) { return "ResourceProfile{ANY}"; } return "ResourceProfile{" + getResourceString() + (extended...
@Test void includesCPUAndMemoryInToStringIfTheyAreBelowThreshold() { ResourceProfile resourceProfile = createResourceProfile(1.0, MemorySize.ofMebiBytes(4)); assertThat(resourceProfile.toString()).contains("cpuCores=").contains("taskHeapMemory="); }
protected static Map<String, String> getFilterParameters(Configuration conf, String prefix) { Map<String, String> filterParams = new HashMap<String, String>(); for (Map.Entry<String, String> entry : conf.getValByRegex(prefix) .entrySet()) { String name = entry.getKey(); String value = ...
@Test public void testGetFilterParameters() { // Initialize configuration object Configuration conf = new Configuration(); conf.set(HttpCrossOriginFilterInitializer.PREFIX + "rootparam", "rootvalue"); conf.set(HttpCrossOriginFilterInitializer.PREFIX + "nested.param", "nestedvalue"); ...