focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String getInterfaceName(Invoker invoker) {
return getInterfaceName(invoker, false);
} | @Test
public void testGetInterfaceName() {
URL url = URL.valueOf("dubbo://127.0.0.1:2181")
.addParameter(CommonConstants.VERSION_KEY, "1.0.0")
.addParameter(CommonConstants.GROUP_KEY, "grp1")
.addParameter(CommonConstants.INTERFACE_KEY, DemoService.class.getN... |
public static String getAppId(final String originalFilename) {
checkThreePart(originalFilename);
return getThreePart(originalFilename)[0];
} | @Test
public void getAppId() {
final String application = ConfigFileUtils.getAppId("application+default+application.properties");
assertEquals("application", application);
final String abc = ConfigFileUtils.getAppId("abc+default+application.yml");
assertEquals("abc", abc);
} |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Retain Ordering cannot be altered")
public void testMergeDifferentRetainOrdering() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("r... |
@Override
public List<String> getRegisterData(final String key) {
try {
KV kvClient = etcdClient.getKVClient();
GetOption option = GetOption.newBuilder().isPrefix(true).build();
GetResponse response = kvClient.get(bytesOf(key), option).get();
return response.g... | @Test
void testGetRegisterData() throws InterruptedException, ExecutionException {
final String key = "key";
final KV kv = mock(KV.class);
when(etcdClient.getKVClient()).thenReturn(kv);
final GetResponse getResponse = mock(GetResponse.class);
when(getResponse.getKvs()).thenRe... |
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
String serverNamespace = event.getApplicationContext().getServerNamespace();
if (SPRING_MANAGEMENT_CONTEXT_NAMESPACE.equals(serverNamespace)) {
// ignore
// fix#issue https://github.com/alibaba/nacos/... | @Test
void testEnvSetPort() {
ServletWebServerApplicationContext context = new ServletWebServerApplicationContext();
context.setServerNamespace("management");
Mockito.when(mockEvent.getApplicationContext()).thenReturn(context);
serverMemberManager.onApplicationEvent(mockEvent);
... |
public List<ContainerLogMeta> collect(
LogAggregationFileController fileController) throws IOException {
List<ContainerLogMeta> containersLogMeta = new ArrayList<>();
RemoteIterator<FileStatus> appDirs = fileController.
getApplicationDirectoriesOfUser(logsRequest.getUser());
while (appDirs.ha... | @Test
void testSingleNodeRequest() throws IOException {
ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder request =
new ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder();
request.setAppId(null);
request.setContainerId(null);
request.setFileName(null);
request.setFileSize(null);
... |
@VisibleForTesting
void recover() {
try (DbSession dbSession = dbClient.openSession(false)) {
Profiler profiler = Profiler.create(LOGGER).start();
long beforeDate = system2.now() - minAgeInMs;
IndexingResult result = new IndexingResult();
Collection<EsQueueDto> items = dbClient.esQueueDao... | @Test
public void recent_records_are_not_recovered() {
EsQueueDto item = insertItem(FOO_TYPE, "f1");
SuccessfulFakeIndexer indexer = new SuccessfulFakeIndexer(FOO_TYPE);
// do not advance in time
underTest = newRecoveryIndexer(indexer);
underTest.recover();
assertThatQueueHasSize(1);
as... |
public int getNumServersQueried() {
// Lazily load the field from the JsonNode to avoid reading the stats when not needed.
return _brokerResponse.has(NUM_SERVERS_QUERIED) ? _brokerResponse.get(NUM_SERVERS_QUERIED).asInt() : -1;
} | @Test
public void testGetNumServersQueried() {
// Run the test
final int result = _executionStatsUnderTest.getNumServersQueried();
// Verify the results
assertEquals(10, result);
} |
public boolean hasRequiredCoordinators()
{
return currentCoordinatorCount >= coordinatorMinCountActive;
} | @Test
public void testHasRequiredCoordinators()
throws InterruptedException
{
assertFalse(monitor.hasRequiredCoordinators());
for (int i = numResourceManagers.get(); i < DESIRED_COORDINATOR_COUNT_ACTIVE; i++) {
addCoordinator(nodeManager);
}
assertTrue(mon... |
@Override
public ProcNodeInterface lookup(String jobIdStr) throws AnalysisException {
throw new AnalysisException("Not support");
} | @Test(expected = AnalysisException.class)
public void testLookup() throws AnalysisException {
optimizeProcDir.lookup("");
} |
public static GenericData get() {
return INSTANCE;
} | @Test
void arrayRemove() {
Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
GenericArray<Integer> array = new GenericData.Array<>(10, schema);
array.clear();
for (int i = 0; i < 10; ++i)
array.add(i);
assertEquals(10, array.size());
assertEquals(Integer.valueOf(0), arr... |
public JwtBuilder jwtBuilder() {
return new JwtBuilder();
} | @Test
void testParseWith48Key() {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567890120124568aa9012345"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
assertTrue(token.startsWith(NacosSignatureAlgorithm.HS384... |
public TreeCache start() throws Exception {
Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started");
if (createParentNodes) {
client.createContainers(root.path);
}
client.getConnectionStateListenable().addListener(connectionSt... | @Test
public void testStartEmpty() throws Exception {
cache = newTreeCacheWithListeners(client, "/test");
cache.start();
assertEvent(TreeCacheEvent.Type.INITIALIZED);
client.create().forPath("/test");
assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test");
assertNoMore... |
@Override
public Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit) {
requireNonNull(executor);
requireNonNull(command);
requireNonNull(unit);
if (scheduledExecutorService.isShutdown()) {
return DisabledFuture.INSTANCE;
}
return scheduledExecutorService.s... | @Test(dataProvider = "runnableSchedulers")
public void scheduler_exception(Scheduler scheduler) {
var thread = new AtomicReference<Thread>();
Executor executor = task -> {
thread.set(Thread.currentThread());
throw new IllegalStateException();
};
var future = scheduler.schedule(executor, ()... |
T call() throws IOException, RegistryException {
String apiRouteBase = "https://" + registryEndpointRequestProperties.getServerUrl() + "/v2/";
URL initialRequestUrl = registryEndpointProvider.getApiRoute(apiRouteBase);
return call(initialRequestUrl);
} | @Test
public void testCall_logErrorOnBrokenPipe() throws IOException, RegistryException {
IOException ioException = new IOException("this is due to broken pipe");
setUpRegistryResponse(ioException);
try {
endpointCaller.call();
Assert.fail();
} catch (IOException ex) {
Assert.asser... |
@Override
public String getDataSource() {
return DataSourceConstant.MYSQL;
} | @Test
void testGetDataSource() {
String dataSource = configTagsRelationMapperByMySql.getDataSource();
assertEquals(DataSourceConstant.MYSQL, dataSource);
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testOnTimerDeclaredInSuperclass() throws Exception {
class DoFnDeclaringTimerAndProcessElement extends DoFn<KV<String, Integer>, Long> {
public static final String TIMER_ID = "my-timer-id";
@TimerId(TIMER_ID)
private final TimerSpec bizzle = TimerSpecs.timer(TimeDomain.EVENT_T... |
public static void sort(short[] array, ShortComparator comparator) {
sort(array, 0, array.length, comparator);
} | @Test
void test_sorting_custom_comparator() {
short[] array = {4, 2, 5};
PrimitiveArraySorter.sort(array, (a, b) -> Short.compare(b, a)); // Sort using inverse ordering.
short[] expected = {5, 4, 2};
assertArrayEquals(expected, array);
} |
@PUT
@Path("/{connector}/config")
@Operation(summary = "Create or reconfigure the specified connector")
public Response putConnectorConfig(final @PathParam("connector") String connector,
final @Context HttpHeaders headers,
final @... | @Test
public void testPutConnectorConfigWithSpecialCharsInName() throws Throwable {
final ArgumentCaptor<Callback<Herder.Created<ConnectorInfo>>> cb = ArgumentCaptor.forClass(Callback.class);
expectAndCallbackResult(cb, new Herder.Created<>(true, new ConnectorInfo(CONNECTOR_NAME_SPECIAL_CHARS, CONN... |
public T getRecordingProxy()
{
return _templateProxy;
} | @Test
public void testMethodsInheritedFromObjectOnProxy()
{
PatchTreeRecorder<PatchTreeTestModel> pc = makeOne();
PatchTreeTestModel testModel = pc.getRecordingProxy();
Assert.assertEquals(testModel.hashCode(), testModel.hashCode());
Assert.assertNotNull(testModel.toString());
Assert.assertTrue... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
JsonPrimitive other = (JsonPrimitive) obj;
if (value == null) {
return other.value == null;
}
if (isIntegral(this) && isI... | @Test
public void testBigDecimalEqualsTransitive() {
JsonPrimitive x = new JsonPrimitive(new BigDecimal("0"));
JsonPrimitive y = new JsonPrimitive(0.0d);
JsonPrimitive z = new JsonPrimitive(new BigDecimal("0.00"));
assertThat(x.equals(y)).isTrue();
assertThat(y.equals(z)).isTrue();
// ... imp... |
public GenericRecord convert(String json, Schema schema) {
try {
Map<String, Object> jsonObjectMap = mapper.readValue(json, Map.class);
return convertJsonToAvro(jsonObjectMap, schema, shouldSanitize, invalidCharMask);
} catch (IOException e) {
throw new HoodieIOException(e.getMessage(), e);
... | @Test
public void basicConversion() throws IOException {
Schema simpleSchema = SchemaTestUtil.getSimpleSchema();
String name = "John Smith";
int number = 1337;
String color = "Blue. No yellow!";
Map<String, Object> data = new HashMap<>();
data.put("name", name);
data.put("favorite_number",... |
public Coin getBlockInflation(int height) {
return Coin.FIFTY_COINS.shiftRight(height / getSubsidyDecreaseBlockCount());
} | @Test
public void getBlockInflation() {
assertEquals(Coin.FIFTY_COINS, BITCOIN_PARAMS.getBlockInflation(209998));
assertEquals(Coin.FIFTY_COINS, BITCOIN_PARAMS.getBlockInflation(209999));
assertEquals(Coin.FIFTY_COINS.div(2), BITCOIN_PARAMS.getBlockInflation(210000));
assertEquals(Co... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFu... | @Test
void assertCreateWithSelectStatementFromInformationSchemaOfSchemaTable() {
initProxyContext(Collections.emptyMap());
SimpleTableSegment tableSegment = new SimpleTableSegment(new TableNameSegment(10, 13, new IdentifierValue("SCHEMATA")));
tableSegment.setOwner(new OwnerSegment(7, 8, new... |
@Override
public Collection<String> getXADriverClassNames() {
return Collections.singletonList("com.microsoft.sqlserver.jdbc.SQLServerXADataSource");
} | @Test
void assertGetXADriverClassName() {
assertThat(new SQLServerXADataSourceDefinition().getXADriverClassNames(), is(Collections.singletonList("com.microsoft.sqlserver.jdbc.SQLServerXADataSource")));
} |
public static String sanitizeUri(String uri) {
// use xxxxx as replacement as that works well with JMX also
String sanitized = uri;
if (uri != null) {
sanitized = ALL_SECRETS.matcher(sanitized).replaceAll("$1=xxxxxx");
sanitized = USERINFO_PASSWORD.matcher(sanitized).repl... | @Test
public void testSanitizeAccessToken() {
String out1 = URISupport
.sanitizeUri("google-sheets-stream://spreadsheets?accessToken=MY_TOKEN&clientId=foo&clientSecret=MY_SECRET");
assertEquals("google-sheets-stream://spreadsheets?accessToken=xxxxxx&clientId=xxxxxx&clientSecret=xxxxx... |
public static MemberLookup createLookUp(ServerMemberManager memberManager) throws NacosException {
if (!EnvUtil.getStandaloneMode()) {
String lookupType = EnvUtil.getProperty(LOOKUP_MODE_TYPE);
LookupType type = chooseLookup(lookupType);
LOOK_UP = find(type);
curr... | @Test
void createLookUpAddressServerMemberLookup() throws Exception {
EnvUtil.setIsStandalone(false);
mockEnvironment.setProperty(LOOKUP_MODE_TYPE, "address-server");
memberLookup = LookupFactory.createLookUp(memberManager);
assertEquals(AddressServerMemberLookup.class, memberLookup.... |
@Override
public boolean isQualified(final SQLStatementContext sqlStatementContext, final ReadwriteSplittingDataSourceGroupRule rule, final HintValueContext hintValueContext) {
return connectionContext.getTransactionContext().isInTransaction();
} | @Test
void assertWriteRouteTransaction() {
ConnectionContext connectionContext = mock(ConnectionContext.class);
TransactionConnectionContext transactionConnectionContext = mock(TransactionConnectionContext.class);
when(connectionContext.getTransactionContext()).thenReturn(transactionConnecti... |
public boolean delete(String eventDefinitionId) {
return doDelete(eventDefinitionId,
() -> eventDefinitionService.deleteUnregister(eventDefinitionId) > 0);
} | @Test
@MongoDBFixtures("event-processors.json")
public void delete() {
assertThat(eventDefinitionService.get("54e3deadbeefdeadbeef0000")).isPresent();
assertThat(jobDefinitionService.get("54e3deadbeefdeadbeef0001")).isPresent();
assertThat(jobTriggerService.get("54e3deadbeefdeadbeef0002"... |
public InstanceType instanceType() {
return instanceType;
} | @Test
public void checkConstruction() {
assertThat(event1.type(), is(ClusterEvent.Type.INSTANCE_ADDED));
assertThat(event1.subject(), is(cNode1));
assertThat(event1.instanceType(), is(ClusterEvent.InstanceType.UNKNOWN));
assertThat(event7.time(), is(time));
assertThat(event7... |
public boolean setImpacts(DefaultIssue issue, Map<SoftwareQuality, Severity> previousImpacts, IssueChangeContext context) {
Map<SoftwareQuality, Severity> currentImpacts = new EnumMap<>(issue.impacts());
if (!previousImpacts.equals(currentImpacts)) {
issue.replaceImpacts(currentImpacts);
issue.setUp... | @Test
void setImpacts_whenImpactAdded_shouldBeUpdated() {
Map<SoftwareQuality, Severity> currentImpacts = Map.of(SoftwareQuality.RELIABILITY, Severity.LOW);
Map<SoftwareQuality, Severity> newImpacts = Map.of(SoftwareQuality.MAINTAINABILITY, Severity.HIGH);
issue.replaceImpacts(newImpacts);
boolean up... |
void allocateCollectionField( Object object, BeanInjectionInfo beanInjectionInfo, String fieldName ) {
BeanInjectionInfo.Property property = getProperty( beanInjectionInfo, fieldName );
String groupName = ( property != null ) ? property.getGroupName() : null;
if ( groupName == null ) {
return;
}... | @Test
public void allocateCollectionField_List() {
BeanInjector bi = new BeanInjector(null );
BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class );
MetaBeanLevel1 mbl1 = new MetaBeanLevel1();
mbl1.setSub( new MetaBeanLevel2() );
// should set other field based on this size
mbl... |
public static Document parseXml(final InputStream is) throws Exception {
return parseXml(is, null);
} | @Test
public void testParseCamelContextForceNamespace() throws Exception {
InputStream fis = Files.newInputStream(Paths.get("src/test/resources/org/apache/camel/util/camel-context.xml"));
Document dom = XmlLineNumberParser.parseXml(fis, null, "camelContext", "http://camel.apache.org/schema/spring");... |
@Override
public List<Input> allOfThisNode(final String nodeId) {
final List<BasicDBObject> query = ImmutableList.of(
new BasicDBObject(MessageInput.FIELD_NODE_ID, nodeId),
new BasicDBObject(MessageInput.FIELD_GLOBAL, true));
final List<DBObject> ownInputs = query(Inp... | @Test
@MongoDBFixtures("InputServiceImplTest.json")
public void allOfThisNodeReturnsGlobalInputsIfNodeIDDoesNotExist() {
final List<Input> inputs = inputService.allOfThisNode("cd03ee44-b2a7-0000-0000-000000000000");
assertThat(inputs).hasSize(1);
} |
@Override
public List<MenuDO> getMenuList() {
return menuMapper.selectList();
} | @Test
public void testGetMenuList() {
// mock 数据
MenuDO menuDO = randomPojo(MenuDO.class, o -> o.setName("芋艿").setStatus(CommonStatusEnum.ENABLE.getStatus()));
menuMapper.insert(menuDO);
// 测试 status 不匹配
menuMapper.insert(cloneIgnoreId(menuDO, o -> o.setStatus(CommonStatusEnu... |
@Override
public PageResult<DiyPageDO> getDiyPagePage(DiyPagePageReqVO pageReqVO) {
return diyPageMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetDiyPagePage() {
// mock 数据
DiyPageDO dbDiyPage = randomPojo(DiyPageDO.class, o -> { // 等会查询到
o.setName(null);
o.setCreateTime(null);
});
diyPageMapper.insert(dbDiyPage);
/... |
public Node parse() throws ScanException {
return E();
} | @Test
public void testKeyword() throws Exception {
{
Parser<Object> p = new Parser<>("hello%xyz");
Node t = p.parse();
Node witness = new Node(Node.LITERAL, "hello");
witness.next = new SimpleKeywordNode("xyz");
Assertions.assertEquals(witness, t)... |
@Override
public long freeze() {
finalizeSnapshotWithFooter();
appendBatches(accumulator.drain());
snapshot.freeze();
accumulator.close();
return snapshot.sizeInBytes();
} | @Test
void testBuilderKRaftVersion1WithoutVoterSet() {
OffsetAndEpoch snapshotId = new OffsetAndEpoch(100, 10);
int maxBatchSize = 1024;
AtomicReference<ByteBuffer> buffer = new AtomicReference<>(null);
RecordsSnapshotWriter.Builder builder = new RecordsSnapshotWriter.Builder()
... |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test(expected = NullPointerException.class)
public void testInvalidValueOfNullArrayIPv4() {
Ip4Prefix ipPrefix;
byte[] value;
value = null;
ipPrefix = Ip4Prefix.valueOf(value, 24);
} |
public static int bytesToIntLE(byte[] bytes, int off) {
return (bytes[off + 3] << 24) + ((bytes[off + 2] & 255) << 16)
+ ((bytes[off + 1] & 255) << 8) + (bytes[off] & 255);
} | @Test
public void testBytesToIntLE() {
assertEquals(-12345,
ByteUtils.bytesToIntLE(INT_12345_LE, 0));
} |
public static String format(Object x) {
if (x != null) {
return format(x.toString());
} else {
return StrUtil.EMPTY;
}
} | @Test
public void testFormatDecimal() {
// 测试传入小数的情况
String result = NumberWordFormatter.format(1234.56);
assertEquals("ONE THOUSAND TWO HUNDRED AND THIRTY FOUR AND CENTS FIFTY SIX ONLY", result);
} |
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
ObjectUtil.checkNotNull(command, "command");
ObjectUtil.checkNotNull(unit, "unit");
if (initialDelay < 0) {
throw new IllegalArgumentException(
... | @Test
public void testScheduleWithFixedDelayNegative() {
final TestScheduledEventExecutor executor = new TestScheduledEventExecutor();
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
executor.scheduleWithFixedD... |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (d... | @Test
void throws_when_conversion_fails() {
registry.defineDocStringType(jsonNodeForJsonThrowsException);
DocString docString = DocString.create("{\"hello\":\"world\"}", "json");
CucumberDocStringException exception = assertThrows(
CucumberDocStringException.class,
()... |
public Set<? extends AuthenticationRequest> getRequest(final Host bookmark, final LoginCallback prompt)
throws LoginCanceledException {
final StringBuilder url = new StringBuilder();
url.append(bookmark.getProtocol().getScheme().toString()).append("://");
url.append(bookmark.getHostn... | @Test(expected = LoginCanceledException.class)
public void testGetDefault2NoTenant() throws Exception {
final SwiftAuthenticationService s = new SwiftAuthenticationService();
final Credentials credentials = new Credentials("u", "P");
final SwiftProtocol protocol = new SwiftProtocol() {
... |
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (!Strings.isNullOrEmpty(request.getParameter("error"))) {
// there's an error coming back from the server, need to handle this
han... | @Test
public void attemptAuthentication_error() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getParameter("error")).thenReturn("Error");
Mockito.when(request.getParameter("error_description")).thenReturn("Description");
Mockito.when(request.getPa... |
public void registerStrategy(BatchingStrategy<?, ?, ?> strategy) {
_strategies.add(strategy);
} | @Test
public void testSingletonsInvoked() {
RecordingStrategy<Integer, Integer, String> strategy =
new RecordingStrategy<>((key, promise) -> promise.done(String.valueOf(key)), key -> key);
_batchingSupport.registerStrategy(strategy);
Task<String> task = Task.par(strategy.batchable(0), strategy.b... |
public static AzureStoragePath parseAzureStoragePath(String path) {
try {
URI uri = new URI(path);
String rawAuthority = uri.getRawAuthority();
if (rawAuthority == null) {
throw new URISyntaxException(path, "Illegal azure storage path");
}
... | @Test
public void testAzurePathParseWithWASB() {
String uri = "wasb://bottle@smith.blob.core.windows.net/path/1/2";
AzureStoragePath path = CredentialUtil.parseAzureStoragePath(uri);
Assert.assertEquals(path.getContainer(), "bottle");
Assert.assertEquals(path.getStorageAccount(), "sm... |
public static HashingAlgorithm getHashingAlgorithm(String password)
{
if (password.startsWith("$2y")) {
if (getBCryptCost(password) < BCRYPT_MIN_COST) {
throw new HashedPasswordException("Minimum cost of BCrypt password must be " + BCRYPT_MIN_COST);
}
retu... | @Test
public void testHashingAlgorithmPBKDF2()
{
String password = "1000:5b4240333032306164:f38d165fce8ce42f59d366139ef5d9e1ca1247f0e06e503ee1a611dd9ec40876bb5edb8409f5abe5504aab6628e70cfb3d3a18e99d70357d295002c3d0a308a0";
assertEquals(getHashingAlgorithm(password), PBKDF2);
} |
static String asErrorJson(String message) {
try {
return Jackson.mapper().writeValueAsString(Map.of("error", message));
} catch (JsonProcessingException e) {
log.log(WARNING, "Could not encode error message to json:", e);
return "Could not encode error message to json... | @Test
void error_message_is_wrapped_in_json_object() {
var json = ErrorResponse.asErrorJson("bad");
assertEquals("{\"error\":\"bad\"}", json);
} |
static int encodeTrailingString(
final UnsafeBuffer encodingBuffer, final int offset, final int remainingCapacity, final String value)
{
final int maxLength = remainingCapacity - SIZE_OF_INT;
if (value.length() <= maxLength)
{
return encodingBuffer.putStringAscii(offset, ... | @Test
void encodeTrailingStringAsAsciiWhenPayloadIsSmallerThanMaxMessageSizeWithoutHeader()
{
final int offset = 17;
final int remainingCapacity = 22;
final int encodedLength = encodeTrailingString(buffer, offset, remainingCapacity, "ab©d️");
assertEquals(SIZE_OF_INT + 5, encod... |
@Override
public void initialize(ServiceConfiguration config) throws IOException, IllegalArgumentException {
String prefix = (String) config.getProperty(CONF_TOKEN_SETTING_PREFIX);
if (null == prefix) {
prefix = "";
}
this.confTokenSecretKeySettingName = prefix + CONF_TOK... | @Test(expectedExceptions = IOException.class)
public void testValidationKeyWhenBlankPublicKeyIsPassed() throws IOException {
Properties properties = new Properties();
properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_PUBLIC_KEY, " ");
ServiceConfiguration conf = new ServiceCon... |
public static final void loadAttributesMap( DataNode dataNode, AttributesInterface attributesInterface )
throws KettleException {
loadAttributesMap( dataNode, attributesInterface, NODE_ATTRIBUTE_GROUPS );
} | @Test
public void testLoadAttributesMap_CustomTag() throws Exception {
try ( MockedStatic<AttributesMapUtil> mockedAttributesMapUtil = mockStatic( AttributesMapUtil.class ) ) {
mockedAttributesMapUtil.when( () -> AttributesMapUtil.loadAttributesMap( any( DataNode.class ),
any( AttributesInterface.cl... |
public CompletableFuture<LookupResult> createLookupResult(String candidateBroker, boolean authoritativeRedirect,
final String advertisedListenerName) {
CompletableFuture<LookupResult> lookupFuture = new CompletableFuture<>();
try {
... | @Test
public void testCreateLookupResult() throws Exception {
final String candidateBroker = "localhost:8080";
final String brokerUrl = "pulsar://localhost:6650";
final String listenerUrl = "pulsar://localhost:7000";
final String listenerUrlTls = "pulsar://localhost:8000";
f... |
public static TypeTransformation legacyRawToTypeInfoRaw() {
return LegacyRawTypeTransformation.INSTANCE;
} | @Test
void testLegacyRawToTypeInfoRaw() {
DataType dataType =
DataTypes.ROW(
DataTypes.FIELD("a", DataTypes.STRING()),
DataTypes.FIELD("b", DataTypes.DECIMAL(10, 3)),
DataTypes.FIELD("c", createLegacyRaw()),
... |
@Override
@MethodNotAvailable
public void loadAll(boolean replaceExistingValues) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testLoadAll() {
adapter.loadAll(true);
} |
@Override
public String getProviderMethodProperty(String service, String method, String key) {
return config.getProperty(DynamicConfigKeyHelper.buildProviderMethodProKey(service, method, key),
DynamicHelper.DEFAULT_DYNAMIC_VALUE);
} | @Test
public void getProviderMethodProperty() {
} |
@VisibleForTesting
static List<String> tokenizeArguments(@Nullable final String args) {
if (args == null) {
return Collections.emptyList();
}
final Matcher matcher = ARGUMENTS_TOKENIZE_PATTERN.matcher(args);
final List<String> tokens = new ArrayList<>();
while (ma... | @Test
void testTokenizeSingleQuoted() {
final List<String> arguments = JarHandlerUtils.tokenizeArguments("--foo 'bar baz '");
assertThat(arguments.get(0)).isEqualTo("--foo");
assertThat(arguments.get(1)).isEqualTo("bar baz ");
} |
public static PDImageXObject createFromFile(PDDocument document, File file)
throws IOException
{
return createFromFile(document, file, 0);
} | @Test
void testByteShortPaddedWithGarbage() throws IOException
{
try (PDDocument document = new PDDocument())
{
String basePath = "src/test/resources/org/apache/pdfbox/pdmodel/graphics/image/ccittg3-garbage-padded-fields";
for (String ext : Arrays.asList(".tif", "-bigendi... |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldDeserializedJsonText() {
// Given:
final KsqlJsonDeserializer<String> deserializer =
givenDeserializerForSchema(Schema.OPTIONAL_STRING_SCHEMA, String.class);
final Map<String, String> validCoercions = ImmutableMap.<String, String>builder()
.put("true", "true")
... |
public static int getSessionCount() {
if (!instanceCreated) {
return -1;
}
// nous pourrions nous contenter d'utiliser SESSION_MAP_BY_ID.size()
// mais on se contente de SESSION_COUNT qui est suffisant pour avoir cette valeur
// (SESSION_MAP_BY_ID servira pour la fonction d'invalidateAllSessions entre autr... | @Test
public void testGetSessionCount() {
sessionListener.sessionCreated(createSessionEvent());
if (SessionListener.getSessionCount() != 1) {
fail("getSessionCount");
}
} |
public R apply(R record) {
if (predicate == null || negate ^ predicate.test(record)) {
return transformation.apply(record);
}
return record;
} | @Test
public void apply() {
applyAndAssert(true, false, transformed);
applyAndAssert(true, true, initial);
applyAndAssert(false, false, initial);
applyAndAssert(false, true, transformed);
} |
public static TimestampExtractionPolicy create(
final KsqlConfig ksqlConfig,
final LogicalSchema schema,
final Optional<TimestampColumn> timestampColumn
) {
if (!timestampColumn.isPresent()) {
return new MetadataTimestampExtractionPolicy(getDefaultTimestampExtractor(ksqlConfig));
}
... | @Test
public void shouldThrowIfLongTimestampTypeAndFormatIsSupplied() {
// Given:
final String timestamp = "timestamp";
final LogicalSchema schema = schemaBuilder2
.valueColumn(ColumnName.of(timestamp.toUpperCase()), SqlTypes.BIGINT)
.build();
// When:
assertThrows(
KsqlEx... |
@Udf
public Map<String, String> splitToMap(
@UdfParameter(
description = "Separator string and values to join") final String input,
@UdfParameter(
description = "Separator string and values to join") final String entryDelimiter,
@UdfParameter(
description = "Separator s... | @Test
public void shouldReturnEmptyForInputWithoutDelimiters() {
Map<String, String> result = udf.splitToMap("cherry", "/", ":=");
assertThat(result, is(Collections.EMPTY_MAP));
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleAliasQualifiedSelectStarOnRightJoinSource() {
// Given:
final SingleStatementContext stmt =
givenQuery("SELECT T2.* FROM TEST1 JOIN TEST2 T2 WITHIN 1 SECOND ON TEST1.ID = T2.ID;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
... |
public static Coordinate wgs84ToBd09(double lng, double lat) {
final Coordinate gcj02 = wgs84ToGcj02(lng, lat);
return gcj02ToBd09(gcj02.lng, gcj02.lat);
} | @Test
public void wgs84toBd09Test2() {
// https://tool.lu/coordinate/
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.wgs84ToBd09(122.99395597D, 44.99804071D);
assertEquals(123.00636516028885D, coordinate.getLng(), 0.00000000000001D);
// 不同jdk版本、不同架构jdk, 精度有差异,数值不完全相等,这里增加精度控制delta
// 参考:从Java Ma... |
@SuppressWarnings("unchecked")
public static void validateFormat(Object offsetData) {
if (offsetData == null)
return;
if (!(offsetData instanceof Map))
throw new DataException("Offsets must be specified as a Map");
validateFormat((Map<Object, Object>) offsetData);
... | @Test
public void testValidateFormatNotMap() {
DataException e = assertThrows(DataException.class, () -> OffsetUtils.validateFormat(new Object()));
assertThat(e.getMessage(), containsString("Offsets must be specified as a Map"));
} |
public static Profiler createIfTrace(Logger logger) {
if (logger.isTraceEnabled()) {
return create(logger);
}
return NullProfiler.NULL_INSTANCE;
} | @Test
public void create_null_profiler_if_trace_level_is_disabled() {
tester.setLevel(LoggerLevel.TRACE);
Profiler profiler = Profiler.createIfTrace(LoggerFactory.getLogger("foo"));
assertThat(profiler).isInstanceOf(DefaultProfiler.class);
tester.setLevel(LoggerLevel.DEBUG);
profiler = Profiler.c... |
@Override
public TCreatePartitionResult createPartition(TCreatePartitionRequest request) throws TException {
LOG.info("Receive create partition: {}", request);
TCreatePartitionResult result;
try {
if (partitionRequestNum.incrementAndGet() >= Config.thrift_server_max_worker_thre... | @Test
public void testCreatePartitionWithRollup() throws TException {
new MockUp<GlobalTransactionMgr>() {
@Mock
public TransactionState getTransactionState(long dbId, long transactionId) {
return new TransactionState();
}
};
Database db =... |
public Result<Boolean> deleteConfig(ConfigInfo request) {
Result<Boolean> checkResult = checkConnection(request);
if (!checkResult.isSuccess()) {
return checkResult;
}
String group = request.getGroup();
ConfigClient client = getConfigClient(request.getNamespace());
... | @Test
public void deleteConfig() {
ConfigInfo configInfo = new ConfigInfo();
configInfo.setGroup(GROUP);
configInfo.setKey(KEY);
Result<Boolean> result = configService.deleteConfig(configInfo);
Assert.assertTrue(result.isSuccess());
Assert.assertTrue(result.getData())... |
public void isEqualTo(@Nullable Object expected) {
standardIsEqualTo(expected);
} | @Test
public void isEqualToFailureWithDifferentTypesAndSameToString() {
Object a = "true";
Object b = true;
expectFailure.whenTesting().that(a).isEqualTo(b);
assertFailureKeys("expected", "an instance of", "but was", "an instance of");
assertFailureValue("expected", "true");
assertFailureValue... |
public ClientSession toClientSession()
{
return new ClientSession(
parseServer(server),
user,
source,
Optional.empty(),
parseClientTags(clientTags),
clientInfo,
catalog,
schema,
... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalidServer()
{
ClientOptions options = new ClientOptions();
options.server = "x:y";
options.toClientSession();
} |
@Override
public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
checkForDynamicType(typeDescriptor);
return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType());
} | @Test
public void testOneOfSchema() {
Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(OneOf.class));
assertEquals(ONEOF_SCHEMA, schema);
} |
public CsvReader ignoreFirstLine() {
skipFirstLineAsHeader = true;
return this;
} | @Test
void testIgnoreHeaderConfigure() {
CsvReader reader = getCsvReader();
reader.ignoreFirstLine();
assertThat(reader.skipFirstLineAsHeader).isTrue();
} |
public void createDir(File dir) {
Path dirPath = requireNonNull(dir, "dir can not be null").toPath();
if (dirPath.toFile().exists()) {
checkState(dirPath.toFile().isDirectory(), "%s is not a directory", dirPath);
} else {
try {
createDirectories(dirPath);
} catch (IOException e) {
... | @Test
public void createDir_creates_specified_directory_and_missing_parents() throws IOException {
File dir1 = new File(temp.newFolder(), "dir1");
File dir2 = new File(dir1, "dir2");
File dir = new File(dir2, "someDir");
assertThat(dir1).doesNotExist();
assertThat(dir2).doesNotExist();
assert... |
@Override
public String getValue() {
return value();
} | @Test
void testSetValue() {
StringNode n = new StringNode();
n.setValue("\"foo\"");
assertEquals("foo", n.getValue());
n.setValue("foo");
assertEquals("foo", n.getValue());
} |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenCustomQuoteCharacter_includesSpecialCharacters() {
CSVFormat csvFormat = csvFormat().withQuote(':');
PCollection<String> input =
pipeline.apply(Create.of(headerLine(csvFormat), ":a,:,1,1.1", "b,2,2.2", "c,3,3.3"));
CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvReco... |
@Override
public double score(int[] truth, int[] prediction) {
return of(truth, prediction);
} | @Test
public void test() {
System.out.println("specificity");
int[] truth = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... |
@VisibleForTesting
void saveApprove(Long userId, Integer userType, String clientId,
String scope, Boolean approved, LocalDateTime expireTime) {
// 先更新
OAuth2ApproveDO approveDO = new OAuth2ApproveDO().setUserId(userId).setUserType(userType)
.setClientId(clientId)... | @Test
public void testSaveApprove_insert() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
String scope = randomString();
Boolean approved = randomBoolean();
LocalDateTim... |
public static NamingSelector newClusterSelector(Collection<String> clusters) {
if (CollectionUtils.isNotEmpty(clusters)) {
final Set<String> set = new HashSet<>(clusters);
Predicate<Instance> filter = instance -> set.contains(instance.getClusterName());
String clusterString =... | @Test
public void testNewClusterSelector1() {
Instance ins1 = new Instance();
ins1.setClusterName("a");
Instance ins2 = new Instance();
ins2.setClusterName("b");
Instance ins3 = new Instance();
ins3.setClusterName("c");
NamingContext namingContext = m... |
public synchronized NumaResourceAllocation allocateNumaNodes(
Container container) throws ResourceHandlerException {
NumaResourceAllocation allocation = allocate(container.getContainerId(),
container.getResource());
if (allocation != null) {
try {
// Update state store.
conte... | @Test
public void testAllocateNumaNodeWithMultipleNodesForCpus() throws Exception {
NumaResourceAllocation nodeInfo = numaResourceAllocator
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 6)));
Assert... |
@Override
public KTable<Windowed<K>, V> reduce(final Reducer<V> reducer) {
return reduce(reducer, NamedInternal.empty());
} | @Test
@SuppressWarnings("unchecked")
public void shouldThrowNullPointerOnMaterializedReduceIfMaterializedIsNull() {
assertThrows(NullPointerException.class, () -> windowedStream.reduce(MockReducer.STRING_ADDER, (Materialized) null));
} |
@Override
public boolean schemaExists(SnowflakeIdentifier schema) {
Preconditions.checkArgument(
schema.type() == SnowflakeIdentifier.Type.SCHEMA,
"schemaExists requires a SCHEMA identifier, got '%s'",
schema);
if (!databaseExists(SnowflakeIdentifier.ofDatabase(schema.databaseName()))... | @SuppressWarnings("unchecked")
@Test
public void testSchemaExists() throws SQLException {
when(mockResultSet.next())
.thenReturn(true)
.thenReturn(false)
.thenReturn(true)
.thenReturn(false);
when(mockResultSet.getString("name")).thenReturn("DB1").thenReturn("SCHEMA1");
w... |
@Override
public void addJobStorageOnChangeListener(StorageProviderChangeListener listener) {
onChangeListeners.add(listener);
startTimerToSendUpdates();
} | @Test
void metadataChangeListenersAreNotifiedOfMetadataChanges() {
final JobRunrMetadata jobRunrMetadata = new JobRunrMetadata(SOME_METADATA_NAME, "some owner", "some value");
storageProvider.saveMetadata(jobRunrMetadata);
final MetadataChangeListenerForTest changeListener = new MetadataChan... |
@Override
public String getName() {
return getLogger().getName();
} | @Test
public void getName() throws Exception {
Logger loggerFromClass = new SLF4JLoggerImpl(SLF4JLoggerImplTest.class);
Logger logger = new SLF4JLoggerImpl(SLF4JLoggerImplTest.class.getCanonicalName());
Assert.assertEquals(loggerFromClass.getName(), logger.getName());
String appName ... |
@Override
public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) {
List<SmsReceiveStatus> statuses = JsonUtils.parseArray(text, SmsReceiveStatus.class);
return convertList(statuses, status -> new SmsReceiveRespDTO().setSuccess(status.getSuccess())
.setErrorCode(status.getE... | @Test
public void testParseSmsReceiveStatus() {
// 准备参数
String text = "[\n" +
" {\n" +
" \"phone_number\" : \"13900000001\",\n" +
" \"send_time\" : \"2017-01-01 11:12:13\",\n" +
" \"report_time\" : \"2017-02-02 22:23:24\",\n" ... |
public static CommandExecutor newInstance(final CommandPacketType commandPacketType, final PostgreSQLCommandPacket commandPacket,
final ConnectionSession connectionSession, final PortalContext portalContext) throws SQLException {
if (commandPacket instanceof SQLRece... | @Test
void assertNewPostgreSQLSimpleQueryExecutor() throws SQLException {
PostgreSQLComQueryPacket queryPacket = mock(PostgreSQLComQueryPacket.class);
when(queryPacket.getSQL()).thenReturn("");
CommandExecutor actual = OpenGaussCommandExecutorFactory.newInstance(PostgreSQLCommandPacketType.S... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Un... | @Test
public void shouldVisitBigInt() {
// Given:
final SqlPrimitiveType type = SqlTypes.BIGINT;
when(visitor.visitBigInt(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitBigInt(same(type));
assertThat(re... |
public List<S> loadInstanceListSorted() {
load();
return createInstanceList(sortedClassList);
} | @Test
public void testLoadInstanceListSorted() {
List<ProcessorSlot> sortedSlots = SpiLoader.of(ProcessorSlot.class).loadInstanceListSorted();
assertNotNull(sortedSlots);
// Total 8 default slot in sentinel-core
assertEquals(9, sortedSlots.size());
// Verify the order of sl... |
@Override
public byte[] randomKey(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<byte[]> f = executorService.readRandomAsync(entry, ByteArrayCodec.INSTANCE, RedisCommands.RANDOM_KEY);
return syncFuture(f);
} | @Test
public void testRandomKey() {
testInCluster(connection -> {
RedissonClient redisson = (RedissonClient) connection.getNativeConnection();
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(new RedissonConnectionFactory(r... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations")
public void testHandleTooManyParallelRequests(MultiplexerRunMode multiplexerRunMode) throws Exception
{
// MultiplexedRequestHandlerImpl is created with the request limit set to 2
MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(null, multiplexe... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void castToShort() {
final TypedExpression left = expr(THIS_PLACEHOLDER + ".getAgeAsShort()", java.lang.Short.class);
final TypedExpression right = expr("40", int.class);
final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, false).coerce();... |
protected List<ProviderInfo> resolveDomain(String directUrl) {
List<ProviderInfo> providerInfos = domainCache.get(directUrl);
if (providerInfos != null) {
return providerInfos;
}
ProviderInfo providerInfo = convertToProviderInfo(directUrl);
List<ProviderInfo> result =... | @Test
public void testResolveDomain() {
String mockKey = "mock";
List<ProviderInfo> value = new ArrayList<>();
domainRegistry.domainCache.put(mockKey, value);
assertSame(value, domainRegistry.resolveDomain(mockKey));
String local = "127.0.0.1";
List<ProviderInfo> act... |
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml4(input));
} | @Test
public void shouldSupportEmptyQuoteLineWithAndWithoutLeadingSpace() {
assertThat(Markdown.convertToHtml("""
>just some quotation without leading space
>
>
> continue quotation"""
)).isEqualTo("""
<blockquote>just some quotation without leading space<br/>
... |
public String getName() {
return name;
} | @Test
public void testGetName_ShouldReturnCorrectName() {
assertEquals("testAttribute", attribute.getName());
} |
@EventListener(ApplicationEvent.class)
void onApplicationEvent(ApplicationEvent event) {
if (AnnotationUtils.findAnnotation(event.getClass(), SharedEvent.class) == null) {
return;
}
// we should copy the plugins list to avoid ConcurrentModificationException
var startedPlu... | @Test
void shouldUnwrapPluginSharedEventAndRepublish() {
var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this));
dispatcher.onApplicationEvent(event);
verify(publisher).publishEvent(event.getDelegate());
} |
public void validate(CreateReviewAnswerRequest request) {
validateNotContainingText(request);
Question question = questionRepository.findById(request.questionId())
.orElseThrow(() -> new SubmittedQuestionNotFoundException(request.questionId()));
OptionGroup optionGroup = optionGr... | @Test
void 저장되지_않은_옵션그룹에_대해_응답하면_예외가_발생한다() {
// given
CreateReviewAnswerRequest request = new CreateReviewAnswerRequest(
savedQuestion.getId(), List.of(1L), null
);
// when, then
assertThatCode(() -> createCheckBoxAnswerRequestValidator.validate(request))
... |
@Override
public void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
NamingUtils.batchCheckInstanceIsLegal(instances);
batchCheckAndStripGroupNamePrefix(instances, groupName);
clientProxy.batchRegisterService(serviceN... | @Test
void testBatchRegisterInstance() throws NacosException {
Instance instance = new Instance();
String serviceName = "service1";
String ip = "1.1.1.1";
int port = 10000;
instance.setServiceName(serviceName);
instance.setEphemeral(true);
instance.setPort(por... |
public static void warn(final Logger logger, final String format, final Supplier<Object> supplier) {
if (logger.isWarnEnabled()) {
logger.warn(format, supplier.get());
}
} | @Test
public void testAtLeastOnceWarnWithFormat() {
when(logger.isWarnEnabled()).thenReturn(true);
LogUtils.warn(logger, "testWarn: {}", supplier);
verify(supplier, atLeastOnce()).get();
} |
@Override
public String toSpec() {
return String.format("plain:%s:%s", algorithm.toString().toLowerCase(), Base64.getEncoder().encodeToString(plainKey));
} | @Test
public void testToSpec() {
String base64Key = Base64.getEncoder().encodeToString(normalKey.getPlainKey());
String expectedSpec = "plain:aes_128:" + base64Key;
assertEquals(expectedSpec, normalKey.toSpec());
} |
public static String getSonarqubeVersion() {
if (sonarqubeVersion == null) {
loadVersion();
}
return sonarqubeVersion;
} | @Test
public void getSonarQubeVersion_must_always_return_same_value() {
String sonarqubeVersion = SonarQubeVersionHelper.getSonarqubeVersion();
for (int i = 0; i < 3; i++) {
assertThat(SonarQubeVersionHelper.getSonarqubeVersion()).isEqualTo(sonarqubeVersion);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.