focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Object convert(Class<?> expectedClass, Object originalObject) { if (originalObject == null) { return null; } Class<?> currentClass = originalObject.getClass(); if (expectedClass.isAssignableFrom(currentClass)) { return originalObject; } ...
@Test void convertUnconvertibleFromDouble() { UNCONVERTIBLE_FROM_DOUBLE.forEach((s, o) -> { Class<?> expectedClass = o.getClass(); try { ConverterTypeUtil.convert(expectedClass, s); fail(String.format("Expecting KiePMMLException for %s %s", s, o)); ...
public Collection<ConfigEntry> entries() { return Collections.unmodifiableCollection(entries.values()); }
@Test public void shouldGetAllEntries() { assertEquals(2, config.entries().size()); assertTrue(config.entries().contains(E1)); assertTrue(config.entries().contains(E2)); }
public void setUuids(Set<String> uuids) { requireNonNull(uuids, "Uuids cannot be null"); checkState(this.uuids == null, "Uuids have already been initialized"); this.uuids = new HashSet<>(uuids); }
@Test public void fail_with_NPE_when_setting_null_uuids() { assertThatThrownBy(() -> sut.setUuids(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Uuids cannot be null"); }
@Override public Connector create(String catalogName, Map<String, String> requiredConfig, ConnectorContext context) { requireNonNull(requiredConfig, "requiredConfig is null"); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) { Bootstrap app = new Bo...
@Test public void test() { JdbcConnectorFactory connectorFactory = new JdbcConnectorFactory( "test", new TestingH2JdbcModule(), getClass().getClassLoader()); connectorFactory.create("test", TestingH2JdbcModule.createProperties(), new TestingConnec...
public static String getCertFingerPrint(Certificate cert) { byte [] digest = null; try { byte[] encCertInfo = cert.getEncoded(); MessageDigest md = MessageDigest.getInstance("SHA-1"); digest = md.digest(encCertInfo); } catch (Exception e) { logger...
@Test public void testGetCertFingerPrintSecondary() throws Exception { X509Certificate cert = null; try (InputStream is = Config.getInstance().getInputStreamFromFile("secondary.crt")){ CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) c...
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testTableScanAllStats() throws Exception { appendTwoSnapshots(); ScanContext scanContext = ScanContext.builder() .includeColumnStats(true) .startingStrategy(StreamingStartingStrategy.TABLE_SCAN_THEN_INCREMENTAL) .build(); ContinuousSplitPlanne...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void placeholderSpelTest() throws Exception { String testExpression = "${missingProperty:default}"; DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resolve(...
private static boolean checkKeytool(String keytoolPath) { final SystemCommand nativeCommand = new SystemCommand(null, null); final List<String> arguments = new ArrayList<>(); arguments.add(keytoolPath); arguments.add("-J-Xmx128m"); arguments.add("-help"); // $NON-NLS-1$ t...
@Test public void testCheckKeytool() throws Exception { SystemCommand sc = new SystemCommand(null, null); List<String> arguments = new ArrayList<>(); arguments.add("xyzqwas"); // should not exist Assertions.assertThrows(IOException.class, () -> { int status = sc.run(argum...
public String generateReport(MavenProject project, final File xmlPath, final File htmlPath) throws IOException { String out; parseAllTestResults(xmlPath); if (!testResults.isEmpty()) { gatherBestRouteCoverages(); squashDuplicateRoutes(); generateRouteSta...
@Test public void testGenerateReport() throws IOException { File htmlPath = htmlPath(); Path htmlPathAsPath = Paths.get(htmlPath.getPath()); if (!Files.exists(htmlPathAsPath)) { Files.createDirectories(htmlPathAsPath); } MavenProject mavenProject = new MavenProj...
private static int getSplitRatio(Configuration conf) { int splitRatio = conf.getInt( DistCpConstants.CONF_LABEL_SPLIT_RATIO, DistCpConstants.SPLIT_RATIO_DEFAULT); if (splitRatio <= 0) { LOG.warn(DistCpConstants.CONF_LABEL_SPLIT_RATIO + " should be positive. Fall back to default v...
@Test public void testGetSplitRatio() throws Exception { Assert.assertEquals(1, DynamicInputFormat.getSplitRatio(1, 1000000000)); Assert.assertEquals(2, DynamicInputFormat.getSplitRatio(11000000, 10)); Assert.assertEquals(4, DynamicInputFormat.getSplitRatio(30, 700)); Assert.assertEquals(2, DynamicInp...
public static DualInputSemanticProperties addSourceFieldOffsets( DualInputSemanticProperties props, int numInputFields1, int numInputFields2, int offset1, int offset2) { DualInputSemanticProperties offsetProps = new DualInputSemanticProperties(); ...
@Test void testAddSourceFieldOffsets() { DualInputSemanticProperties semProps = new DualInputSemanticProperties(); semProps.addForwardedField(0, 0, 1); semProps.addForwardedField(0, 3, 3); semProps.addForwardedField(1, 1, 2); semProps.addForwardedField(1, 1, 4); semP...
protected float convertFloat(Object value) { if (value instanceof Number) { return ((Number) value).floatValue(); } else if (value instanceof String) { return Float.parseFloat((String) value); } throw new IllegalArgumentException("Cannot convert to float: " + value.getClass().getName()); }
@Test public void testFloatConversion() { Table table = mock(Table.class); when(table.schema()).thenReturn(SIMPLE_SCHEMA); RecordConverter converter = new RecordConverter(table, config); float expectedFloat = 123f; ImmutableList.of("123", 123, 123L, 123d, expectedFloat) .forEach( ...
@PostMapping("/meta/saveOrUpdate") public Mono<String> saveOrUpdate(@RequestBody final MetaData metaData) { if (CollectionUtils.isEmpty(subscribers)) { return Mono.just(Constants.SUCCESS); } LOG.info("saveOrUpdate apache shenyu local meta data"); subscribers.forEach(metaD...
@Test public void testSaveOrUpdate() throws Exception { final MockHttpServletResponse response = this.mockMvc.perform(MockMvcRequestBuilders.post("/shenyu/meta/saveOrUpdate") .contentType(MediaType.APPLICATION_JSON) .content(GsonUtils.getInstance().toJson(meta...
@PostMapping(value = "/artifact/download") public ResponseEntity<String> importArtifact(@RequestParam(value = "url", required = true) String url, @RequestParam(value = "mainArtifact", defaultValue = "true") boolean mainArtifact, @RequestParam(value = "secretName", required = false) String secretNam...
@Test @DisplayName("Should return 500 when there is an error retrieving remote item") void shouldReturnInternalServerError() throws MockRepositoryImportException { // arrange String wrongUrl = "https://raw.githubusercontent.com/microcks/microcks/master/samples/wrong-openapi.yaml"; // act ...
public static byte parsePermFromString(String permString) { if (permString == null) { return Permission.DENY; } switch (permString.trim()) { case AclConstants.PUB: return Permission.PUB; case AclConstants.SUB: return Permission....
@Test public void fromStringGetPermissionTest() { byte perm = Permission.parsePermFromString("PUB"); Assert.assertEquals(perm, Permission.PUB); perm = Permission.parsePermFromString("SUB"); Assert.assertEquals(perm, Permission.SUB); perm = Permission.parsePermFromString("PU...
public static void putIntByteBuffer(ByteBuffer buf, int b) { buf.put((byte) (b & 0xFF)); }
@Test public void putIntByteBuffer() { class TestCase { byte mExpected; int mInput; public TestCase(byte expected, int input) { mExpected = expected; mInput = input; } } ArrayList<TestCase> testCases = new ArrayList<>(); testCases.add(new TestCase((byte) 0x00,...
public static ObjectMapper ofIon() { return ION_MAPPER; }
@Test @DefaultTimeZone("Europe/Athens") void ion() throws IOException { ObjectMapper mapper = JacksonMapper.ofIon(); Pojo original = pojo(); String s = mapper.writeValueAsString(original); assertThat(s, containsString("nullable:null")); Pojo deserialize = mapper.readVal...
public static <T extends Throwable> void checkNotEmpty(final String value, final Supplier<T> exceptionSupplierIfUnexpected) throws T { if (Strings.isNullOrEmpty(value)) { throw exceptionSupplierIfUnexpected.get(); } }
@Test void assertCheckNotEmptyWithCollectionToThrowsException() { assertThrows(SQLException.class, () -> ShardingSpherePreconditions.checkNotEmpty(Collections.emptyList(), SQLException::new)); }
public void update(final TRuntimeProfileTree thriftProfile) { Reference<Integer> idx = new Reference<>(0); update(thriftProfile.nodes, idx, false); Preconditions.checkState(idx.getRef().equals(thriftProfile.nodes.size())); }
@Test public void testUpdate() { RuntimeProfile profile = new RuntimeProfile("REAL_ROOT"); /* the profile tree * ROOT(time=5s info[key=value]) * A(time=2s) B(time=1s info[BInfo1=BValu1;BInfo2=BValue2]) * A_SON(time=10...
@Override public @UnknownKeyFor @NonNull @Initialized String identifier() { return "beam:schematransform:org.apache.beam:kafka_write:v1"; }
@Test public void testManagedMappings() { KafkaWriteSchemaTransformProvider provider = new KafkaWriteSchemaTransformProvider(); Map<String, String> mapping = ManagedTransformConstants.MAPPINGS.get(provider.identifier()); assertNotNull(mapping); List<String> configSchemaFieldNames = provider.configur...
String authHeader(Map<String, String> attributes, Map<String, String> headers, String body, AwsCredentials credentials, String timestamp, String httpMethod) { return buildAuthHeader( credentials.getAccessKey(), credentialScopeEcs(timestamp), signedHeader...
@Test public void authHeaderEc2() { // given String timestamp = "20141106T111126Z"; Map<String, String> attributes = new HashMap<>(); attributes.put("Action", "DescribeInstances"); attributes.put("Version", "2016-11-15"); Map<String, String> headers = new HashMap<>(...
public static String toString(final Collection<?> col) { if (col == null) { return "null"; } if (col.isEmpty()) { return "[]"; } return CycleDependencyHandler.wrap(col, o -> { StringBuilder sb = new StringBuilder(32); sb.append("["...
@Test public void testMapToString() { Map<Object, Object> nullMap = null; Map<Object, Object> emptyMap = new HashMap<>(); Map<Object, Object> filledMap = new HashMap<>(); filledMap.put("aaa", "111"); filledMap.put("bbb", "222"); filledMap.put("self", filledMap); ...
@Override public void handlerRule(final RuleData ruleData) { Optional.ofNullable(ruleData.getHandle()).ifPresent(ruleHandle -> { JwtRuleHandle jwtRuleHandle = JwtRuleHandle.newInstance(ruleHandle); CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(ruleData), jwtRuleHandle); ...
@Test public void testHandlerRule() { RuleData ruleData = new RuleData(); ruleData.setId("jwtRule"); ruleData.setSelectorId("jwt"); String handleJson = "{\"converter\":[{\"jwtVal\":\"sub\",\"headerVal\":\"id\"}]}"; ruleData.setHandle(handleJson); jwtPluginDataHandlerU...
@Override public RuleNodePath getRuleNodePath() { return INSTANCE; }
@Test void assertNew() { RuleNodePathProvider ruleNodePathProvider = new EncryptRuleNodePathProvider(); RuleNodePath actualRuleNodePath = ruleNodePathProvider.getRuleNodePath(); assertThat(actualRuleNodePath.getNamedItems().size(), is(2)); assertTrue(actualRuleNodePath.getNamedItems(...
@VisibleForTesting JobMeta filterPrivateDatabases( JobMeta jobMeta ) { Set<String> privateDatabases = jobMeta.getPrivateDatabases(); if ( privateDatabases != null ) { // keep only private transformation databases for ( Iterator<DatabaseMeta> it = jobMeta.getDatabases().iterator(); it.hasNext(); ) ...
@Test public void filterPrivateDatabasesNoPrivateDatabaseTest() { IUnifiedRepository purMock = mock( IUnifiedRepository.class ); JobMeta jobMeta = new JobMeta( ); jobMeta.setDatabases( getDummyDatabases() ); jobMeta.setPrivateDatabases( new HashSet<>( ) ); StreamToJobNodeConverter jobConverter =...
public static long parseSize(final String propertyName, final String propertyValue) { final int lengthMinusSuffix = propertyValue.length() - 1; final char lastCharacter = propertyValue.charAt(lengthMinusSuffix); if (Character.isDigit(lastCharacter)) { return Long.parseLon...
@Test void shouldThrowWhenParseSizeOverflows() { assertThrows(NumberFormatException.class, () -> parseSize("", 8589934592L + "g")); }
public static Map<String, Object> flatten(Map<String, Object> originalMap, String parentKey, String separator) { final Map<String, Object> result = new HashMap<>(); for (Map.Entry<String, Object> entry : originalMap.entrySet()) { final String key = parentKey.isEmpty() ? entry.getKey() : pare...
@Test public void flattenHandlesFlatMap() throws Exception { final Map<String, Object> map = ImmutableMap.of( "foo", "bar", "baz", "qux"); assertThat(MapUtils.flatten(map, "", "_")).isEqualTo(map); }
@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 testConvertCompressedTextMessageCreatesDataSectionBody() throws Exception { String contentString = "myTextMessageContent"; ActiveMQTextMessage outbound = createTextMessage(contentString, true); outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_DATA); outbou...
@Override public boolean isEmpty() { return data.isEmpty(); }
@CacheSpec(population = Population.EMPTY, refreshAfterWrite = Expire.DISABLED, expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED, weigher = CacheWeigher.DISABLED, keys = ReferenceType.STRONG, values = ReferenceType.STRONG) @Test(dataProvider = "c...
@Override public AuthenticationResult authenticate(final ChannelHandlerContext context, final PacketPayload payload) { AuthorityRule rule = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class); if (MySQLConnecti...
@Test void assertAuthenticationSwitchResponse() { setConnectionPhase(MySQLConnectionPhase.AUTHENTICATION_METHOD_MISMATCH); MySQLPacketPayload payload = mock(MySQLPacketPayload.class); Channel channel = mock(Channel.class); ChannelHandlerContext channelHandlerContext = mock(ChannelHan...
@Deprecated protected MetadataReportRetry getMetadataReportRetry() { return metadataReportRetry; }
@Test void testRetryCancel() throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.RetryTestService"; String version = "1.0.0.retrycancel"; String group = null; String application = "vic.retry"; URL storeUrl = URL.valueOf("retryReport://" + N...
public abstract T getNow(T valueIfAbsent) throws InterruptedException, ExecutionException;
@Test public void testCompletingFuturesViaCancellation() throws Exception { final KafkaFutureImpl<String> future = new KafkaFutureImpl<>(); CompleterThread<String> myThread = new CompleterThread<>(future, null, new CancellationException("Ultimate efficiency achieved.")); asse...
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) { Optional<String> externalJobId = extractExternalJobId(runtimeSummary); if (externalJobId.isPresent()) { Optional<OutputData> outputDataOpt = outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobTyp...
@Test public void testMissingJobIdArtifact() { outputDataManager.validateAndMergeOutputParams(runtimeSummary); assertTrue(runtimeSummary.getParams().isEmpty()); }
public ResourcePattern toKafkaResourcePattern() { org.apache.kafka.common.resource.ResourceType kafkaType; String kafkaName; PatternType kafkaPattern = PatternType.LITERAL; switch (type) { case TOPIC: kafkaType = org.apache.kafka.common.resource.ResourceType....
@Test public void testToKafkaResourcePatternForTransactionalIdResource() { // Regular transactionalId SimpleAclRuleResource transactionalIdResourceRules = new SimpleAclRuleResource("my-transactionalId", SimpleAclRuleResourceType.TRANSACTIONAL_ID, null); ResourcePattern expectedKafkaResource...
@Override @Nullable public Portable[] readPortableArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, PORTABLE_ARRAY, super::readPortableArray); }
@Test public void testReadPortableArray() throws Exception { assertNull(reader.readPortableArray("NO SUCH FIELD")); }
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) { Objects.requireNonNull(type, "type must not be null"); TypeAdapter<?> cached = typeTokenCache.get(type); if (cached != null) { @SuppressWarnings("unchecked") TypeAdapter<T> adapter = (TypeAdapter<T>) cached; return adapter; } ...
@Test public void testGetAdapter_Concurrency() { class DummyAdapter<T> extends TypeAdapter<T> { @Override public void write(JsonWriter out, T value) throws IOException { throw new AssertionError("not needed for this test"); } @Override public T read(JsonReader in) throws IOE...
public static Schema convert(final org.apache.iceberg.Schema schema) { ImmutableList.Builder<Field> fields = ImmutableList.builder(); for (NestedField f : schema.columns()) { fields.add(convert(f)); } return new Schema(fields.build()); }
@Test public void convertComplex() { Schema iceberg = new Schema( Types.NestedField.optional( 0, "m", MapType.ofOptional(1, 2, StringType.get(), LongType.get())), Types.NestedField.required( 3, "m2", MapType.ofOptional...
public MailConfiguration getConfiguration() { if (configuration == null) { configuration = new MailConfiguration(getCamelContext()); } return configuration; }
@Test public void testSMTPEndpointWithSubjectOption() { MailEndpoint endpoint = checkEndpoint("smtp://myhost:25?subject=hello"); MailConfiguration config = endpoint.getConfiguration(); assertEquals("smtp", config.getProtocol(), "getProtocol()"); assertEquals("myhost", config.getHost(...
Label(String spec) { String[] labelParts = spec.trim().split("\\s*=\\s*"); if (labelParts.length != 2) { throw new IllegalArgumentException(String.format("Invalid label specification: '%s'", spec)); } this.key = labelParts[0]; this.value = labelParts[1]; }
@Test public void label() { // given String label = "key=value"; // when Label result = new Label(label); // then assertEquals("key", result.getKey()); assertEquals("value", result.getValue()); }
@Override public long getUsableSpace() { throw new UnsupportedOperationException("Not implemented"); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testGetUsableSpace() { fs.getFile("nonsuch.txt").getUsableSpace(); }
@PublicAPI(usage = ACCESS) public boolean isEquivalentTo(Class<?> clazz) { return getName().equals(clazz.getName()); }
@Test public void JavaClass_is_equivalent_to_reflect_type() { JavaClass list = importClassWithContext(List.class); assertThat(list.isEquivalentTo(List.class)).as("JavaClass is List.class").isTrue(); assertThat(list.isEquivalentTo(Collection.class)).as("JavaClass is Collection.class").isFals...
static String getAbbreviation(Exception ex, Integer statusCode, String storageErrorMessage) { String result = null; for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) { final String abbreviation = retryReasonCategory.captureAndGetAbbreviation(ex, statusC...
@Test public void testIngressLimitRetryReason() { Assertions.assertThat(RetryReason.getAbbreviation(null, HTTP_UNAVAILABLE, INGRESS_OVER_ACCOUNT_LIMIT.getErrorMessage())).isEqualTo( INGRESS_LIMIT_BREACH_ABBREVIATION ); }
@Override public double read() { return gaugeSource.read(); }
@Test public void whenProbeRegisteredAfterGauge() { DoubleGauge gauge = metricsRegistry.newDoubleGauge("foo.doubleField"); SomeObject someObject = new SomeObject(); metricsRegistry.registerStaticMetrics(someObject, "foo"); assertEquals(someObject.doubleField, gauge.read(), 10E-6); ...
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test public void shouldNotThrowOnDuplicateHandler0() { HandlerMaps.forClass(BaseType.class) .put(LeafTypeA.class, handler0_1) .put(LeafTypeB.class, handler0_1); }
public List<GitLabBranch> getBranches(String gitlabUrl, String pat, Long gitlabProjectId) { String url = format("%s/projects/%s/repository/branches", gitlabUrl, gitlabProjectId); LOG.debug("get branches : [{}]", url); Request request = new Request.Builder() .addHeader(PRIVATE_TOKEN, pat) .get() ...
@Test public void get_branches_fail_if_exception() throws IOException { server.shutdown(); String instanceUrl = gitlabUrl; assertThatThrownBy(() -> underTest.getBranches(instanceUrl, "pat", 12345L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Failed to connect to"); }
public Reaper(Engine engine) { _engine = engine; }
@Test public void testReaper() throws InterruptedException { final int COUNT = 10; final List<Reaper.Zombie> zombies = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(COUNT); for (int i = 0; i < COUNT; ++i) { zombies.add(() -> Task.action("countDown", () -> latch.countD...
public String convertInt(int i) { return convert(i); }
@Test // test ways for dealing with flowing i converter, as in "foo%ix" public void flowingI() { { FileNamePattern pp = new FileNamePattern("foo%i{}bar%i", context); assertEquals("foo3bar3", pp.convertInt(3)); } { FileNamePattern pp = new FileNamePattern("foo%i{}bar%i", context); ...
public static Reader read(String fileName) throws FileNotFoundException { return new InputStreamReader(readToStream(fileName), StandardCharsets.UTF_8); }
@Test public void shouldThrowWhenResourceNotFound() { assertThrows(FileNotFoundException.class, () -> ResourceUtils.read("/not-existed")); }
@Override public String toString() { return "QualityGateImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", status=" + status + ", conditions=" + conditions + '}'; }
@Test public void verify_toString() { when(condition.toString()).thenReturn("{Condition}"); assertThat(underTest) .hasToString("QualityGateImpl{id='some id', name='some name', status=OK, conditions=[{Condition}]}"); }
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_map_of_serializable_key_and_value_with_null() { Map<String, SerializableObject> original = new LinkedHashMap<>(); original.put("null", null); original.put("key", new SerializableObject("value")); Object cloned = serializer.clone(original); asser...
@Operation(summary = "updateProjectParameter", description = "UPDATE_PROJECT_PARAMETER_NOTES") @Parameters({ @Parameter(name = "code", description = "PROJECT_PARAMETER_CODE", schema = @Schema(implementation = long.class, example = "123456")), @Parameter(name = "projectParameterName", descrip...
@Test public void testUpdateProjectParameter() { User loginUser = getGeneralUser(); Mockito.when(projectParameterService.updateProjectParameter(Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.any(), Mockito.any())).thenReturn(getSuccessResult()); Result result =...
@Override public void run(DiagnosticsLogWriter writer) { keyList.clear(); keyList.addAll(properties.keySet()); sort(keyList); writer.startSection("ConfigProperties"); for (String key : keyList) { String value = properties.get(key); writer.writeKeyValu...
@Test public void testRun() { plugin.run(logWriter); assertContains("property1=value1"); }
String accessToken() { String urlString = String.format("%s/computeMetadata/v1/instance/service-accounts/default/token", endpoint); String accessTokenResponse = callGet(urlString); return extractAccessToken(accessTokenResponse); }
@Test public void accessToken() { // given stubFor(get(urlEqualTo("/computeMetadata/v1/instance/service-accounts/default/token")) .withHeader("Metadata-Flavor", equalTo("Google")) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(accessTokenRespon...
@Override public Collection<RedisServer> slaves(NamedNode master) { List<Map<String, String>> slaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, master.getName()); return toRedisServersList(slaves); }
@Test public void testSlaves() { Collection<RedisServer> masters = connection.masters(); Collection<RedisServer> slaves = connection.slaves(masters.iterator().next()); assertThat(slaves).hasSize(2); }
public RedisCache(final RedisConfigProperties redisConfigProperties) { this.redisTemplate = new ReactiveRedisTemplate<>(new RedisConnectionFactory(redisConfigProperties).getLettuceConnectionFactory(), ShenyuRedisSerializationContext.bytesSerializationContext()); }
@Test public void testRedisCache() { final String testKey = "testRedisCache"; final ICache cache = new RedisCache(getConfig()); cache.isExist(testKey).subscribe(v -> assertEquals(Boolean.FALSE, v)); cache.cacheData(testKey, testKey.getBytes(StandardCharsets.UTF_8), 1000) ...
@Override public void visitProject(Component project, Path<AnalysisFromSonarQube94Visitor.AnalysisFromSonarQube94> path) { measureRepository.add(project, analysisFromSonarQube94Metric, Measure.newMeasureBuilder().create(path.current().sonarQube94OrGreater)); }
@Test public void visitProject_createMeasureForMetric() { Component project = builder(FILE).setUuid("uuid") .setKey("dbKey") .setName("name") .setStatus(Component.Status.SAME) .setReportAttributes(mock(ReportAttributes.class)) .build(); PathAwareVisitor.Path<AnalysisFromSonarQub...
@Override public boolean isPluginDisabled(String pluginId) { if (disabledPlugins.contains(pluginId)) { return true; } return !enabledPlugins.isEmpty() && !enabledPlugins.contains(pluginId); }
@Test public void testIsPluginDisabledWithEnableEmpty() throws IOException { createDisabledFile(); PluginStatusProvider statusProvider = new DefaultPluginStatusProvider(pluginsPath); assertFalse(statusProvider.isPluginDisabled("plugin-1")); assertTrue(statusProvider.isPluginDisable...
@Override public synchronized int read() throws IOException { checkNotClosed(); if (finished) { return -1; } file.readLock().lock(); try { int b = file.read(pos++); // it's ok for pos to go beyond size() if (b == -1) { finished = true; } else { file.setLas...
@Test public void testRead_partialArray_sliceSmaller() throws IOException { JimfsInputStream in = newInputStream(1, 2, 3, 4, 5, 6, 7, 8); byte[] bytes = new byte[12]; assertThat(in.read(bytes, 0, 6)).isEqualTo(6); assertArrayEquals(bytes(1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0), bytes); assertThat(in.r...
@Override public void onDeserializationFailure( final String source, final String changelog, final byte[] data ) { // NOTE: this only happens for values, we should never auto-register key schemas final String sourceSubject = KsqlConstants.getSRSubject(source, false); final String chang...
@Test public void shouldRegisterOtherSchemaIdIfFirstFails() throws IOException, RestClientException { // Given: when(srClient.getSchemaBySubjectAndId(KsqlConstants.getSRSubject(SOURCE, false), ID2)).thenReturn(schema2); when(srClient.getSchemaBySubjectAndId(KsqlConstants.getSRSubject(SOURCE, false), ID))....
public static void closeStreams(java.io.Closeable... streams) { if (streams != null) { cleanupWithLogger(null, streams); } }
@Test public void testCloseStreams() throws IOException { File tmpFile = null; FileOutputStream fos; BufferedOutputStream bos; FileOutputStream nullStream = null; try { tmpFile = new File(GenericTestUtils.getTestDir(), "testCloseStreams.txt"); fos = new FileOutputStream(tmpFile) { ...
public final void isSameInstanceAs(@Nullable Object expected) { if (actual != expected) { failEqualityCheck( SAME_INSTANCE, expected, /* * Pass through *whether* the values are equal so that failEqualityCheck() can print that * information. But remove the de...
@Test public void isSameInstanceAsFailureWithDifferentTypesAndSameToString() { Object a = "true"; Object b = true; expectFailure.whenTesting().that(a).isSameInstanceAs(b); assertFailureKeys("expected specific instance", "an instance of", "but was", "an instance of"); assertFailureValue("expected s...
@VisibleForTesting void validateOldPassword(Long id, String oldPassword) { AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); } if (!isPasswordMatch(oldPassword, user.getPassword())) { throw exception(USER_PASSW...
@Test public void testValidateOldPassword_notExists() { assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()), USER_NOT_EXISTS); }
@Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minLength") || node.has("maxLength")) && isApplicableType(field...
@Test public void testMaxAndMinLength() { when(config.isIncludeJsr303Annotations()).thenReturn(true); final int minValue = new Random().nextInt(); final int maxValue = new Random().nextInt(); JsonNode maxSubNode = Mockito.mock(JsonNode.class); when(subNode.asInt()).thenReturn...
public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException { UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream))); return parser.parse(); }
@Test public void testParseIssue107_3() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue107_3.diff")); assertThat(diff.getFiles().size()).isEqualTo(1); UnifiedDiffFile file1 = dif...
@Override public void publish(ScannerReportWriter writer) { List<DefaultAnalysisWarnings.Message> warnings = defaultAnalysisWarnings.warnings(); if (warnings.isEmpty()) { return; } writer.writeAnalysisWarnings(warnings.stream() .map(AnalysisWarningsPublisher::toProtobufAnalysisWarning) ...
@Test public void publish_warnings() throws IOException { ScannerReportWriter writer = new ScannerReportWriter(fileStructure); String warning1 = "warning 1"; String warning2 = "warning 2"; analysisWarnings.addUnique(warning1); analysisWarnings.addUnique(warning1); analysisWarnings.addUnique(w...
void doSubmit(final Runnable action) { CONTINUATION.get().submit(action); }
@Test public void testOnSuccessCalled() { final AtomicInteger sequence = new AtomicInteger(0); final AtomicInteger action = new AtomicInteger(); final AtomicInteger onSuccess = new AtomicInteger(); Continuations CONT = new Continuations(); CONT.doSubmit(() -> { action.set(sequence.incrementA...
public static ThrowableType getThrowableType(Throwable cause) { final ThrowableAnnotation annotation = cause.getClass().getAnnotation(ThrowableAnnotation.class); return annotation == null ? ThrowableType.RecoverableError : annotation.value(); }
@Test void testThrowableType_NonRecoverable() { assertThat( ThrowableClassifier.getThrowableType( new SuppressRestartsException(new Exception("")))) .isEqualTo(ThrowableType.NonRecoverableError); }
@Override public AuthenticationDataProvider getAuthData() throws PulsarClientException { Lock readLock = cachedRoleTokenLock.readLock(); readLock.lock(); try { if (cachedRoleTokenIsValid()) { return new AuthenticationDataAthenz(roleToken, i...
@Test public void testGetAuthData() throws Exception { com.yahoo.athenz.auth.token.RoleToken roleToken = new com.yahoo.athenz.auth.token.RoleToken( auth.getAuthData().getCommandData()); assertEquals(roleToken.getPrincipal(), String.format("%s.%s", TENANT_DOMAIN, TENANT_SERVICE)); ...
@Override public TImmutablePartitionResult updateImmutablePartition(TImmutablePartitionRequest request) throws TException { LOG.info("Receive update immutable partition: {}", request); TImmutablePartitionResult result; try { result = updateImmutablePartitionInternal(request); ...
@Test public void testImmutablePartitionApi() throws TException { Database db = GlobalStateMgr.getCurrentState().getDb("test"); OlapTable table = (OlapTable) db.getTable("site_access_auto"); List<Long> partitionIds = table.getPhysicalPartitions().stream() .map(PhysicalPartiti...
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testLatLonQuery() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setLon("4"); weatherConfiguration.setLat("52"); weatherConfiguration.setMode(WeatherMode.XML); weatherConfiguration.setLanguage(...
void placeOrder(Order order) { sendShippingRequest(order); }
@Test void testPlaceOrder() throws Exception { long paymentTime = timeLimits.paymentTime(); long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; Commander c = buildCommanderObject(tru...
static final String[] getPrincipalNames(String keytabFileName) throws IOException { Keytab keytab = Keytab.loadKeytab(new File(keytabFileName)); Set<String> principals = new HashSet<>(); List<PrincipalName> entries = keytab.getPrincipals(); for (PrincipalName entry : entries) { principals.add(entr...
@Test public void testGetPrincipalNamesMissingPattern() throws IOException { createKeyTab(testKeytab, new String[]{"test/testhost@testRealm"}); try { KerberosUtil.getPrincipalNames(testKeytab, null); Assert.fail("Exception should have been thrown"); } catch (Exception e) { //expects exce...
@Udf(description = "Returns the natural logarithm (base e) of an INT value.") public Double ln( @UdfParameter( value = "value", description = "the value get the natual logarithm of." ) final Integer value ) { return ln(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNull() { assertThat(udf.ln((Integer)null), is(nullValue())); assertThat(udf.ln((Long)null), is(nullValue())); assertThat(udf.ln((Double)null), is(nullValue())); }
public Optional<Violation> validate(IndexSetConfig newConfig) { // Don't validate prefix conflicts in case of an update if (Strings.isNullOrEmpty(newConfig.id())) { final Violation prefixViolation = validatePrefix(newConfig); if (prefixViolation != null) { return...
@Test public void testWarmTierKeywordReserved() { IndexSetConfig config = testIndexSetConfig().toBuilder().indexPrefix("warm_").build(); this.validator = new IndexSetValidator(indexSetRegistry, elasticsearchConfiguration, dataTieringOrchestrator, dataTieringChecker); assertThat(validator.v...
public static String getRemoteAddr(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String proxyHeader = request.getHeader("X-Forwarded-For"); if (proxyHeader != null && ProxyServers.isProxyServer(remoteAddr)) { final String clientAddr = proxyHeader.split(",")[0].trim(); ...
@Test public void testRemoteAddr() { assertEquals(clientAddr, getRemoteAddr(clientAddr, null, false)); }
protected static String cleanName(String name) { name = FairSchedulerUtilities.trimQueueName(name); if (name.contains(DOT)) { String converted = name.replaceAll("\\.", DOT_REPLACEMENT); LOG.warn("Name {} is converted to {} when it is used as a queue name.", name, converted); return c...
@Test public void testCleanName() { // permutations of dot placements final String clean = "clean"; final String dotted = "not.clean"; final String multiDot = "more.un.clean"; final String seqDot = "not..clean"; final String unTrimmed = " .invalid. "; // not really a valid queue String cl...
@NonNull @VisibleForTesting static String[] getPermissionsStrings(int requestCode) { switch (requestCode) { case CONTACTS_PERMISSION_REQUEST_CODE -> { return new String[] {Manifest.permission.READ_CONTACTS}; } case NOTIFICATION_PERMISSION_REQUEST_CODE -> { if (Build.VERSION.SDK_I...
@Test @Config(sdk = S_V2) public void testGetPermissionsStringsNotificationsOldDevice() { Assert.assertArrayEquals( new String[0], PermissionRequestHelper.getPermissionsStrings( PermissionRequestHelper.NOTIFICATION_PERMISSION_REQUEST_CODE)); }
public static boolean matchAnyDomain(String name, Collection<String> patterns) { if (patterns == null || patterns.isEmpty()) { return false; } for (String pattern : patterns) { if (matchDomain(name, pattern)) { return true; } } ...
@Test public void testMatchAnyDomain() { assertTrue(AddressUtil.matchAnyDomain("hazelcast.com", singletonList("hazelcast.com"))); assertFalse(AddressUtil.matchAnyDomain("hazelcast.com", null)); assertFalse(AddressUtil.matchAnyDomain("hazelcast.com", Collections.emptyList())); assert...
@Override public V get(Object k) { return containsKey(k) ? super.get(k) : defaultValue; }
@Test public void defaultToFive() { map = new DefaultHashMap<>(5); loadMap(); assertEquals("missing 1", 1, (int) map.get(ONE)); assertEquals("missing 2", 2, (int) map.get(TWO)); assertEquals("three?", 5, (int) map.get(THREE)); assertEquals("four?", 5, (int) map.get(FO...
public boolean statsHaveChanged() { if (!aggregatedStats.hasUpdatesFromAllDistributors()) { return false; } for (ContentNodeStats contentNodeStats : aggregatedStats.getStats()) { int nodeIndex = contentNodeStats.getNodeIndex(); boolean currValue = mayHaveMerge...
@Test void stats_have_changed_if_in_sync_node_not_found_in_previous_stats() { Fixture f = Fixture.fromStats(stats().inSync(0)); assertTrue(f.statsHaveChanged()); }
@Config("sql.forced-session-time-zone") @ConfigDescription("User session time zone overriding value sent by client") public SqlEnvironmentConfig setForcedSessionTimeZone(@Nullable String timeZoneId) { this.forcedSessionTimeZone = Optional.ofNullable(timeZoneId) .map(TimeZoneKey::getT...
@Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("sql.forced-session-time-zone", "UTC") .build(); SqlEnvironmentConfig expected = new SqlEnvironmentConfig() .setFor...
@NotNull @Override public List<InetAddress> lookup(@NotNull String host) throws UnknownHostException { InetAddress address = InetAddress.getByName(host); if (configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY).orElse(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE) && (address.isLoopbackAddress() || addr...
@Test public void lookup_fail_on_192_168_1_21() throws UnknownHostException, SocketException { InetAddress inetAddress = InetAddress.getByName(HttpUrl.parse("https://192.168.1.21/").host()); when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY)) .thenReturn(Optional.of(true)); when(netwo...
@Override public void checkForInvalidityOfToken(String tokenId) { final boolean isTokenInvalid = invalidTokenRepository.findByTokenId(tokenId).isPresent(); if (isTokenInvalid) { throw new TokenAlreadyInvalidatedException(tokenId); } }
@Test void givenInvalidToken_whenCheckForInvalidityOfToken_thenThrowTokenAlreadyInvalidatedException() { // Given String tokenId = "invalidToken"; InvalidTokenEntity invalidTokenEntity = InvalidTokenEntity.builder().tokenId(tokenId).build(); // When when(invalidTokenReposit...
@Override public List<TableInfo> getTableList(Long dataSourceConfigId, String nameLike, String commentLike) { List<TableInfo> tables = getTableList0(dataSourceConfigId, null); return tables.stream().filter(tableInfo -> (StrUtil.isEmpty(nameLike) || tableInfo.getName().contains(nameLike)) ...
@Test public void testGetTableList() { // 准备参数 Long dataSourceConfigId = randomLongId(); // mock 方法 DataSourceConfigDO dataSourceConfig = new DataSourceConfigDO().setUsername("sa").setPassword("") .setUrl("jdbc:h2:mem:testdb"); when(dataSourceConfigService.get...
@Override public ChannelFuture writeRstStream(ChannelHandlerContext ctx, int streamId, long errorCode, ChannelPromise promise) { // Delegate to the lifecycle manager for proper updating of connection state. return lifecycleManager.resetStream(ctx, streamId, errorCode, promise); }
@Test public void rstStreamWriteForUnknownStreamShouldIgnore() throws Exception { ChannelPromise promise = newPromise(); encoder.writeRstStream(ctx, 5, PROTOCOL_ERROR.code(), promise); verify(writer, never()).writeRstStream(eq(ctx), anyInt(), anyLong(), eq(promise)); }
public static NotFoundException clusterNotFound(String appId, String clusterName) { return new NotFoundException("cluster not found for appId:%s clusterName:%s", appId, clusterName); }
@Test public void testClusterNotFoundException() { NotFoundException exception = NotFoundException.clusterNotFound(appId, clusterName); assertEquals(exception.getMessage(), "cluster not found for appId:app-1001 clusterName:test"); }
@Override public OpenstackVtap updateVtap(OpenstackVtap description) { checkNotNull(description, VTAP_DESC_NULL, "vtap"); Set<DeviceId> txDevices = description.type().isValid(Type.VTAP_TX) ? getEdgeDevice(Type.VTAP_TX, description.vtapCriterion()) : ImmutableSet.of(); Set<De...
@Test public void testUpdateNotExistingVtap() { assertNull(target.updateVtap(VTAP_1)); }
@Override public boolean tryReturnRecordAt(boolean isAtSplitPoint, Long recordStart) { return tryReturnRecordAt(isAtSplitPoint, recordStart.longValue()); }
@Test public void testTryReturnRecordSimpleSparse() throws Exception { OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); assertTrue(tracker.tryReturnRecordAt(true, 110)); assertTrue(tracker.tryReturnRecordAt(true, 140)); assertTrue(tracker.tryReturnRecordAt(true, 183)); assertFalse(tr...
@Override public ShenyuContext decorator(final ShenyuContext shenyuContext, final MetaData metaData) { String path = shenyuContext.getPath(); shenyuContext.setMethod(path); shenyuContext.setRealUrl(path); shenyuContext.setRpcType(RpcTypeEnum.SPRING_CLOUD.getName()); shenyuCon...
@Test public void testDecorator() { MetaData metaData = null; ShenyuContext shenyuContext = new ShenyuContext(); springCloudShenyuContextDecorator.decorator(shenyuContext, metaData); Assertions.assertNull(shenyuContext.getMethod()); Assertions.assertNull(shenyuContext.getReal...
@Override public boolean hasAccess( RepositoryFilePermission perm ) throws KettleException { if ( hasAccess == null ) { hasAccess = new HashMap<RepositoryFilePermission, Boolean>(); } if ( hasAccess.get( perm ) == null ) { hasAccess.put( perm, new Boolean( aclService.hasAccess( getObjectId(), ...
@Test public void testAccess() throws Exception { when( mockAclService.hasAccess( mockObjectId, RepositoryFilePermission.READ ) ).thenReturn( true ); when( mockAclService.hasAccess( mockObjectId, RepositoryFilePermission.WRITE ) ).thenReturn( false ); assertTrue( uiPurRepDir.hasAccess( RepositoryFilePerm...
public ZLoop(Context context) { Objects.requireNonNull(context, "Context has to be supplied for ZLoop"); this.context = context; pollers = new ArrayList<>(); timers = new ArrayList<>(); zombies = new ArrayList<>(); newTimers = new ArrayList<>(); }
@Test public void testZLoop() { int rc; // setUp() should create the context assert (ctx != null); ZLoop loop = new ZLoop(ctx); assert (loop != null); ZLoop.IZLoopHandler timerEvent = (loop12, item, arg) -> { ((Socket) arg).send("PING", 0); ...
@Override public Long zLexCount(byte[] key, org.springframework.data.domain.Range range) { String min = value(range.getLowerBound(), "-"); String max = value(range.getUpperBound(), "+"); return read(key, StringCodec.INSTANCE, ZLEXCOUNT, key, min, max); }
@Test public void testZLexCount() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate....
public static int getIdForValueMeta( String valueMetaName ) { for ( PluginInterface plugin : pluginRegistry.getPlugins( ValueMetaPluginType.class ) ) { if ( valueMetaName != null && valueMetaName.equalsIgnoreCase( plugin.getName() ) ) { return Integer.valueOf( plugin.getIds()[0] ); } } r...
@Test public void testGetIdForValueMeta() { assertEquals( ValueMetaInterface.TYPE_NONE, ValueMetaFactory.getIdForValueMeta( null ) ); assertEquals( ValueMetaInterface.TYPE_NONE, ValueMetaFactory.getIdForValueMeta( "" ) ); assertEquals( ValueMetaInterface.TYPE_NONE, ValueMetaFactory.getIdForValueMeta( "Non...
@ScalarOperator(NOT_EQUAL) @SqlType(StandardTypes.BOOLEAN) @SqlNullable public static Boolean notEqual(@SqlType(StandardTypes.BOOLEAN) boolean left, @SqlType(StandardTypes.BOOLEAN) boolean right) { return left != right; }
@Test public void testNotEqual() { assertFunction("true <> true", BOOLEAN, false); assertFunction("true <> false", BOOLEAN, true); assertFunction("false <> true", BOOLEAN, true); assertFunction("false <> false", BOOLEAN, false); }
protected boolean isListEmpty(ArrayNode json) { for (JsonNode node : json) { if (!isNodeEmpty(node)) { return false; } } return true; }
@Test public void isListEmpty_nodeWithEmptyField() { ArrayNode json = new ArrayNode(factory); ObjectNode nestedNode = new ObjectNode(factory); json.add(nestedNode); nestedNode.set("emptyField", new TextNode("")); assertThat(expressionEvaluator.isListEmpty(json)).isTr...
public static CvssV2 vectorToCvssV2(String vectorString, Double baseScore) { if (vectorString.startsWith("CVSS:")) { throw new IllegalArgumentException("Not a valid CVSSv2 vector string: " + vectorString); } final String[] metricStrings = vectorString.substring(vectorString.indexOf('...
@Test public void testVectorToCvssV2() { String vectorString = "/AV:L/AC:L/Au:N/C:N/I:N/A:C"; Double baseScore = 1.0; CvssV2 result = CvssUtil.vectorToCvssV2(vectorString, baseScore); assertEquals(CvssV2Data.Version._2_0, result.getCvssData().getVersion()); assertEquals(CvssV...
@Override public long skip(long ns) throws IOException { ensureOpen(); if (mPosition >= mLimit) { return 0; } long n = Math.min(mLimit - mPosition, ns); n = Math.max(-mPosition, n); mPosition += n; return n; }
@Test void testSkipTooLong() throws IOException { UnsafeStringReader reader = new UnsafeStringReader("abc"); reader.skip(10); long skip = reader.skip(10); assertThat(skip, is(0L)); }
@Override public void start() throws Exception { LOG.debug("Start leadership runner for job {}.", getJobID()); leaderElection.startLeaderElection(this); }
@Test void testLeaderAddressOfOutdatedLeaderIsIgnored() throws Exception { final CompletableFuture<String> leaderAddressFuture = new CompletableFuture<>(); final JobMasterServiceLeadershipRunner jobManagerRunner = newJobMasterServiceLeadershipRunnerBuilder() ....
public static ValueLabel formatBytes(long bytes) { return new ValueLabel(bytes, BYTES_UNIT); }
@Test public void formatMegaBytes() { vl = TopoUtils.formatBytes(3_000_000L); assertEquals(AM_WM, TopoUtils.Magnitude.MEGA, vl.magnitude()); assertEquals(AM_WL, "2.86 MB", vl.toString()); }
@Override public Set<String> tags() { if (tags == null) { return Set.of(); } else { return ImmutableSet.copyOf(tags); } }
@Test void tags_whenNull_shouldReturnEmptySet() { assertThat(issue.tags()).isEmpty(); }