focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static CronPattern of(String pattern) {
return new CronPattern(pattern);
} | @Test
public void patternTest() {
CronPattern pattern = CronPattern.of("* 0 4 * * ?");
assertMatch(pattern, "2017-02-09 04:00:00");
assertMatch(pattern, "2017-02-19 04:00:33");
// 6位Quartz风格表达式
pattern = CronPattern.of("* 0 4 * * ?");
assertMatch(pattern, "2017-02-09 04:00:00");
assertMatch(pattern, "20... |
@Override
public void run() {
if (!redoService.isConnected()) {
LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task");
return;
}
try {
redoForInstances();
redoForSubscribes();
} catch (Exception e) {
... | @Test
void testRunRedoRegisterSubscriber() throws NacosException {
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false, true);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy).doSubscribe(SERVICE, GROUP, CLUST... |
public static String encodeBase64ZippedString( String in ) throws IOException {
Charset charset = Charset.forName( Const.XML_ENCODING );
ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 );
try ( Base64OutputStream base64OutputStream = new Base64OutputStream( baos );
GZIPOutputStream gz... | @Test
public void testEncodeBase64ZippedString() throws IOException {
String enc64 = HttpUtil.encodeBase64ZippedString( STANDART );
String decoded = HttpUtil.decodeBase64ZippedString( enc64 );
Assert.assertEquals( "Strings are the same after transformation", STANDART, decoded );
} |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final CopyFileRequest copy = new CopyFileRequest()
.name(target.getName())
... | @Test
public void testCopyWithRenameToExistingFile() throws Exception {
final StoregateIdProvider fileid = new StoregateIdProvider(session);
final Path top = new StoregateDirectoryFeature(session, fileid).mkdir(new Path(
String.format("/My files/%s", new AlphanumericRandomStringService()... |
public void init() throws GeneralSecurityException, IOException {
createCACertAndKeyPair();
initInternal();
} | @Test
void testInit() throws Exception {
ProxyCA proxyCA = new ProxyCA();
assertNull(proxyCA.getCaCert());
assertNull(proxyCA.getCaKeyPair());
assertNull(proxyCA.getX509KeyManager());
assertNull(proxyCA.getHostnameVerifier());
proxyCA.init();
assertNotNull(proxyCA.getCaCert());
assert... |
static @Nullable String resolveConsumerArn(Read spec, PipelineOptions options) {
String streamName = Preconditions.checkArgumentNotNull(spec.getStreamName());
KinesisIOOptions sourceOptions = options.as(KinesisIOOptions.class);
Map<String, String> streamToArnMapping = sourceOptions.getKinesisIOConsumerArns(... | @Test
public void testConsumerArnInPipelineOptionsOverwritesIOSetting() {
KinesisIO.Read readSpec =
KinesisIO.read().withStreamName("stream-xxx").withConsumerArn("arn-ignored");
KinesisIOOptions options =
createIOOptions("--kinesisIOConsumerArns={\"stream-xxx\": \"arn-01\"}");
assertThat(... |
@Override
public boolean canManageResource(EfestoResource toProcess) {
return toProcess instanceof EfestoInputStreamResource && ((EfestoInputStreamResource) toProcess).getModelType().equalsIgnoreCase(PMML_STRING);
} | @Test
void canManageResource() throws IOException {
String fileName = "LinearRegressionSample.pmml";
File pmmlFile = getFileFromFileName(fileName).orElseThrow(() -> new RuntimeException("Failed to get pmmlFIle"));
EfestoInputStreamResource toProcess = new EfestoInputStreamResource(Files.newI... |
@Override
public Message receive() {
MessageExt rmqMsg = localMessageCache.poll();
return rmqMsg == null ? null : OMSUtil.msgConvert(rmqMsg);
} | @Test
public void testPoll_WithTimeout() {
//There is a default timeout value, @see ClientConfig#omsOperationTimeout.
Message message = consumer.receive();
assertThat(message).isNull();
message = consumer.receive(OMS.newKeyValue().put(Message.BuiltinKeys.TIMEOUT, 100));
asse... |
public String decompress(String compressorName, String compressedString) throws IOException {
Checks.notNull(compressedString, "compressedString cannot be null");
Compressor compressor = getCompressor(compressorName);
return new String(compressor.decompress(base64Decode(compressedString)), DEFAULT_ENCODING)... | @Test
public void decompressShouldThrowExceptionIfCompressorNotFound() {
AssertHelper.assertThrows(
"decompress should throw exception if compressor not found",
NullPointerException.class,
"unknown compressorName: abcd",
() -> stringCodec.decompress("abcd", "H4sIAAAAAAAA/0tMBAMAdCC... |
public static String prettyPrint(String taskId) {
return taskWatchMap.get(taskId).prettyPrint();
} | @Test
void testPrettyPrint() {
TaskTimeCaculateUtil.startTask("Task 1", "taskId1");
// Perform some task-related operations
// ...
TaskTimeCaculateUtil.stop("taskId1");
String output = TaskTimeCaculateUtil.prettyPrint("taskId1");
Assertions.assertNotNull(output);
... |
public static Serializable decode(final ByteBuf byteBuf) {
int valueType = byteBuf.readUnsignedByte() & 0xff;
StringBuilder result = new StringBuilder();
decodeValue(valueType, 1, byteBuf, result);
return result.toString();
} | @Test
void assertDecodeLargeJsonObjectWithInt16() {
List<JsonEntry> jsonEntries = new LinkedList<>();
jsonEntries.add(new JsonEntry(JsonValueTypes.INT16, "key1", 0x00007fff));
jsonEntries.add(new JsonEntry(JsonValueTypes.INT16, "key2", 0x00008000));
ByteBuf payload = mockJsonObjectBy... |
@UdafFactory(description = "Compute sample standard deviation of column with type Double.",
aggregateSchema = "STRUCT<SUM double, COUNT bigint, M2 double>")
public static TableUdaf<Double, Struct, Double> stdDevDouble() {
return getStdDevImplementation(
0.0,
STRUCT_DOUBLE,
(agg, newV... | @Test
public void shouldMergeDoubles() {
final TableUdaf<Double, Struct, Double> udaf = stdDevDouble();
Struct left = udaf.initialize();
final Double[] leftValues = new Double[] {5.5, 8.4, 10.9};
for (final Double thisValue : leftValues) {
left = udaf.aggregate(thisValue, left);
}
Stru... |
@Override
public boolean canManageInput(EfestoInput toEvaluate, EfestoRuntimeContext context) {
return canManageEfestoInput(toEvaluate, context);
} | @Test
void canManageManageableInput() {
modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME);
Map<String, Object> inputData = new HashMap<>();
inputPMML = new BaseEfestoInput<>(modelLocalUriId, inputData);
assertThat(kieRuntimeServicePMMLMapInput.canManageInpu... |
public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
checkArgument(b.signum() >= 0, () -> "b must be positive or zero: " + b);
checkArgument(numBytes > 0, () -> "numBytes must be positive: " + numBytes);
byte[] src = b.toByteArray();
byte[] dest = new byte[numBytes];
... | @Test
public void bigIntegerToBytes_singleByteSignFit() {
BigInteger b = BigInteger.valueOf(0b0000_1111);
byte[] expected = new byte[]{0b0000_1111};
byte[] actual = ByteUtils.bigIntegerToBytes(b, 1);
assertArrayEquals(expected, actual);
} |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test
public void testContainsIpAddressIPv4() {
Ip4Prefix ipPrefix;
ipPrefix = Ip4Prefix.valueOf("1.2.0.0/24");
assertTrue(ipPrefix.contains(Ip4Address.valueOf("1.2.0.0")));
assertTrue(ipPrefix.contains(Ip4Address.valueOf("1.2.0.4")));
assertFalse(ipPrefix.contains(Ip4Addres... |
@Override
public KStream<K, V> filter(final Predicate<? super K, ? super V> predicate) {
return filter(predicate, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullNamedOnFilter() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.filter((k, v) -> true, null));
assertThat(exception.getMessage(), equalTo("named can't be null"));
} |
@Override
public Set<Path> getPaths(ElementId src, ElementId dst) {
checkPermission(TOPOLOGY_READ);
return getPaths(src, dst, (LinkWeigher) null);
} | @Test
public void edgeToInfra() {
HostId src = hid("12:34:56:78:90:ab/1");
DeviceId dst = did("dst");
fakeTopoMgr.paths.add(createPath("edge", "middle", "dst"));
fakeHostMgr.hosts.put(src, host("12:34:56:78:90:ab/1", "edge"));
Set<Path> paths = service.getPaths(src, dst);
... |
@Override
public SCMPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
SCMPropertyConfiguration scmConfiguration = extension.getSCMConfiguration(descriptor.id());
SCMView scmView = extension.getSCMView(descriptor.id());
PluggableInstanceSettings pluginSettingsAndView = getPluginSettin... | @Test
public void shouldBuildPluginInfo() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
SCMPluginInfo pluginInfo = new SCMPluginInfoBuilder(extension).pluginInfoFor(descriptor);
List<PluginConfiguration> scmConfigurations = List.of(
... |
public String roleName()
{
return ctx.agentRoleName();
} | @Test
void shouldUseAssignedRoleName()
{
final String expectedRoleName = "test-role-name";
final TestClusterClock clock = new TestClusterClock(TimeUnit.MILLISECONDS);
ctx.agentRoleName(expectedRoleName)
.epochClock(clock)
.clusterClock(clock);
final Conse... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP);
if (args.isEmpty()) {
terminal.println(restClient.getServerAddress());
return;
} else {
final String serverAddress = args.get(0);
restClient.setS... | @Test
public void shouldIdentifyNonCCloudServer() {
// When:
command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal);
// Then:
verify(restClient).setIsCCloudServer(false);
} |
public String getVersionsNodePath() {
return String.join("/", key, VERSIONS, currentActiveVersion);
} | @Test
void assertGetVersionsNodePath() {
assertThat(new MetaDataVersion("foo", "0", "1").getVersionsNodePath(), is("foo/versions/0"));
} |
@Override
public SecretsPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
String pluginId = descriptor.id();
return new SecretsPluginInfo(descriptor, securityConfigSettings(pluginId), image(pluginId));
} | @Test
public void shouldBuildPluginInfoWithSecuritySettings() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
List<PluginConfiguration> pluginConfigurations = List.of(
new PluginConfiguration("username", new Metadata(true, false)),
... |
public static String getLocalHostName() {
if (StrUtil.isNotBlank(localhostName)) {
return localhostName;
}
final InetAddress localhost = getLocalhost();
if (null != localhost) {
String name = localhost.getHostName();
if (StrUtil.isEmpty(name)) {
name = localhost.getHostAddress();
}
localhos... | @Test
@Disabled
public void getLocalHostNameTest() {
// 注意此方法会触发反向DNS解析,导致阻塞,阻塞时间取决于网络!
assertNotNull(NetUtil.getLocalHostName());
} |
@Override
public MapperResult findAllConfigInfoBetaForDumpAllFetchRows(MapperContext context) {
int startRow = context.getStartRow();
int pageSize = context.getPageSize();
String sql = " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key "
... | @Test
void testFindAllConfigInfoBetaForDumpAllFetchRows() {
MapperResult result = configInfoBetaMapperByMySql.findAllConfigInfoBetaForDumpAllFetchRows(context);
String sql = result.getSql();
List<Object> paramList = result.getParamList();
assertEquals(sql, " SELECT t.id,data_id,group... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleAliasedJoinDataSources() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1 t1 JOIN TEST2 t2"
+ " ON test1.col1 = test2.col1;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.g... |
public static void tryShutdown(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
closeSockets(factory);
try {
factory.node.shutdown(true);
} ... | @Test
public void testTryShutdown_shouldDoNothingWhenThrowableIsThrown() {
tryShutdown(hazelcastInstanceThrowsException);
} |
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
while (it.hasNext()) ... | @Test
public void lines() {
assertThat(
CommandLineOptionsParser.parse(
Arrays.asList("--lines", "1:2", "-lines=4:5", "--line", "7:8", "-line=10:11"))
.lines()
.asRanges())
.containsExactly(
Range.closedOpen(0, 2),
Ran... |
@Field
public void setExtractBookmarksText(boolean extractBookmarksText) {
defaultConfig.setExtractBookmarksText(extractBookmarksText);
} | @Test
public void testTurningOffBookmarks() throws Exception {
PDFParserConfig config = new PDFParserConfig();
config.setExtractBookmarksText(false);
ParseContext parseContext = new ParseContext();
parseContext.set(PDFParserConfig.class, config);
String xml = getXML("testPDF_... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(2.0), numOf(1.5)));
assertFalse(criterion.betterThan(numOf(1.5), numOf(2.0)));
} |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(ap... | @Test
public void status_YELLOW_when_one_RED_node_and_one_YELLOW_application_node() {
Set<NodeHealth> nodeHealths = nodeHealths(RED, YELLOW).collect(toSet());
Health check = underTest.check(nodeHealths);
assertThat(check)
.forInput(nodeHealths)
.hasStatus(Health.Status.YELLOW)
.andCaus... |
@Override
public Long del(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key: keys) {
write(key, LongCodec.INSTANCE, RedisCommands.DEL, key);
}
return null;
}
CommandBatchService es = new CommandBatchService(executorSe... | @Test
public void testDelPipeline() {
byte[] k = "key".getBytes();
byte[] v = "val".getBytes();
connection.set(k, v);
connection.openPipeline();
connection.get(k);
connection.del(k);
List<Object> results = connection.closePipeline();
byte[] val = (byt... |
@Unstable
public static Text getRMDelegationTokenService(Configuration conf) {
return getTokenService(conf, YarnConfiguration.RM_ADDRESS,
YarnConfiguration.DEFAULT_RM_ADDRESS,
YarnConfiguration.DEFAULT_RM_PORT);
} | @Test
void testGetRMDelegationTokenService() {
String defaultRMAddress = YarnConfiguration.DEFAULT_RM_ADDRESS;
YarnConfiguration conf = new YarnConfiguration();
// HA is not enabled
Text tokenService = ClientRMProxy.getRMDelegationTokenService(conf);
String[] services = tokenService.toString().sp... |
@Override
public Optional<Page> commit()
{
try {
orcWriter.close();
}
catch (IOException | UncheckedIOException | PrestoException e) {
try {
rollbackAction.call();
}
catch (Exception ignored) {
// ignore
... | @Test
public void testIOExceptionPropagation()
{
// This test is to verify that a IOException thrown by the underlying data sink implementation is wrapped into a PrestoException.
OrcFileWriter orcFileWriter = createOrcFileWriter(false);
try {
// Throws PrestoException with H... |
@Override
public void validate(String value, @Nullable List<String> options) {
// Nothing to do
} | @Test
public void not_fail_on_valid_text() {
validation.validate("10", null);
validation.validate("abc", null);
} |
@Override
@Transactional
public boolean checkForPreApproval(Long userId, Integer userType, String clientId, Collection<String> requestedScopes) {
// 第一步,基于 Client 的自动授权计算,如果 scopes 都在自动授权中,则返回 true 通过
OAuth2ClientDO clientDO = oauth2ClientService.validOAuthClientFromCache(clientId);
Asse... | @Test
public void checkForPreApproval_reject() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
List<String> requestedScopes = Lists.newArrayList("read");
// mock 方法
when(... |
@Override
public List<PrivilegedOperation> bootstrap(Configuration configuration)
throws ResourceHandlerException {
// if bootstrap is called on this class, disk is already enabled
// so no need to check again
this.cGroupsHandler
.initializeCGroupController(CGroupsHandler.CGroupController.BLKI... | @Test
public void testBootstrap() throws Exception {
Configuration conf = new YarnConfiguration();
List<PrivilegedOperation> ret =
cGroupsBlkioResourceHandlerImpl.bootstrap(conf);
verify(mockCGroupsHandler, times(1)).initializeCGroupController(
CGroupsHandler.CGroupController.BLKIO);
A... |
public CoordinatorResult<Void, CoordinatorRecord> onPartitionsDeleted(
List<TopicPartition> topicPartitions
) {
final long startTimeMs = time.milliseconds();
final List<CoordinatorRecord> records = offsetMetadataManager.onPartitionsDeleted(topicPartitions);
log.info("Generated {} to... | @Test
public void testOnPartitionsDeleted() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
Coordin... |
public static LogCollector<ShenyuRequestLog> getInstance() {
return INSTANCE;
} | @Test
public void testAbstractLogCollector() throws Exception {
HuaweiLtsLogCollector.getInstance().start();
Field field1 = AbstractLogCollector.class.getDeclaredField("started");
field1.setAccessible(true);
Assertions.assertEquals(field1.get(HuaweiLtsLogCollector.getInstance()).toSt... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
callback.delete(file);
try {
if(file.attributes().isDuplicate()) {
... | @Test
public void testDeleteFile() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.... |
@Override
public String exportResources( VariableSpace space, Map<String, ResourceDefinition> definitions,
ResourceNamingInterface namingInterface, Repository repository, IMetaStore metaStore ) throws KettleException {
// Try to load the transformation from repository or file.
// Modify this recursively t... | @Test
public void testExportResources() throws Exception {
try ( MockedConstruction<JobMeta> jobMetaMockedConstruction = mockConstruction( JobMeta.class );
MockedConstruction<CurrentDirectoryResolver> currentDirectoryResolverMockedConstruction = mockConstruction(
CurrentDirectoryResolver.cla... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void timeWindowNamedMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.windowedBy(TimeWindows.of(ofMillis(1)))
.count(Materialized.<Object, Long, Windo... |
@Override
public void setConfig(RedisClusterNode node, String param, String value) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value);
syncFuture(f);
} | @Test
public void testSetConfig() {
RedisClusterNode master = getFirstMaster();
connection.setConfig(master, "timeout", "10");
} |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String,... | @Test
public void reportsShortGaugeValues() throws Exception {
reporter.report(map("gauge", gauge((short) 1)),
map(),
map(),
map(),
map());
final InOrder inOrder = inOrder(graphite);
inOrder.verify(graphite).connect();
inOrder.verify(g... |
public TriRpcStatus withDescription(String description) {
return new TriRpcStatus(code, cause, description);
} | @Test
void withDescription() {
TriRpcStatus origin = TriRpcStatus.NOT_FOUND;
TriRpcStatus withDesc = origin.withDescription("desc");
Assertions.assertNull(origin.description);
Assertions.assertTrue(withDesc.description.contains("desc"));
} |
@Override
public List<Port> getPorts(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_NULL);
return manager.getVirtualPorts(this.networkId, deviceId)
.stream()
.collect(Collectors.toList());
} | @Test(expected = NullPointerException.class)
public void testGetPortsByNullId() {
manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
DeviceService deviceService = manager.get(virtualNet... |
static void handleDowngrade(Namespace namespace, Admin adminClient) throws TerseException {
handleUpgradeOrDowngrade("downgrade", namespace, adminClient, downgradeType(namespace));
} | @Test
public void testHandleDowngrade() {
Map<String, Object> namespace = new HashMap<>();
namespace.put("metadata", "3.3-IV3");
namespace.put("feature", Collections.singletonList("foo.bar=1"));
namespace.put("dry_run", false);
String downgradeOutput = ToolsTestUtils.captureS... |
public static String configMapToRedactedString(Map<String, Object> map, ConfigDef configDef) {
StringBuilder bld = new StringBuilder("{");
List<String> keys = new ArrayList<>(map.keySet());
Collections.sort(keys);
String prefix = "";
for (String key : keys) {
bld.appe... | @Test
public void testConfigMapToRedactedStringWithSecrets() {
Map<String, Object> testMap1 = new HashMap<>();
testMap1.put("myString", "whatever");
testMap1.put("myInt", 123);
testMap1.put("myPassword", "foosecret");
testMap1.put("myString2", null);
testMap1.put("myU... |
Map<String, File> scanExistingUsers() throws IOException {
Map<String, File> users = new HashMap<>();
File[] userDirectories = listUserDirectories();
if (userDirectories != null) {
for (File directory : userDirectories) {
String userId = idStrategy.idFromFilename(dire... | @Test
public void scanExistingUsersOldLegacy() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), hasSize(4));
assertThat(userMappings.keySet(), hasItems("make\u100000... |
public static String getSLcDtTm() {
//
return getSLcDtTm( "mm:ss.SSS" );
} | @Test
public void testgetSLcDtTm() throws Exception {
//
assertEquals( 15, BTools.getSLcDtTm().length() );
assertEquals( "LDTm: ", BTools.getSLcDtTm().substring( 0, 6 ) );
//
} |
@Nonnull
public static <T extends Throwable> T cloneExceptionWithFixedAsyncStackTrace(@Nonnull T original) {
StackTraceElement[] fixedStackTrace = getFixedStackTrace(original, Thread.currentThread().getStackTrace());
Class<? extends Throwable> exceptionClass = original.getClass();
Throwabl... | @Test
public void testCloneExceptionWithFixedAsyncStackTrace_whenNonStandardConstructor_then_cloneReflectively() {
IOException expectedException = new IOException();
Throwable result = ExceptionUtil.cloneExceptionWithFixedAsyncStackTrace(
new NonStandardException(1337, expectedExcept... |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldEvaluateLambdaInUDFWithMap() {
// Given:
givenUdfWithNameAndReturnType("TRANSFORM", SqlTypes.DOUBLE);
when(function.parameters()).thenReturn(
ImmutableList.of(
MapType.of(DoubleType.INSTANCE, DoubleType.INSTANCE),
LambdaType.of(ImmutableList.of(LongT... |
@Nullable
@Override
public String getMainClassFromJarPlugin() {
Jar jarTask = (Jar) project.getTasks().findByName("jar");
if (jarTask == null) {
return null;
}
Object value = jarTask.getManifest().getAttributes().get("Main-Class");
if (value instanceof Provider) {
value = ((Provide... | @Test
public void testGetMainClassFromJarAsPropertyWithValueNull_missing() {
Property<String> mainClass = project.getObjects().property(String.class).value((String) null);
Jar jar = project.getTasks().withType(Jar.class).getByName("jar");
jar.setManifest(new DefaultManifest(null).attributes(ImmutableMap.... |
public X509Certificate sign(PrivateKey caPrivateKey, X509Certificate caCertificate, PKCS10CertificationRequest csr, RenewalPolicy renewalPolicy) throws Exception {
Instant validFrom = Instant.now(clock);
var validUntil = validFrom.plus(renewalPolicy.parsedCertificateLifetime());
return sign(caP... | @Test
void testSigningCertWithSixMonthsLifetime() throws Exception {
var result = sign("P6M");
assertThat(result).isNotNull();
assertThat(result.getNotAfter()).isEqualTo(fixedInstant.plus(180, ChronoUnit.DAYS));
} |
public CSVSchemaCommand(Logger console) {
super(console);
} | @Test
public void testCSVSchemaCommand() throws IOException {
File file = csvFile();
CSVSchemaCommand command = new CSVSchemaCommand(createLogger());
command.samplePaths = Arrays.asList(file.getAbsolutePath());
command.recordName = "Test";
command.setConf(new Configuration());
Assert.assertEqu... |
public static <T> CompletionStage<T> recover(CompletionStage<T> completionStage, Function<Throwable, T> exceptionHandler){
return completionStage.exceptionally(exceptionHandler);
} | @Test
public void shouldRecoverFromSpecificExceptions()
throws InterruptedException, ExecutionException, TimeoutException {
CompletableFuture<String> future = new CompletableFuture<>();
future.completeExceptionally(new TimeoutException());
String result = recover(future, asList(Time... |
@SuppressWarnings("unchecked")
public static <T> NFAFactory<T> compileFactory(
final Pattern<T, ?> pattern, boolean timeoutHandling) {
if (pattern == null) {
// return a factory for empty NFAs
return new NFAFactoryImpl<>(
0,
Collect... | @Test
public void testWindowTimeCorrectlySet() {
Pattern<Event, ?> pattern =
Pattern.<Event>begin("start")
.followedBy("middle")
.within(Time.seconds(10))
.followedBy("then")
.within(Time.seconds(... |
public static Map<String, String> buildDirectoryContextProperties(ConnectorSession session)
{
ImmutableMap.Builder<String, String> directoryContextProperties = ImmutableMap.builder();
directoryContextProperties.put(PRESTO_QUERY_ID, session.getQueryId());
session.getSource().ifPresent(source ... | @Test
public void testBuildDirectoryContextProperties()
{
Map<String, String> additionalProperties = buildDirectoryContextProperties(SESSION);
assertEquals(additionalProperties.get(PRESTO_QUERY_ID), SESSION.getQueryId());
assertEquals(Optional.ofNullable(additionalProperties.get(PRESTO_Q... |
Mono<ResponseEntity<Void>> save(Post post) {
return client.post()
.uri("/posts")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(post)
.exchangeToMono(response -> {
if (response.statusCode().equals(HttpStatus.CREATED)) {
... | @SneakyThrows
@Test
public void testCreatePost() {
var id = UUID.randomUUID();
var data = new Post(null, "title1", "content1", Status.DRAFT, null);
stubFor(post("/posts")
.willReturn(
aResponse()
.withHeader("Locati... |
protected static String getTrimmedUrl(String rawUrl) {
if (isBlank(rawUrl)) {
return rawUrl;
}
if (rawUrl.endsWith("/")) {
return substringBeforeLast(rawUrl, "/");
}
return rawUrl;
} | @Test
public void trim_null_url() {
assertThat(AzureDevOpsHttpClient.getTrimmedUrl(null))
.isNull();
} |
@Override
public List<String> tokenise(String text) {
if (Objects.isNull(text) || text.isEmpty()) {
return new ArrayList<>();
}
List<String> tokens = new ArrayList<>();
text = text.replaceAll("[^\\p{L}\\p{N}\\s\\-'.]", " ").trim();
String[] parts = text.split("\\s+");
for (int i = 0;... | @Description("Tokenise, when text only has one word but lots of commas, then return one word")
@Test
void tokenise_WhenTextOnlyHasOneWordButLotsOfCommas_ThenReturnOneToken() {
// When
var result = textTokeniser.tokenise(",Aberdeen,,,,");
// Then
assertThat(result).isNotEmpty().hasSize(1).contains(... |
public synchronized ObjectId insertTransformationCluster( ObjectId id_transformation, ObjectId id_cluster ) throws KettleException {
ObjectId id = connectionDelegate.getNextTransformationClusterID();
RowMetaAndData table = new RowMetaAndData();
table.addValue( new ValueMetaInteger(
KettleDatabaseRep... | @Test
public void testInsertTransformationCluster() throws KettleException {
ArgumentCaptor<String> argumentTableName = ArgumentCaptor.forClass( String.class );
ArgumentCaptor<RowMetaAndData> argumentTableData = ArgumentCaptor.forClass( RowMetaAndData.class );
doNothing().when( repo.connectionDelegate ).i... |
public Account changeNumber(final Account account, final String number,
@Nullable final IdentityKey pniIdentityKey,
@Nullable final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
@Nullable final List<IncomingMessage> deviceMes... | @Test
void changeNumberSetPrimaryDevicePrekeyPqAndSendMessages() throws Exception {
final String originalE164 = "+18005551234";
final String changedE164 = "+18025551234";
final UUID aci = UUID.randomUUID();
final UUID pni = UUID.randomUUID();
final Account account = mock(Account.class);
when(... |
@Override
public String getTargetName(final String groupName, final List<String> availableTargetNames) {
double[] weight = weightMap.containsKey(groupName) && weightMap.get(groupName).length == availableTargetNames.size() ? weightMap.get(groupName) : initWeight(availableTargetNames);
weightMap.put(g... | @Test
void assertGetSingleAvailableTarget() {
LoadBalanceAlgorithm loadBalanceAlgorithm = TypedSPILoader.getService(LoadBalanceAlgorithm.class, "WEIGHT", PropertiesBuilder.build(new Property("test_read_ds_1", "5")));
assertThat(loadBalanceAlgorithm.getTargetName("ds", Collections.singletonList("test... |
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sor... | @Test
void sort_by_numerical_metric_period_1_key_ascending() {
components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure"));
ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_PERIOD_SORT), true, NEW_METRIC_KEY).setMetricPeriodSort(1)... |
@Override
public SchemaPath getSchemaPath(TopicPath topicPath) throws IOException {
GetTopicRequest request = GetTopicRequest.newBuilder().setTopic(topicPath.getPath()).build();
Topic topic = publisherStub().getTopic(request);
SchemaSettings schemaSettings = topic.getSchemaSettings();
if (schemaSettin... | @Test
public void getSchemaPath() throws IOException {
initializeClient(null, null);
TopicPath topicDoesNotExist =
PubsubClient.topicPathFromPath("projects/testProject/topics/idontexist");
TopicPath topicExistsDeletedSchema =
PubsubClient.topicPathFromPath("projects/testProject/topics/dele... |
@Override
public void cancel(InterpreterContext context) throws InterpreterException {
String shinyApp = context.getStringLocalProperty("app", DEFAULT_APP_NAME);
IRInterpreter irInterpreter = getIRInterpreter(shinyApp);
irInterpreter.cancel(context);
} | @Test
void testShinyApp() throws
IOException, InterpreterException, InterruptedException, UnirestException {
/****************** Launch Shiny app with default app name *****************************/
InterpreterContext context = getInterpreterContext();
context.getLocalProperties().put("type", "u... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatCreateStreamStatementWithExplicitKey() {
// Given:
final CreateStream createStream = new CreateStream(
TEST,
ELEMENTS_WITH_KEY,
false,
false,
SOME_WITH_PROPS,
false);
// When:
final String sql = SqlFormatter.formatSql(creat... |
public CharSequence format(Monetary monetary) {
// determine maximum number of decimals that can be visible in the formatted string
// (if all decimal groups were to be used)
int max = minDecimals;
if (decimalGroups != null)
for (int group : decimalGroups)
max... | @Test
public void btcRounding() {
assertEquals("0", format(ZERO, 0, 0));
assertEquals("0.00", format(ZERO, 0, 2));
assertEquals("1", format(COIN, 0, 0));
assertEquals("1.0", format(COIN, 0, 1));
assertEquals("1.00", format(COIN, 0, 2, 2));
assertEquals("1.00", format... |
public String toBaseMessageIdString(Object messageId) {
if (messageId == null) {
return null;
} else if (messageId instanceof String) {
String stringId = (String) messageId;
// If the given string has a type encoding prefix,
// we need to escape it as an ... | @Test
public void testToBaseMessageIdStringWithNull() {
String nullString = null;
assertNull("null string should have been returned", messageIdHelper.toBaseMessageIdString(nullString));
} |
public InetSocketAddress getBoundIpcAddress() {
return rpcServer.getAddress();
} | @Test(timeout=100000)
public void testJournal() throws Exception {
MetricsRecordBuilder metrics = MetricsAsserts.getMetrics(
journal.getMetrics().getName());
MetricsAsserts.assertCounter("BatchesWritten", 0L, metrics);
MetricsAsserts.assertCounter("BatchesWrittenWhileLagging", 0L, metrics);
Me... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
final Stacker contextStacker = buildContext.buildNodeContext(getId().toString());
return schemaKStreamFactory.create(
buildContext,
dataSource,
contextStacker.push(SOURCE_OP_NAME)
);
} | @Test
public void shouldBuildSourceStreamWithCorrectTimestampIndexForQualifiedFieldName() {
// Given:
givenNodeWithMockSource();
// When:
node.buildStream(buildContext);
// Then:
verify(schemaKStreamFactory).create(any(), any(), any());
} |
@Override
public ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) {
ExecutorService executorService = threadPoolFactory.newThreadPool(profile, threadFactory);
return ExecutorServiceMetrics.monitor(meterRegistry, executorService, name(profile.getId()));
} | @Test
public void testNewThreadPool() {
final ExecutorService executorService = instrumentedThreadPoolFactory.newThreadPool(profile, threadFactory);
assertThat(executorService, is(notNullValue()));
assertThat(executorService, is(instanceOf(TimedExecutorService.class)));
Tags tags = T... |
@Override
protected Optional<Change> fix(ExpressionTree tree, VisitorState state, NameSuggester suggester) {
return Change.of(definiteFix(tree, state));
} | @Test
public void fix() {
BugCheckerRefactoringTestHelper.newInstance(StreamResourceLeak.class, getClass())
.addInputLines(
"in/Test.java",
"import java.io.IOException;",
"import java.nio.file.Files;",
"import java.nio.file.Path;",
"import java.u... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeCreateStreamAsQueryCorrectly() {
final String output = anon.anonymize(
"CREATE STREAM my_stream AS SELECT user_id, browser_cookie, ip_address\n"
+ "FROM another_stream\n"
+ "WHERE user_id = 4214\n"
+ "AND browser_cookie = 'aefde34ec'\n"
... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldFindOneArg() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING)));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
} |
@Override
public void openWorkspace(Workspace workspace) {
synchronized (this) {
closeCurrentWorkspace();
getCurrentProject().setCurrentWorkspace(workspace);
//Event
fireWorkspaceEvent(EventType.SELECT, workspace);
}
} | @Test
public void testOpenWorkspace() {
ProjectControllerImpl pc = new ProjectControllerImpl();
pc.addWorkspaceListener(workspaceListener);
Project project = pc.newProject();
Workspace originalWorkspace = pc.getCurrentWorkspace();
Workspace workspace = pc.newWorkspace(project... |
public String getXML() {
try {
StringBuilder xml = new StringBuilder( 100 );
xml.append( XMLHandler.getXMLHeader() ); // UFT-8 XML header
xml.append( XMLHandler.openTag( XML_TAG ) ).append( Const.CR );
if ( id != null ) {
xml.append( " " ).append( XMLHandler.addTagValue( "ID", id ... | @Test
public void getXMLWithId() {
DragAndDropContainer dnd = new DragAndDropContainer( DragAndDropContainer.TYPE_BASE_STEP_TYPE, "Step Name", "StepID" );
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Const.CR
+ "<DragAndDrop>" + Const.CR
+ " <ID>StepID</ID>"... |
public static URI getCanonicalUri(URI uri, int defaultPort) {
// skip if there is no authority, ie. "file" scheme or relative uri
String host = uri.getHost();
if (host == null) {
return uri;
}
String fqHost = canonicalizeHost(host);
int port = uri.getPort();
// short out if already can... | @Test
public void testCanonicalUriWithNoPortNoDefaultPort() {
URI uri = NetUtils.getCanonicalUri(URI.create("scheme://host/path"), -1);
assertEquals("scheme://host.a.b/path", uri.toString());
} |
public Optional<Map<String, EncryptionInformation>> getReadEncryptionInformation(
ConnectorSession session,
Table table,
Optional<Set<HiveColumnHandle>> requestedColumns,
Map<String, Partition> partitions)
{
for (EncryptionInformationSource source : sources) {... | @Test
public void testReturnsFirstNonEmptyObject()
{
EncryptionInformation encryptionInformation1 = TestEncryptionInformationSource.createEncryptionInformation("test1");
EncryptionInformation encryptionInformation2 = TestEncryptionInformationSource.createEncryptionInformation("test2");
... |
@PublicAPI(usage = ACCESS)
public Optional<Result> match(String aPackage) {
Matcher matcher = packagePattern.matcher(aPackage);
return matcher.matches() ? Optional.of(new Result(matcher)) : Optional.empty();
} | @Test
@DataProvider(value = {
"some.arbitrary.pkg , some.arbitrary.pkg , true",
"some.arbitrary.pkg , some.thing.different , false",
"some..pkg , some.arbitrary.pkg , true",
"some..middle..pkg , some.arbitrary.middle.more.pk... |
@Transactional
public void create(String uuid, long attendeeId, ScheduleCreateRequest request) {
Meeting meeting = meetingRepository.findByUuid(uuid)
.orElseThrow(() -> new MomoException(MeetingErrorCode.INVALID_UUID));
validateMeetingUnLocked(meeting);
Attendee attendee = a... | @DisplayName("스케줄 생성 요청의 UUID가 존재하지 않으면 예외를 발생시킨다.")
@Test
void throwsExceptionWhenInvalidUUID() {
Meeting other = MeetingFixture.DINNER.create();
String invalidUUID = other.getUuid();
long attendeeId = attendee.getId();
ScheduleCreateRequest request = new ScheduleCreateRequest(d... |
PartitionReplica checkAndGetPrimaryReplicaOwner(int partitionId, int replicaIndex) {
InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(partitionId);
PartitionReplica owner = partition.getOwnerReplicaOrNull();
if (owner == null) {
logger.info("Sync replica targe... | @Test
public void testCheckSyncPartitionTarget_whenPartitionOwnerIsNull_thenReturnFalse() {
assertNull(manager.checkAndGetPrimaryReplicaOwner(PARTITION_ID, 0));
} |
public InetAddress resolve(final String name, final String uriParamName, final boolean isReResolution)
{
final long beginNs = clock.nanoTime();
maxTimeTracker.update(beginNs);
InetAddress address = null;
try
{
address = delegateResolver.resolve(name, uriParamName,... | @Test
void resolveShouldMeasureExecutionTimeEvenWhenExceptionIsThrown()
{
final NameResolver delegateResolver = mock(NameResolver.class);
final IllegalStateException exception = new IllegalStateException("error");
when(delegateResolver.resolve(anyString(), anyString(), anyBoolean()))
... |
public void setBatchSize(int batchSize) {
this.batchSize = checkPositive(batchSize, "batchSize");
} | @Test
public void test_setBatchSize_whenNegative() {
ReactorBuilder builder = newBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.setBatchSize(-1));
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final ReadOnlyWindowStore<GenericKey, ValueAndTime... | @Test
public void shouldFetchWithEndLowerBoundIfHighest() {
// Given:
final Range<Instant> startBounds = Range.closed(
NOW,
NOW.plusSeconds(10)
);
final Range<Instant> endBounds = Range.closed(
NOW.plusSeconds(5).plus(WINDOW_SIZE),
NOW.plusSeconds(15).plus(WINDOW_SIZE)... |
@Override
public void available() {
if (!allocationExcludeChecked) {
this.checkAllocationEnabledStatus();
}
} | @Test
public void testResetAllocation() throws IOException {
Settings settings = Settings.builder()
.put(OpensearchProcessImpl.CLUSTER_ROUTING_ALLOCATION_EXCLUDE_SETTING, nodeName)
.build();
when(clusterClient.getSettings(any(), any())).thenReturn(new ClusterGetSettin... |
public static Schema mergeWideningNullable(Schema schema1, Schema schema2) {
if (schema1.getFieldCount() != schema2.getFieldCount()) {
throw new IllegalArgumentException(
"Cannot merge schemas with different numbers of fields. "
+ "schema1: "
+ schema1
+ " s... | @Test
public void testWidenIterable() {
Schema schema1 = Schema.builder().addIterableField("field1", FieldType.INT32).build();
Schema schema2 =
Schema.builder().addIterableField("field1", FieldType.INT32.withNullable(true)).build();
Schema expected =
Schema.builder().addIterableField("fiel... |
public static boolean isValidValue(Map<String, Object> serviceSuppliedConfig,
Map<String, Object> clientSuppliedServiceConfig,
String propertyName)
{
// prevent clients from violating SLAs as published by the service
if (propertyName.eq... | @Test
public void testMaxResponse()
{
Map<String, Object> serviceSuppliedProperties = new HashMap<>();
serviceSuppliedProperties.put(PropertyKeys.HTTP_MAX_RESPONSE_SIZE, "1000");
Map<String, Object> clientSuppliedProperties = new HashMap<>();
clientSuppliedProperties.put(PropertyKeys.HTTP_MAX_RESPO... |
public <T> CompletableFuture<T> withLockAsync(final List<String> e164s,
final Supplier<CompletableFuture<T>> taskSupplier,
final Executor executor) {
if (e164s.isEmpty()) {
throw new IllegalArgumentException("List of e164s to lock must not be empty");
}
final List<LockItem> lockItems = n... | @Test
void withLockAsync() throws InterruptedException {
accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
() -> CompletableFuture.completedFuture(null), executor).join();
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLoc... |
@Override
public List<TransferItem> list(final Session<?> session, final Path remote,
final Local directory, final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("List children for %s", directory))... | @Test
public void testListSorted() throws Exception {
final NullLocal local = new NullLocal("t") {
@Override
public AttributedList<Local> list() {
AttributedList<Local> l = new AttributedList<>();
l.add(new NullLocal(this.getAbsolute(), "c"));
... |
@Override
public int delete(String patternId) {
final GrokPattern grokPattern;
try {
grokPattern = load(patternId);
} catch (NotFoundException e) {
log.debug("Couldn't find grok pattern with ID <{}> for deletion", patternId, e);
return 0;
}
... | @Test
@MongoDBFixtures("MongoDbGrokPatternServiceTest.json")
public void deleteNonExistentGrokPattern() {
assertThat(collection.countDocuments()).isEqualTo(3);
final int deletedRecords = service.delete("56250da2d4000000deadbeef");
assertThat(deletedRecords).isEqualTo(0);
assertT... |
@SuppressWarnings("unchecked")
public static <T extends SpecificRecord> TypeInformation<Row> convertToTypeInfo(
Class<T> avroClass) {
return convertToTypeInfo(avroClass, true);
} | @Test
void testAvroSchemaConversion() {
final String schema = User.getClassSchema().toString(true);
validateUserSchema(AvroSchemaConverter.convertToTypeInfo(schema));
} |
@Override
public List<TimelineEntity> getApplicationAttemptEntities(
ApplicationId appId, String fields, Map<String, String> filters,
long limit, String fromId) throws IOException {
String path = PATH_JOINER.join("clusters", clusterId, "apps",
appId, "entities", YARN_APPLICATION_ATTEMPT);
... | @Test
void getApplicationAttemptEntities() throws Exception {
ApplicationId applicationId =
ApplicationId.fromString("application_1234_0001");
List<TimelineEntity> entities =
client.getApplicationAttemptEntities(applicationId, null,
null, 0, null);
assertEquals(2, entities.size... |
public int getVersion() {
return _version;
} | @Test
public void withEmptyConf()
throws JsonProcessingException {
String confStr = "{}";
RangeIndexConfig config = JsonUtils.stringToObject(confStr, RangeIndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
assertEquals(config.getVersion(), RangeIndexConfig.DEFAULT.getV... |
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
Object span = request.getAttribute(SpanCustomizer.class.getName());
if (span instanceof SpanCustomizer) {
setHttpRouteAttribute(request);
handlerParser.preHandle(request, o, (SpanCustomizer) sp... | @Test void preHandle_nothingWhenNoSpanAttribute() {
interceptor.preHandle(request, response, controller);
verify(request).getAttribute("brave.SpanCustomizer");
verifyNoMoreInteractions(request, request, parser, span);
} |
public static Throwable findOriginalThrowable(Throwable throwable)
{
//just to make sure we don't go to infinite loop. Most exception is less than 100 level deep.
int depth = 0;
Throwable original = throwable;
while (original.getCause() != null && depth < 100)
{
original = original.getCause(... | @Test
public void testFindOriginalThrowable()
{
ConnectException connectException = new ConnectException("Foo");
RemoteInvocationException e = new RemoteInvocationException("Failed to get connect to a server", connectException);
Throwable throwable = LoadBalancerUtil.findOriginalThrowable(e);
Asser... |
public static SystemState deserialize(@NonNull ConfigMap configMap) {
Map<String, String> data = configMap.getData();
if (data == null) {
return new SystemState();
}
return JsonUtils.jsonToObject(data.getOrDefault(GROUP, emptyJsonObject()),
SystemState.class);
... | @Test
void deserialize() {
ConfigMap configMap = new ConfigMap();
SystemState systemState = SystemState.deserialize(configMap);
assertThat(systemState).isNotNull();
configMap.setData(Map.of(SystemState.GROUP, "{\"isSetup\":true}"));
systemState = SystemState.deserialize(conf... |
public String decode(byte[] val) {
return codecs[0].decode(val, 0, val.length);
} | @Test
public void testDecodeChineseLongTextGB2312() {
assertEquals(CHINESE_LONG_TEXT_GB2312,
gb2312().decode(CHINESE_LONG_TEXT_GB2312_BYTES));
} |
@Override
public void executor(final Collection<URIRegisterDTO> dataList) {
if (CollectionUtils.isEmpty(dataList)) {
return;
}
final Map<String, List<URIRegisterDTO>> groupByRpcType = dataList.stream()
.filter(data -> StringUtils.isNotBlank(data.getRpcType()))
... | @Test
public void testExecutor() {
List<URIRegisterDTO> list = new ArrayList<>();
uriRegisterExecutorSubscriber.executor(list);
assertTrue(list.isEmpty());
list.add(URIRegisterDTO.builder().rpcType(RpcTypeEnum.HTTP.getName())
.appName("test").contextPath("/test").buil... |
@Nullable
public static <T> T checkSerializable(@Nullable T object, @Nonnull String objectName) {
if (object == null) {
return null;
}
if (object instanceof DataSerializable) {
// hz-serialization is implemented, but we cannot actually check it - we don't have a
... | @Test
public void whenNullToCheckSerializable_thenReturnNull() {
Object returned = Util.checkSerializable(null, "object");
assertThat(returned).isNull();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.