focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public double calculateAveragePercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) { int skippedResourceTypes = 0; double total = 0.0; if (usedMemoryMb > totalMemoryMb) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); }...
@Test public void testCalculateAvgUsageWithNoResourcesInTotal() { NormalizedResources resources = new NormalizedResources(normalize(Collections.emptyMap())); NormalizedResources usedResources = new NormalizedResources(normalize(Collections.emptyMap())); double avg = resources.calcul...
public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ...
@Test public void testRetriesOnConnectionFailure() throws Exception { MRClientProtocol historyServerProxy = mock(MRClientProtocol.class); when(historyServerProxy.getJobReport(getJobReportRequest())).thenThrow( new RuntimeException("1")).thenThrow(new RuntimeException("2")) .thenReturn(...
static String isHostParam(final String given) { final String hostUri = StringHelper.notEmpty(given, "host"); final Matcher matcher = HOST_PATTERN.matcher(given); if (!matcher.matches()) { throw new IllegalArgumentException( "host must be an absolute URI (e.g. ht...
@Test public void shouldReturnUriParameter() { assertThat(RestOpenApiHelper.isHostParam("http://api.example.com")).isEqualTo("http://api.example.com"); }
public void printStreamedRow(final StreamedRow row) { row.getErrorMessage().ifPresent(this::printErrorMessage); row.getFinalMessage().ifPresent(finalMsg -> writer().println(finalMsg)); row.getHeader().ifPresent(this::printRowHeader); if (row.getRow().isPresent()) { switch (outputFormat) { ...
@Test public void testPrintDataRow() { // Given: final StreamedRow row = StreamedRow.pushRow(genericRow("col_1", "col_2")); // When: console.printStreamedRow(row); // Then: assertThat(terminal.getOutputString(), containsString("col_1")); assertThat(terminal.getOutputString(), containsStr...
public static String nullifyIfEmptyTrimmed(final String input) { if (input == null) { return null; } String trimmed = input.trim(); if (trimmed.length() == 0) { return null; } return trimmed; }
@Test public void testNullifyIfEmptyTrimmed() { assertNull(JOrphanUtils.nullifyIfEmptyTrimmed(null)); assertNull(JOrphanUtils.nullifyIfEmptyTrimmed("\u0001")); assertEquals("1234", JOrphanUtils.nullifyIfEmptyTrimmed("1234")); }
public synchronized LogAction record(double... values) { return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values); }
@Test public void testLoggingWithMultipleValues() { assertTrue(helper.record(1).shouldLog()); for (int i = 0; i < 4; i++) { timer.advance(LOG_PERIOD / 5); int base = i % 2 == 0 ? 0 : 1; assertFalse(helper.record(base, base * 2).shouldLog()); } timer.advance(LOG_PERIOD); LogActi...
@Override public double getStdDev() { // two-pass algorithm for variance, avoids numeric overflow if (values.length <= 1) { return 0; } final double mean = getMean(); double sum = 0; for (long value : values) { final double diff = value - me...
@Test public void calculatesAStdDevOfZeroForASingletonSnapshot() { final Snapshot singleItemSnapshot = new UniformSnapshot(new long[]{1}); assertThat(singleItemSnapshot.getStdDev()) .isZero(); }
@Override public SchemaAndValue get(final ProcessingLogConfig config) { final Struct struct = new Struct(ProcessingLogMessageSchema.PROCESSING_LOG_SCHEMA) .put(ProcessingLogMessageSchema.TYPE, MessageType.SERIALIZATION_ERROR.getTypeId()) .put(ProcessingLogMessageSchema.SERIALIZATION_ERROR, seriali...
@Test public void shouldBuildErrorWithKeyComponent() { // Given: final SerializationError<GenericRow> serError = new SerializationError<>(ERROR, Optional.of(RECORD), TOPIC, true); // When: final SchemaAndValue msg = serError.get(LOGGING_CONFIG); // Then: final Struct struct = (Struct...
public static SupportLevel defaultSupportLevel(String firstVersion, String currentVersion) { if (firstVersion == null || firstVersion.isEmpty()) { throw new IllegalArgumentException( "FirstVersion is not specified. This can be done in @UriEndpoint or in pom.xml file."); }...
@Test public void testStable() { Assertions.assertNotEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.20.0")); Assertions.assertEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.21.0")); Assertions.assertEquals(SupportLevel.Stable,...
@Override public String name() { return name; }
@Test public void testValidDomainNameUmlaut() { String name = "ä"; AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { }; assertEquals("xn--4ca.", record.name()); }
@Override public int actionSave(String fileName, String appName, Long lifetime, String queue) throws IOException, YarnException { int result = EXIT_SUCCESS; try { Service service = loadAppJsonFromLocalFS(fileName, appName, lifetime, queue); service.setState(ServiceState.STOPPED); ...
@Test void testSave() { String fileName = "target/test-classes/example-app.json"; String appName = "example-app"; long lifetime = 3600L; String queue = "default"; try { int result = asc.actionSave(fileName, appName, lifetime, queue); assertEquals(EXIT_SUCCESS, result); } catch (IOE...
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KST...
@Test public void shouldCreateWindowedStreamSourceWithNewPseudoColumnVersionIfNoOldQuery() { // Given: givenWindowedStream(); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSource, contextStacker ); // Then: assertThat...
@Description("Given a geometry and a zoom level, returns the minimum set of Bing tiles of that zoom level that fully covers that geometry") @ScalarFunction("geometry_to_bing_tiles") @SqlType("array(" + BingTileType.NAME + ")") public static Block geometryToBingTiles(@SqlType(GEOMETRY_TYPE_NAME) Slice input,...
@Test public void testGeometryToBingTiles() throws Exception { // Geometries at boundaries of tiles assertGeometryToBingTiles("POINT (0 0)", 1, ImmutableList.of("3")); assertGeometryToBingTiles(format("POINT (%s 0)", MIN_LONGITUDE), 1, ImmutableList.of("2")); assertGe...
public List<PluginConfiguration> getSecretsConfigMetadata(String pluginId) { return getVersionedSecretsExtension(pluginId).getSecretsConfigMetadata(pluginId); }
@Test void getSecretsConfigMetadata_shouldDelegateToVersionedExtension() { SecretsExtensionV1 secretsExtensionV1 = mock(SecretsExtensionV1.class); Map<String, VersionedSecretsExtension> secretsExtensionMap = Map.of("1.0", secretsExtensionV1); extension = new SecretsExtension(pluginManager, e...
void runOnce() { processApplicationEvents(); final long currentTimeMs = time.milliseconds(); final long pollWaitTimeMs = requestManagers.entries().stream() .filter(Optional::isPresent) .map(Optional::get) .map(rm -> rm.poll(currentTimeMs)) ...
@Test public void testRunOnceInvokesReaper() { consumerNetworkThread.runOnce(); verify(applicationEventReaper).reap(any(Long.class)); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldFetchWithOnlyStartBounds_fetchAll() { // When: table.get(PARTITION, WINDOW_START_BOUNDS, Range.all()); // Then: verify(cacheBypassFetcherAll).fetchAll( eq(tableStore), eq(WINDOW_START_BOUNDS.lowerEndpoint()), eq(WINDOW_START_BOUNDS.upperEndpoint()) ...
@Override public Object convert(String value) { if (value == null || value.isEmpty()) { return value; } return p.matcher(value).replaceAll(REPLACEMENT); }
@Test public void testConvert() throws Exception { Converter hc = new IPAnonymizerConverter(new HashMap<String, Object>()); assertNull(hc.convert(null)); assertEquals("", hc.convert("")); assertEquals("lol no IP in here", hc.convert("lol no IP in here")); assertEquals("127.0...
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) { return decorateTextWithHtml(text, decorationDataHolder, null, null); }
@Test public void should_decorate_multiple_lines_characters_range() { String firstCommentLine = "/*"; String secondCommentLine = " * Test"; String thirdCommentLine = " */"; String blockComment = firstCommentLine + LF_END_OF_LINE + secondCommentLine + LF_END_OF_LINE + thirdCommentLine + L...
@Override public boolean createEmptyObject(String key) { try { ObjectMetadata objMeta = new ObjectMetadata(); objMeta.setContentLength(0); mClient.putObject(mBucketNameInternal, key, new ByteArrayInputStream(new byte[0]), objMeta); return true; } catch (CosClientException e) { LO...
@Test public void testCreateEmptyObject() { // test successful create empty object Mockito.when(mClient.putObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(InputStream.class), ArgumentMatchers.any(ObjectMetadata.class))) .thenReturn(null); boolean res...
@VisibleForTesting Optional<Method> getGetContainersFromPreviousAttemptsMethod() { return getContainersFromPreviousAttemptsMethod; }
@Test void testGetContainersFromPreviousAttemptsMethodReflectiveHadoop22() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG); assertThat( ...
public Blob build() throws IOException { UniqueTarArchiveEntries uniqueTarArchiveEntries = new UniqueTarArchiveEntries(); // Adds all the layer entries as tar entries. for (FileEntry layerEntry : layerEntries) { // Adds the entries to uniqueTarArchiveEntries, which makes sure all entries are unique a...
@Test public void testBuild_permissions() throws IOException { Path testRoot = temporaryFolder.getRoot().toPath(); Path folder = Files.createDirectories(testRoot.resolve("files1")); Path fileA = createFile(testRoot, "fileA", "abc", 54321); Path fileB = createFile(testRoot, "fileB", "def", 54321); ...
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException e) { return null; } catch (JMException e) { return null; } }
@Test public void returnsJmxAttribute() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); assertThat(gauge.getValue()).isInstanceOf(Integer.class); a...
@NonNull public Client authenticate(@NonNull Request request) { // https://datatracker.ietf.org/doc/html/rfc7521#section-4.2 try { if (!CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT.equals(request.clientAssertionType())) { throw new AuthenticationException( "unsupported client_assertion_ty...
@Test void authenticate_badSubject() throws JOSEException { var key = generateKey(); var jwkSource = new StaticJwkSource<>(key); var claims = new JWTClaimsSet.Builder() .audience(RP_ISSUER.toString()) .subject("not the right client") .issuer(CLIENT_ID) ...
@Override public void close() throws IOException { this.closed = true; writer.close(); }
@TestTemplate public void testRollingManifestWriterNoRecords() throws IOException { RollingManifestWriter<DataFile> writer = newRollingWriteManifest(SMALL_FILE_SIZE); writer.close(); assertThat(writer.toManifestFiles()).isEmpty(); writer.close(); assertThat(writer.toManifestFiles()).isEmpty(); ...
protected long getCurrentTimeMillis() { return System.currentTimeMillis(); }
@Test void givenActivityHappened_whenRecordActivity_thenShouldDelegateToOnActivity() { // GIVEN TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder() .setSessionIdMSB(SESSION_ID.getMostSignificantBits()) .setSessionIdLSB(SESSION_...
@Override public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) { selectedBundlesCache.clear(); final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0; final Map<String, Long> recentlyUnlo...
@Test public void testBrokerNotOverloaded() { LoadData loadData = new LoadData(); LocalBrokerData broker1 = new LocalBrokerData(); broker1.setBandwidthIn(new ResourceUsage(500, 1000)); broker1.setBandwidthOut(new ResourceUsage(500, 1000)); broker1.setBundles(Sets.newHashSet(...
DistCh(Configuration conf) { super(createJobConf(conf)); }
@Test public void testDistCh() throws Exception { final Configuration conf = new Configuration(); conf.set(CapacitySchedulerConfiguration.PREFIX+CapacitySchedulerConfiguration.ROOT+"."+CapacitySchedulerConfiguration.QUEUES, "default"); conf.set(CapacitySchedulerConfiguration.PREFIX+CapacitySchedulerConfi...
public static String createJobName(String prefix) { return createJobName(prefix, 0); }
@Test public void testCreateJobNameWithUppercase() { assertThat(createJobName("testWithUpperCase")).matches("test-with-upper-case-\\d{17}"); }
public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length) { checkNotNull(a, "a"); checkNotNull(b, "b"); // All indexes and lengths must be non-negative checkPositiveOrZero(aStartIndex, "aStartIndex"); checkPositiveOrZero(bStartIndex, "bStart...
@Test public void equalsBufferSubsections() { byte[] b1 = new byte[128]; byte[] b2 = new byte[256]; Random rand = new Random(); rand.nextBytes(b1); rand.nextBytes(b2); final int iB1 = b1.length / 2; final int iB2 = iB1 + b1.length; final int length = b...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void macosFailedToFindServicePortForDisplay() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/macos_failed_to_find_service_port_for_display.txt")), CrashReportAnalyzer.Rule.MACOS_FAILED_TO_FIND...
@Override public KTable<Windowed<K>, V> reduce(final Reducer<V> reducer) { return reduce(reducer, NamedInternal.empty()); }
@Test public void shouldMaterializeReduced() { windowedStream.reduce( MockReducer.STRING_ADDER, Materialized.<String, String, WindowStore<Bytes, byte[]>>as("reduced") .withKeySerde(Serdes.String()) .withValueSerde(Serdes.String())); try (final...
public static IntStream allLinesFor(DefaultIssue issue, String componentUuid) { DbIssues.Locations locations = issue.getLocations(); if (locations == null) { return IntStream.empty(); } Stream<DbCommons.TextRange> textRanges = Stream.concat( locations.hasTextRange() ? Stream.of(locations.ge...
@Test public void allLinesFor_filters_lines_for_specified_component() { DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); locations.addFlowBuilder() .addLocation(newLocation("file1", 5, 5)) .addLocation(newLocation("file1", 10, 12)) .addLocation(newLocation("file1", 15,...
public DataConnectionConfig load(DataConnectionConfig dataConnectionConfig) { // Make a copy to preserve the original configuration DataConnectionConfig loadedConfig = new DataConnectionConfig(dataConnectionConfig); // Try XML file first if (loadConfig(loadedConfig, HazelcastDataConnect...
@Test public void testLoadXml() { DataConnectionConfig dataConnectionConfig = new DataConnectionConfig(); Path path = Paths.get("src", "test", "resources", "hazelcast-client-test-external.xml"); dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_XML_PATH, path.toString()); ...
public static void processEnvVariables(Map<String, String> inputProperties) { processEnvVariables(inputProperties, System.getenv()); }
@Test void ignoreEmptyValueForJsonEnv() { var inputProperties = new HashMap<String, String>(); EnvironmentConfig.processEnvVariables(inputProperties, Map.of("SONAR_SCANNER_JSON_PARAMS", "")); assertThat(inputProperties).isEmpty(); }
public static double minimize(DifferentiableMultivariateFunction func, double[] x, double gtol, int maxIter) { if (gtol <= 0.0) { throw new IllegalArgumentException("Invalid gradient tolerance: " + gtol); } if (maxIter <= 0) { throw new IllegalArgumentException("Invalid ...
@Test public void testBFGS() { System.out.println("BFGS"); double[] x = new double[100]; for (int j = 1; j <= x.length; j += 2) { x[j - 1] = -1.2; x[j] = 1.2; } double result = BFGS.minimize(func, x, 1E-5, 500); System.out.println(Arrays.toSt...
public T value() { return value; }
@Test public final void testValue() { final Integer n = 42; Timestamped<Integer> tsv = new Timestamped<>(n, TS_1_1); assertSame(n, tsv.value()); }
public static double GroundResolution(final double latitude, final int levelOfDetail) { return GroundResolution(latitude, (double) levelOfDetail); }
@Test public void test_groundResolution() { final double delta = 1e-4; for (int zoomLevel = mMinZoomLevel; zoomLevel <= mMaxZoomLevel; zoomLevel++) { Assert.assertEquals(156543.034 / (1 << zoomLevel), TileSystem.GroundResolution(0, zoomLevel), delta); } }
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest req) { var now = clock.instant(); var bearerToken = requestBearerToken(req).orElse(null); if (bearerToken == null) { log.fine("Missing bearer token"); return Optional.of(new ErrorResponse(Response.St...
@Test void fails_for_unknown_token() { var req = FilterTestUtils.newRequestBuilder() .withMethod(Method.GET) .withHeader("Authorization", "Bearer " + UNKNOWN_TOKEN.secretTokenString()) .build(); var responseHandler = new MockResponseHandler(); ...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldParseArbitraryExpressions() { // Given: final String statementString = "INSERT INTO ADDRESS VALUES (2 + 1);"; final Statement statement = KsqlParserTestUtil.buildSingleAst(statementString, metaStore).getStatement(); // When: final String result = SqlFormatter.formatSql(sta...
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBuildSourceStreamWithCorrectParamsWhenBuildingTable() { // Given: givenNodeWithMockSource(); // When: node.buildStream(buildContext); // Then: verify(schemaKStreamFactory).create( same(buildContext), same(dataSource), stackerCaptor.capture() ...
public String getNextId() { return String.format("%s-%d-%d", prefix, generatorInstanceId, counter.getAndIncrement()); }
@Test public void simple() throws Exception { DistributedIdGenerator gen1 = new DistributedIdGenerator(coordinationService, "/my/test/simple", "p"); assertEquals(gen1.getNextId(), "p-0-0"); assertEquals(gen1.getNextId(), "p-0-1"); assertEquals(gen1.getNextId(), "p-0-2"); ass...
@Override public void filter(ContainerRequestContext req) throws IOException { TrackedByGauge trackedByGauge = _resourceInfo.getResourceMethod().getAnnotation(TrackedByGauge.class); if (trackedByGauge != null) { _controllerMetrics.addValueToGlobalGauge(trackedByGauge.gauge(), 1L); } }
@Test public void testContainerRequestFilterIncrementsGauge() throws Exception { Method methodOne = TrackedClass.class.getDeclaredMethod("trackedMethod"); when(_resourceInfo.getResourceMethod()).thenReturn(methodOne); _interceptor.filter(_containerRequestContext); verify(_controllerMetrics) ...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void banChatSenderChat() { BaseResponse response = bot.execute(new BanChatSenderChat(channelName, memberBot)); assertTrue(response.isOk()); }
public static void stopProxy(Object proxy) { if (proxy == null) { throw new HadoopIllegalArgumentException( "Cannot close proxy since it is null"); } try { if (proxy instanceof Closeable) { ((Closeable) proxy).close(); return; } else { InvocationHandler ha...
@Test public void testStopProxy() throws IOException { RPC.setProtocolEngine(conf, StoppedProtocol.class, StoppedRpcEngine.class); StoppedProtocol proxy = RPC.getProxy(StoppedProtocol.class, StoppedProtocol.versionID, null, conf); StoppedInvocationHandler invocationHandler = (StoppedInvoc...
@Override public LocalResourceId resolve(String other, ResolveOptions resolveOptions) { checkState(isDirectory(), "Expected the path is a directory, but had [%s].", pathString); checkArgument( resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) || resolveOptions.equals(StandardResol...
@Test public void testResolveInvalidNotDirectory() { // TODO: Java core test failing on windows, https://github.com/apache/beam/issues/20477 assumeFalse(SystemUtils.IS_OS_WINDOWS); ResourceId tmp = toResourceIdentifier("/root/").resolve("tmp", StandardResolveOptions.RESOLVE_FILE); thrown.expec...
public static boolean isPlainHttp(NetworkService networkService) { checkNotNull(networkService); var isWebService = isWebService(networkService); var isKnownServiceName = IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey( Ascii.toLowerCase(networkService.getServiceName())); var doesNotSup...
@Test public void isPlainHttp_whenHttpServiceFromHttpMethodsWithoutSslVersions_returnsTrue() { assertThat( NetworkServiceUtils.isPlainHttp( NetworkService.newBuilder() .setServiceName("ssh") .addSupportedHttpMethods("GET") .bu...
public static String createErrorMessage(HttpException exception) { String json = tryParseAsJsonError(exception.content()); if (json != null) { return json; } String msg = "HTTP code " + exception.code(); if (isHtml(exception.content())) { return msg; } return msg + ": " + Strin...
@Test public void createErrorMessage_whenHtml_shouldCreateErrorMsg() { String content = "<!DOCTYPE html><html>something</html>"; assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).isEqualTo("HTTP code 400"); }
public List<Stream> match(Message message) { final Set<Stream> result = Sets.newHashSet(); final Set<String> blackList = Sets.newHashSet(); for (final Rule rule : rulesList) { if (blackList.contains(rule.getStreamId())) { continue; } final St...
@Test public void testContainsMatch() throws Exception { final StreamMock stream = getStreamMock("test"); final StreamRuleMock rule = new StreamRuleMock(ImmutableMap.of( "_id", new ObjectId(), "field", "testfield", "value", "testvalue", ...
public void onNotify(String tag, int id, final Notification notification) { if (this.customizeEnable) { try { if (notification.contentIntent != null) { SALog.i(TAG, "onNotify, tag: " + tag + ", id=" + id); final NotificationInfo push = getNotif...
@Test public void onNotify() { SAHelper.initSensors(mApplication); Notification notification = new Notification(); notification.contentIntent = MockDataTest.mockPendingIntent(); // notification.extras.putString("android.title", "notifyTitle"); // notification.extras.putString("...
public static BlendMode getInstance(COSBase cosBlendMode) { BlendMode result = null; if (cosBlendMode instanceof COSName) { result = BLEND_MODES.get(cosBlendMode); } else if (cosBlendMode instanceof COSArray) { COSArray cosBlendModeArray = (COS...
@Test void testInstances() { assertEquals(BlendMode.NORMAL, BlendMode.getInstance(COSName.NORMAL)); assertEquals(BlendMode.NORMAL, BlendMode.getInstance(COSName.COMPATIBLE)); assertEquals(BlendMode.MULTIPLY, BlendMode.getInstance(COSName.MULTIPLY)); assertEquals(BlendMode.SCREEN,...
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testCleanupNoParams() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap("{}"); Map<String, ParamDefinition> cleanedParams = ParamsMergeHelper.cleanupParams(allParams); assertEquals(0, cleanedParams.size()); }
public void updateFileStore(FileStoreInfo fsInfo) throws DdlException { try { client.updateFileStore(fsInfo, serviceId); } catch (StarClientException e) { throw new DdlException("Failed to update file store, error: " + e.getMessage()); } }
@Test public void testUpdateFileStore() throws StarClientException, DdlException { S3FileStoreInfo s3FsInfo = S3FileStoreInfo.newBuilder() .setRegion("region").setEndpoint("endpoint").build(); FileStoreInfo fsInfo = FileStoreInfo.newBuilder().setFsKey("test-fskey") .s...
public RunConfigurationExecutor getExecutor( String type ) { RunConfigurationProvider runConfigurationProvider = getProvider( type ); if ( runConfigurationProvider != null ) { return runConfigurationProvider.getExecutor(); } return null; }
@Test public void testGetExecutor() { DefaultRunConfigurationExecutor defaultRunConfigurationExecutor = (DefaultRunConfigurationExecutor) executionConfigurationManager.getExecutor( DefaultRunConfiguration.TYPE ); assertNotNull( defaultRunConfigurationExecutor ); }
public void cleanupOrphanedInternalTopics( final ServiceContext serviceContext, final Set<String> queryApplicationIds ) { final KafkaTopicClient topicClient = serviceContext.getTopicClient(); final Set<String> topicNames; try { topicNames = topicClient.listTopicNames(); } catch (Kafk...
@Test public void skipNonMatchingTopics() { // Given when(topicClient.listTopicNames()).thenReturn(ImmutableSet.of(TOPIC1, TOPIC2, TOPIC3)); // When cleaner.cleanupOrphanedInternalTopics(serviceContext, ImmutableSet.of(APP_ID_2)); // Then verify(queryCleanupService, times(1)).addCleanupTask(...
@Override public Object toKsqlRow(final Schema connectSchema, final Object connectData) { if (connectData == null) { return null; } return toKsqlValue(schema, connectSchema, connectData, ""); }
@Test public void shouldReturnTimeType() { // Given: final ConnectDataTranslator connectToKsqlTranslator = new ConnectDataTranslator(Time.SCHEMA); // When: final Object row = connectToKsqlTranslator.toKsqlRow(Time.SCHEMA, new Date(100L)); // Then: assertTrue(row instanceof java.sql.Time); ...
long joinPosition() { long position = consumerPosition; for (final ReadablePosition subscriberPosition : subscriberPositions) { position = Math.min(subscriberPosition.getVolatile(), position); } return position; }
@Test void shouldHaveJoiningPositionZeroWhenNoSubscriptions() { assertThat(ipcPublication.joinPosition(), is(0L)); }
public List<CaseInsensitiveString> pathIncludingAncestor() { if (cachedPathIncludingAncestor == null) { cachedPathIncludingAncestor = Collections.unmodifiableList(pathToAncestor(-1)); } return cachedPathIncludingAncestor; }
@Test public void shouldReturnPath_includingActualAncestorNode() { PathFromAncestor path = new PathFromAncestor(new CaseInsensitiveString("grand-parent/parent/child")); assertThat(path.pathIncludingAncestor(), is(List.of(new CaseInsensitiveString("child"), new CaseInsensitiveString("parent"), new Ca...
public static String encodeOnionUrlV2(byte[] onionAddrBytes) { checkArgument(onionAddrBytes.length == 10); return BASE32.encode(onionAddrBytes) + ".onion"; }
@Test(expected = IllegalArgumentException.class) public void encodeOnionUrlV2_badLength() { TorUtils.encodeOnionUrlV2(new byte[11]); }
public static Coder<PublishResult> fullPublishResult() { return new PublishResultCoder( RESPONSE_METADATA_CODER, NullableCoder.of(AwsCoders.sdkHttpMetadata())); }
@Test public void testFullPublishResultIncludingHeadersDecodeEncodeEquals() throws Exception { CoderProperties.coderDecodeEncodeEqual( PublishResultCoders.fullPublishResult(), new PublishResult().withMessageId(UUID.randomUUID().toString())); PublishResult value = buildFullPublishResult(); ...
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null)...
@Test public void testAlterOffsetsIncorrectPartitionKey() { MirrorCheckpointConnector connector = new MirrorCheckpointConnector(); assertThrows(ConnectException.class, () -> connector.alterOffsets(null, Collections.singletonMap( Collections.singletonMap("unused_partition_key", "unuse...
private Mono<Collection<TopicPartition>> filterPartitionsWithLeaderCheck(Collection<TopicPartition> partitions, boolean failOnUnknownLeader) { var targetTopics = partitions.stream().map(TopicPartition::topic).collect(Collectors.toSet()); ...
@Test void filterPartitionsWithLeaderCheckThrowExceptionIfThereIsSomePartitionsWithoutLeaderAndFlagSet() { ThrowingCallable call = () -> ReactiveAdminClient.filterPartitionsWithLeaderCheck( List.of( // contains partitions with no leader new TopicDescription("t1", false, ...
@Override public Integer call() throws Exception { super.call(); try (var files = Files.walk(directory)) { List<Template> templates = files .filter(Files::isRegularFile) .filter(YamlFlowParser::isValidExtension) .map(path -> yamlFlowParser...
@Test void invalid() { URL directory = TemplateNamespaceUpdateCommandTest.class.getClassLoader().getResource("invalidsTemplates"); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.run(Map.o...
@Override public void destroy() { if (this.snsClient != null) { try { this.snsClient.shutdown(); } catch (Exception e) { log.error("Failed to shutdown SNS client during destroy()", e); } } }
@Test void givenSnsClientIsNotNull_whenDestroy_thenShutdown() { node.destroy(); then(snsClientMock).should().shutdown(); }
public static UUnary create(Kind unaryOp, UExpression expression) { checkArgument( UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp); return new AutoValue_UUnary(unaryOp, expression); }
@Test public void rejectsNonUnaryOperations() { ULiteral sevenLit = ULiteral.intLit(7); assertThrows(IllegalArgumentException.class, () -> UUnary.create(Kind.PLUS, sevenLit)); }
@Override public void handle(final RoutingContext routingContext) { if (routingContext.request().isSSL()) { final String indicatedServerName = routingContext.request().connection() .indicatedServerName(); final String requestHost = routingContext.request().host(); if (indicatedServerNa...
@Test public void shouldNotCheckIfHostNull() { // Given: when(serverRequest.host()).thenReturn(null); // When: sniHandler.handle(routingContext); // Then: verify(routingContext, never()).fail(anyInt(), any()); verify(routingContext, times(1)).next(); }
@Override public void execute(SensorContext context) { FileSystem fs = context.fileSystem(); FilePredicates p = fs.predicates(); for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) { createIssues(file, context); } }
@Test public void execute_dataAndExecutionFlowsAreDetectedAndMessageIsFormatted() throws IOException { DefaultInputFile inputFile = newTestFile(IOUtils.toString(getClass().getResource("dataflow.xoo"), StandardCharsets.UTF_8)); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFi...
@Override public long size() { return colIndex[n]; }
@Test public void testSize() { System.out.println("size"); assertEquals(7, sparse.size()); }
public boolean isScratch() { return "".equals(registry) && SCRATCH.equals(repository) && Strings.isNullOrEmpty(tag) && Strings.isNullOrEmpty(digest); }
@Test public void testIsScratch() throws InvalidImageReferenceException { Assert.assertTrue(ImageReference.parse("scratch").isScratch()); Assert.assertTrue(ImageReference.scratch().isScratch()); Assert.assertFalse(ImageReference.of("", "scratch", "").isScratch()); Assert.assertFalse(ImageReference.of(...
@Override public String getDataSource() { return DataSourceConstant.MYSQL; }
@Test void testGetDataSource() { String dataSource = configInfoTagMapperByMySql.getDataSource(); assertEquals(DataSourceConstant.MYSQL, dataSource); }
public static String toJsonString(final Token<? extends TokenIdentifier> token ) throws IOException { return toJsonString(Token.class, toJsonMap(token)); }
@Test public void testHdfsFileStatusWithEcPolicy() throws IOException { final long now = Time.now(); final String parent = "/dir"; ErasureCodingPolicy dummyEcPolicy = new ErasureCodingPolicy("ecPolicy1", new ECSchema("EcSchema", 1, 1), 1024 * 2, (byte) 1); final HdfsFileStatus status = new Hdf...
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) { return index(keyFunction, Function.identity()); }
@Test public void index_supports_duplicate_keys() { ListMultimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId)); assertThat(multimap.keySet()).containsOnly(1, 2); assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C); assertThat(multimap.get(2)).con...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testNonForwardedInvalidTypes1() { String[] nonForwardedFields = {"f1; f2"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsSingleFromString( ...
public void putMap(Map<String, String> map) { if (map == null) { putNumber1(0); } else { Utils.checkArgument(map.size() < 256, "Map has to be smaller than 256 elements"); putNumber1(map.size()); for (Entry<String, String> entry : map.entrySet()...
@Test(expected = IllegalArgumentException.class) public void testMapIncorrectValue() { ZFrame frame = new ZFrame(new byte[(1 + 10)]); ZNeedle needle = new ZNeedle(frame); Map<String, String> map = new HashMap<>(); map.put("key", "=alue"); needle.putMap(map); }
public boolean submitUnknownProcessingError(Message message, String details) { return submitProcessingErrorsInternal(message, ImmutableList.of(new Message.ProcessingError( ProcessingFailureCause.UNKNOWN, "Encountered an unrecognizable processing error", details)))...
@Test public void submitUnknownProcessingError_unknownProcessingErrorSubmittedToQueue() throws Exception { // given final Message msg = Mockito.mock(Message.class); when(msg.processingErrors()).thenReturn(List.of()); when(msg.supportsFailureHandling()).thenReturn(true); when...
public static Serializable decode(final ByteBuf byteBuf) { int valueType = byteBuf.readUnsignedByte() & 0xff; StringBuilder result = new StringBuilder(); decodeValue(valueType, 1, byteBuf, result); return result.toString(); }
@Test void assertDecodeSmallJsonObjectWithUInt64() { List<JsonEntry> jsonEntries = new LinkedList<>(); jsonEntries.add(new JsonEntry(JsonValueTypes.UINT64, "key1", Long.MAX_VALUE)); jsonEntries.add(new JsonEntry(JsonValueTypes.UINT64, "key2", Long.MIN_VALUE)); ByteBuf payload = mockJ...
RuleDto createNewRule(RulesRegistrationContext context, RulesDefinition.Rule ruleDef) { RuleDto newRule = createRuleWithSimpleFields(ruleDef, uuidFactory.create(), system2.now()); ruleDescriptionSectionsGeneratorResolver.generateFor(ruleDef).forEach(newRule::addRuleDescriptionSectionDto); context.created(ne...
@Test public void from_whenRuleDefinitionDoesHaveCleanCodeAttribute_shouldReturnThisAttribute() { RulesDefinition.Rule ruleDef = getDefaultRule(CleanCodeAttribute.TESTED, RuleType.CODE_SMELL); RuleDto newRuleDto = underTest.createNewRule(context, ruleDef); assertThat(newRuleDto.getCleanCodeAttribute())....
@Override public PageResult<FileDO> getFilePage(FilePageReqVO pageReqVO) { return fileMapper.selectPage(pageReqVO); }
@Test public void testGetFilePage() { // mock 数据 FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到 o.setPath("yunai"); o.setType("image/jpg"); o.setCreateTime(buildTime(2021, 1, 15)); }); fileMapper.insert(dbFile); // 测试 path 不匹配 ...
public static void main(String[] args) throws Exception { Tika tika = new Tika(); for (String file : args) { String type = tika.detect(new File(file)); System.out.println(file + ": " + type); } }
@Test public void testSimpleTypeDetector() throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PrintStream out = System.out; System.setOut(new PrintStream(buffer, true, UTF_8.name())); SimpleTypeDetector.main(new String[]{"pom.xml"}); System.setO...
@Override public ProxyInvocationHandler parserInterfaceToProxy(Object target, String objectName) { // eliminate the bean without two phase annotation. Set<String> methodsToProxy = this.tccProxyTargetMethod(target); if (methodsToProxy.isEmpty()) { return null; } //...
@Test public void testNestTcc_should_commit() throws Exception { //given TccActionImpl tccAction = new TccActionImpl(); TccAction tccActionProxy = ProxyUtil.createProxy(tccAction, "oldtccAction"); Assertions.assertNotNull(tccActionProxy); NestTccActionImpl nestTccAction = n...
public static boolean compare(Object source, Object target) { if (source == target) { return true; } if (source == null || target == null) { return false; } if (source.equals(target)) { return true; } if (source instanceof Bo...
@Test public void connectionTest() { Date date = new Date(); Assert.assertTrue(CompareUtils.compare(100, new BigDecimal("100"))); Assert.assertTrue(CompareUtils.compare(new BigDecimal("100"), 100.0D)); Assert.assertTrue(CompareUtils.compare(Arrays.asList(1, 2, 3), Arrays.asList("3...
public static URLArgumentPlaceholderType valueOf(final Properties queryProps) { try { return URLArgumentPlaceholderType.valueOf(queryProps.getProperty(KEY, URLArgumentPlaceholderType.NONE.name()).toUpperCase()); } catch (final IllegalArgumentException ex) { return URLArgumentPlac...
@Test void assertValueOfWithValidQueryProperties() { assertThat(URLArgumentPlaceholderTypeFactory.valueOf(PropertiesBuilder.build(new Property("placeholder-type", "environment"))), is(URLArgumentPlaceholderType.ENVIRONMENT)); }
public Path path() { return path; }
@Test void testPath() { Path path = Path.parse("foo/bar/baz", Name::of); List<String> expected = List.of("foo", "bar", "baz"); assertEquals(expected, path.segments()); assertEquals(expected.subList(1, 3), path.skip(1).segments()); assertEquals(expected.subList(0, 2), path.cu...
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertObjectMessageToAmqpMessageWithDataBody() throws Exception { ActiveMQObjectMessage outbound = createObjectMessage(TEST_OBJECT_VALUE); outbound.onSend(); outbound.storeContent(); JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PCollectionsImmutableMap<?, ?> that = (PCollectionsImmutableMap<?, ?>) o; return underlying().equals(that.underlying()); }
@Test public void testEquals() { final HashPMap<Object, Object> mock = mock(HashPMap.class); assertEquals(new PCollectionsImmutableMap<>(mock), new PCollectionsImmutableMap<>(mock)); final HashPMap<Object, Object> someOtherMock = mock(HashPMap.class); assertNotEquals(new PCollections...
public Set<Flow> parseDataSet(ImmutableList<InformationElement> informationElements, Map<Integer, TemplateRecord> templateMap, ByteBuf setContent) { ImmutableSet.Builder<Flow> flowBuilder = ImmutableSet.builder(); // Padding: data records have no header and no fixed length, but the end of a data set (w...
@Test public void parseDataSet() throws IOException { final ByteBuf packet = Utils.readPacket("templates-data.ipfix"); InformationElementDefinitions infoElementDefs = new InformationElementDefinitions(Resources.getResource("ipfix-iana-elements.json"), ...
public static Credentials create(ECKeyPair ecKeyPair) { String address = Numeric.prependHexPrefix(Keys.getAddress(ecKeyPair)); return new Credentials(ecKeyPair, address); }
@Test public void testCredentialsFromECKeyPair() { Credentials credentials = Credentials.create(SampleKeys.PRIVATE_KEY_STRING, SampleKeys.PUBLIC_KEY_STRING); verify(credentials); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) { if ( n == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null")); } if ( scale == null ) { return FEEL...
@Test void invokeRoundingOdd() { FunctionTestUtil.assertResult(decimalFunction.invoke(BigDecimal.valueOf(10.35), BigDecimal.ONE), BigDecimal.valueOf(10.4)); }
public static void free(final DirectBuffer buffer) { if (null != buffer) { free(buffer.byteBuffer()); } }
@Test @EnabledForJreRange(min = JAVA_9) void freeThrowsIllegalArgumentExceptionIfByteBufferIsASlice() { final ByteBuffer buffer = ByteBuffer.allocateDirect(4).slice(); assertThrows(IllegalArgumentException.class, () -> BufferUtil.free(buffer)); }
public ApplicationBuilder qosPort(Integer qosPort) { this.qosPort = qosPort; return getThis(); }
@Test void qosPort() { ApplicationBuilder builder = new ApplicationBuilder(); builder.qosPort(8080); Assertions.assertEquals(8080, builder.build().getQosPort()); }
public void setExtractor(ApacheHttpClientResourceExtractor extractor) { AssertUtil.notNull(extractor, "extractor cannot be null"); this.extractor = extractor; }
@Test(expected = IllegalArgumentException.class) public void testConfigSetCleaner() { SentinelApacheHttpClientConfig config = new SentinelApacheHttpClientConfig(); config.setExtractor(null); }
@Override public Dataset<PartitionStat> get() { StructType partitionSchema = spark.sql(String.format("SELECT * FROM %s.partitions", tableName)).schema(); try { partitionSchema.apply("partition"); return spark .sql(String.format("SELECT partition, file_count FROM %s.partitions", t...
@Test public void testNonPartitionedTablePartitionStats() throws Exception { final String testTable = "db.test_table_partition_stats_non_partitioned"; try (SparkSession spark = getSparkSession()) { spark.sql("USE openhouse"); spark.sql(String.format("CREATE TABLE %s (id INT, data STRING)", testTab...
public void commitBlock(final long workerId, final long usedBytesOnTier, final String tierAlias, final String mediumType, final long blockId, final long length) throws AlluxioStatusException { retryRPC(() -> { CommitBlockPRequest request = CommitBlockPRequest.newBuilder().setWorkerId(wor...
@Test public void commitBlock() throws Exception { ConcurrentHashMap<Long, Long> committedBlocks = new ConcurrentHashMap<>(); final long workerId = 1L; final long blockId = 2L; final long usedBytesOnTier = 1024 * 1024L; final long length = 1024 * 1024L; final String tierAlias = "MEM"; fina...
public TenantCapacity getTenantCapacity(String tenantId) { TenantCapacityMapper tenantCapacityMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.TENANT_CAPACITY); String sql = tenantCapacityMapper.select( Arrays.asList("id", "quota", "`...
@Test void testGetTenantCapacity() { List<TenantCapacity> list = new ArrayList<>(); TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant("test"); list.add(tenantCapacity); String tenantId = "testId"; when(jdbcTemplate.query(...
@Override public Optional<String> getScmRevision() { return scmRevision; }
@Test public void getScmRevision() { assertThat(new CiConfigurationImpl(null, "test").getScmRevision()).isEmpty(); assertThat(new CiConfigurationImpl("", "test").getScmRevision()).isEmpty(); assertThat(new CiConfigurationImpl(" ", "test").getScmRevision()).isEmpty(); assertThat(new CiConfigurationIm...
@Override public void onWorkflowFinalized(Workflow workflow) { WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput()); WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow); String reason = workflow.getReasonForIncompletion(); LOG.inf...
@Test public void testWorkflowFinalizedComplete() { when(workflow.getStatus()).thenReturn(Workflow.WorkflowStatus.COMPLETED); statusListener.onWorkflowFinalized(workflow); Assert.assertEquals( 1L, metricRepo .getCounter( MetricConstants.WORKFLOW_STATUS_LISTENER_...
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) { if (null == source) { return null; } T target = ReflectUtil.newInstanceIfPossible(tClass); copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); return target; }
@Test public void copyPropertiesMapToMapIgnoreNullTest() { // 测试MapToMap final Map<String, Object> p1 = new HashMap<>(); p1.put("isSlow", true); p1.put("name", "测试"); p1.put("subName", null); final Map<String, Object> map = MapUtil.newHashMap(); BeanUtil.copyProperties(p1, map, CopyOptions.create().setI...
public B accesslog(String accesslog) { this.accesslog = accesslog; return getThis(); }
@Test void accesslog() { ServiceBuilder builder = new ServiceBuilder(); builder.accesslog("accesslog"); Assertions.assertEquals("accesslog", builder.build().getAccesslog()); }
public static @NonNull String quoteArgument(@NonNull String argument) { if (!NEEDS_QUOTING.matcher(argument).find()) return argument; StringBuilder sb = new StringBuilder(); sb.append('"'); int end = argument.length(); for (int i = 0; i < end; i++) { int nrBackslashes...
@Test public void testQuoteArgument_OnlyQuotesWhenNecessary() { for (String arg : Arrays.asList("", "foo", "foo-bar", "C:\\test\\path", "http://www.example.com/")) { assertEquals(arg, WindowsUtil.quoteArgument(arg)); } }
public static long parseBytes(String text) throws IllegalArgumentException { Objects.requireNonNull(text, "text cannot be null"); final String trimmed = text.trim(); if (trimmed.isEmpty()) { throw new IllegalArgumentException("argument is an empty- or whitespace-only string"); ...
@Test void testParseNumberOverflow() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> MemorySize.parseBytes("100000000000000000000000000000000 bytes")); }
public FederationPolicyManager getPolicyManager(String queueName) throws YarnException { FederationPolicyManager policyManager = policyManagerMap.get(queueName); // If we don't have the policy manager cached, pull configuration // from the FederationStateStore to create and cache it if (policyMan...
@Test public void testGetPolicy() throws YarnException { WeightedLocalityPolicyManager manager = (WeightedLocalityPolicyManager) policyFacade .getPolicyManager(TEST_QUEUE); Assert.assertEquals(testConf, manager.serializeConf()); }