focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<>();
if(replies.isEmpty()) {
return children;
}
// At least one entry successfully parsed... | @Test
public void testEmptyDir() throws Exception {
Path path = new Path(
"/www", EnumSet.of(Path.Type.directory));
String[] replies = new String[]{};
final AttributedList<Path> children = new FTPMlsdListResponseReader().read(path, Arrays.asList(replies));
assertEqu... |
public void executor(final ConfigGroupEnum type, final String json, final String eventType) {
ENUM_MAP.get(type).handle(json, eventType);
} | @Test
public void testPluginMyselfExecutor() {
String json = getJson();
websocketDataHandler.executor(ConfigGroupEnum.PLUGIN, json, DataEventTypeEnum.MYSELF.name());
List<PluginData> pluginDataList = new PluginDataHandler(pluginDataSubscriber).convert(json);
Mockito.verify(pluginData... |
public static <Req extends RpcRequest> Matcher<Req> serviceEquals(String service) {
if (service == null) throw new NullPointerException("service == null");
if (service.isEmpty()) throw new NullPointerException("service is empty");
return new RpcServiceEquals<Req>(service);
} | @Test void serviceEquals_unmatched_mixedCase() {
when(request.service()).thenReturn("grpc.health.v1.Health");
assertThat(serviceEquals("grpc.health.v1.health").matches(request)).isFalse();
} |
public EtlStatus getEtlJobStatus(SparkLoadAppHandle handle, String appId, long loadJobId, String etlOutputPath,
SparkResource resource, BrokerDesc brokerDesc) throws UserException {
EtlStatus status = new EtlStatus();
Preconditions.checkState(appId != null && !appId... | @Test(expected = TimeoutException.class)
public void testGetEtlJobStatusTimeout(@Mocked BrokerUtil brokerUtil, @Mocked Util util,
@Mocked SparkYarnConfigFiles sparkYarnConfigFiles,
@Mocked SparkLoadAppHandle handle)
th... |
File putIfAbsent(String userId, boolean saveToDisk) throws IOException {
String idKey = getIdStrategy().keyFor(userId);
String directoryName = idToDirectoryNameMap.get(idKey);
File directory = null;
if (directoryName == null) {
synchronized (this) {
directoryN... | @Test
public void testDirectoryFormatBasic() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "1user";
File directory1 = mapper.putIfAbsent(user1, true);
assertThat(directory1.getName(), startsWith(user1 + '_'));
} |
public void fillMaxSpeed(Graph graph, EncodingManager em) {
// In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info,
// but now we have and can fill the country-dependent max_speed value where missing.
EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(... | @Test
public void testFwdBwd() {
ReaderWay way = new ReaderWay(0L);
way.setTag("country", Country.DEU);
way.setTag("highway", "primary");
way.setTag("maxspeed:forward", "50");
way.setTag("maxspeed:backward", "70");
EdgeIteratorState edge = createEdge(way);
cal... |
@Override
public Set<Interface> getInterfaces() {
return interfaces.values()
.stream()
.flatMap(set -> set.stream())
.collect(collectingAndThen(toSet(), ImmutableSet::copyOf));
} | @Test
public void testRemoveInterface() throws Exception {
ConnectPoint cp = createConnectPoint(1);
NetworkConfigEvent event = new NetworkConfigEvent(
NetworkConfigEvent.Type.CONFIG_REMOVED, cp, CONFIG_CLASS);
assertEquals(NUM_INTERFACES, interfaceManager.getInterfaces().si... |
@Override
public void execute(Context context) {
long count = 0;
try (StreamWriter<ProjectDump.Rule> writer = dumpWriter.newStreamWriter(DumpElement.RULES)) {
ProjectDump.Rule.Builder ruleBuilder = ProjectDump.Rule.newBuilder();
for (Rule rule : ruleRepository.getAll()) {
ProjectDump.Rule ... | @Test
public void excuse_throws_ISE_exception_with_number_of_successfully_exported_rules() {
ruleRepository.add("A").add("B").add("C")
// will cause NPE
.addNull();
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
... |
public String generateKeyStorePassword() {
return RandomStringUtils.random(16, 0, 0, true, true, null, srand);
} | @Test
void testGenerateKeyStorePassword() throws Exception {
// We can't possibly test every possible string, but we can at least verify
// a few things about a few of the generated strings as a sanity check
ProxyCA proxyCA = new ProxyCA();
proxyCA.init();
Set<String> passwords = new HashSet<>();
... |
public JetSqlRow project(Object key, Object value) {
return project(key, null, value, null);
} | @Test
@SuppressWarnings("unchecked")
public void when_filteredByPredicate_then_returnsNull() {
KvRowProjector projector = new KvRowProjector(
new QueryPath[]{QueryPath.KEY_PATH, QueryPath.VALUE_PATH},
new QueryDataType[]{INT, INT},
new IdentityTarget(),
... |
@PublicAPI(usage = ACCESS)
public JavaPackage getPackage(String packageName) {
return getValue(tryGetPackage(packageName), "This package does not contain any sub package '%s'", packageName);
} | @Test
public void function_GET_CLASSES() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, Collection.class);
Iterable<JavaClass> classes = GET_CLASSES.apply(defaultPackage.getPackage("java.lang"));
assertThatTypes(classes).contain(Object.class, String.class);... |
public T getAndRemove(Predicate<T> preCondition) {
Iterator<T> iterator = deque.iterator();
for (int i = 0; iterator.hasNext(); i++) {
T next = iterator.next();
if (preCondition.test(next)) {
if (i < numPriorityElements) {
numPriorityElements--... | @Test
void testGetAndRemove() {
final PrioritizedDeque<Integer> deque = new PrioritizedDeque<>();
deque.add(0);
deque.add(1);
deque.add(2);
deque.add(1);
deque.add(3);
assertThat(deque.getAndRemove(v -> v == 1).intValue()).isOne();
assertThat(deque.a... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void throws_runtime_exception_on_malformed_tag_expression() {
RuntimeException e = assertThrows(RuntimeException.class, () -> {
RuntimeOptions options = parser
.parse("--tags", ")")
.build();
});
} |
public boolean shouldVerboseLog() {
return verboseLog;
} | @Test
public void testVerboseLog() {
final DistCpOptions.Builder builder = new DistCpOptions.Builder(
Collections.singletonList(new Path("hdfs://localhost:8020/source")),
new Path("hdfs://localhost:8020/target/"));
Assert.assertFalse(builder.build().shouldVerboseLog());
try {
builde... |
@Override
public Graph<Entity> resolveForInstallation(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Entity> entities) {
if (entity instanceof EntityV1) {
return resolveF... | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void resolveForInstallationLookupTable() throws NotFoundException {
when(lookupuptableBuilder.lookupTable("whois")).thenReturn(lookupuptableBuilder);
when(lookupuptableBuilder.lookupTable("tor-exit-node-list")).thenReturn(lookupuptableBuilder... |
@JsonProperty("status")
public Status status() {
if (indices.isEmpty() || indices.stream().allMatch(i -> i.status() == Status.NOT_STARTED)) {
return Status.NOT_STARTED;
} else if (indices.stream().allMatch(RemoteReindexIndex::isCompleted)) {
// all are now completed, either f... | @Test
void testStatusFinished() {
final RemoteReindexMigration migration = withIndices(
index("one", RemoteReindexingMigrationAdapter.Status.FINISHED),
index("two", RemoteReindexingMigrationAdapter.Status.FINISHED)
);
Assertions.assertThat(migration.status()).... |
@Override
public boolean hasGlobalAdminRole(String username) {
return roleService.hasGlobalAdminRole(username);
} | @Test
void testHasGlobalAdminRole4() {
NacosUser nacosUser = new NacosUser("nacos");
nacosUser.setGlobalAdmin(false);
when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true);
boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser);
... |
@Override
public int getColumnLength(final Object value) {
throw new UnsupportedSQLOperationException("PostgreSQLFloat4ArrayBinaryProtocolValue.getColumnLength()");
} | @Test
void assertGetColumnLength() {
assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().getColumnLength("val"));
} |
void validateLogLevelConfigs(Collection<AlterableConfig> ops) {
ops.forEach(op -> {
String loggerName = op.name();
switch (OpType.forId(op.configOperation())) {
case SET:
validateLoggerNameExists(loggerName);
String logLevel = op.va... | @Test
public void testValidateDeleteLogLevelConfig() {
MANAGER.validateLogLevelConfigs(Arrays.asList(new AlterableConfig().
setName(LOG.getName()).
setConfigOperation(OpType.DELETE.id()).
setValue("")));
} |
@Override
public void start() {
try {
createAndStartGrpcServer();
} catch (final IOException e) {
throw new IllegalStateException("Failed to start the grpc server", e);
}
} | @Test
void testNoGraceShutdown() {
// The server takes 5s seconds to shutdown
final TestServer server = new TestServer(5000);
when(this.factory.createServer()).thenReturn(server);
// But we won't wait
final GrpcServerLifecycle lifecycle = new GrpcServerLifecycle(this.factory... |
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception { // NOPMD
// cette méthode est appelée par le conteneur ejb grâce à l'annotation AroundInvoke
if (DISABLED || !EJB_COUNTER.isDisplayed()) {
return context.proceed();
}
// nom identifiant la requête
final String requestName ... | @Test
public void testMonitoringTarget() throws Exception {
final Counter ejbCounter = MonitoringProxy.getEjbCounter();
ejbCounter.clear();
final MonitoringTargetInterceptor interceptor = new MonitoringTargetInterceptor();
ejbCounter.setDisplayed(true);
interceptor.intercept(new InvokeContext(false));
ass... |
@Override
public long getLastUpdateTime() {
return record.getLastUpdateTime();
} | @Test
public void test_getLastUpdateTime() {
assertEquals(0, view.getLastUpdateTime());
} |
@POST
@Path("register")
@Produces(MediaType.APPLICATION_JSON)
public Response register(Application app) {
try {
if (app.getName()==null) {
throw new IOException("Application name can not be empty.");
}
if (app.getOrganization()==null) {
throw new IOException("Application orga... | @Test
void testRegister() throws Exception {
AppStoreController ac = Mockito.mock(AppStoreController.class);
Application app = new Application();
app.setName("jenkins");
app.setOrganization("jenkins.org");
app.setDescription("This is a description");
app.setIcon("/css/img/feather.png");
Re... |
public List<ColumnMatchResult<?>> getMismatchedColumns(List<Column> columns, ChecksumResult controlChecksum, ChecksumResult testChecksum)
{
return columns.stream()
.flatMap(column -> columnValidators.get(column.getCategory()).get().validate(column, controlChecksum, testChecksum).stream())
... | @Test
public void testFloatingPoint()
{
List<Column> columns = ImmutableList.of(DOUBLE_COLUMN, REAL_COLUMN);
ChecksumResult controlChecksum = new ChecksumResult(
5,
ImmutableMap.<String, Object>builder()
.putAll(FLOATING_POINT_COUNTS)
... |
@Override
public ResponseHeader execute() throws SQLException {
check(sqlStatement, connectionSession.getConnectionContext().getGrantee());
if (isDropCurrentDatabase(sqlStatement.getDatabaseName())) {
checkSupportedDropCurrentDatabase(connectionSession);
connectionSession.set... | @Test
void assertExecuteDropNotExistDatabase() {
when(sqlStatement.getDatabaseName()).thenReturn("test_not_exist_db");
assertThrows(DatabaseDropNotExistsException.class, () -> handler.execute());
} |
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
... | @Test
public void testInfo() {
Info info = SingletonServiceFactory.getBean(Info.class);
Assert.assertEquals("contact", info.getContact().getName());
Assert.assertEquals("license", info.getLicense().getName());
} |
public HttpResult getBinary(String url) throws IOException, NotModifiedException {
return getBinary(url, null, null);
} | @Test
void dataTimeout() {
Mockito.when(config.httpClient().responseTimeout()).thenReturn(Duration.ofMillis(500));
this.getter = new HttpGetter(config, Mockito.mock(CommaFeedVersion.class), Mockito.mock(MetricRegistry.class));
this.mockServerClient.when(HttpRequest.request().withMethod("GET"))
.respond(Http... |
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
super.check( remarks, transMeta, stepMeta, prev, input, output, i... | @Test
public void testCheck() {
SalesforceInputMeta meta = new SalesforceInputMeta();
meta.setDefault();
List<CheckResultInterface> remarks = new ArrayList<CheckResultInterface>();
meta.check( remarks, null, null, null, null, null, null, null, null, null );
boolean hasError = false;
for ( Chec... |
@Override
public boolean isSecured(ApplicationId appId) {
SecurityInfo info = states.get(appId).value();
return info == null ? false : info.getState().equals(SECURED);
} | @Test
public void testIsSecured() {
SecurityInfo info = states.get(appId);
assertEquals(SECURED, info.getState());
} |
@Override
public PermissionTicket createTicket(ResourceSet resourceSet, Set<String> scopes) {
// check to ensure that the scopes requested are a subset of those in the resource set
if (!scopeService.scopesMatch(resourceSet.getScopes(), scopes)) {
throw new InsufficientScopeException("Scopes of resource set ar... | @Test(expected = InsufficientScopeException.class)
public void testCreate_scopeMismatch() {
@SuppressWarnings("unused")
// try to get scopes outside of what we're allowed to do, this should throw an exception
PermissionTicket perm = permissionService.createTicket(rs1, scopes2);
} |
@Override
protected CompletableFuture<TaskManagerDetailsInfo> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request,
@Nonnull ResourceManagerGateway gateway)
throws RestHandlerException {
final ResourceID taskManagerResourceId =
request.getPathP... | @Test
void testTaskManagerMetricsInfoExtraction()
throws RestHandlerException, ExecutionException, InterruptedException,
JsonProcessingException, HandlerRequestException {
initializeMetricStore(metricFetcher.getMetricStore());
resourceManagerGateway.setRequestTaskMana... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
String methodName = RpcUtils.getMethodName(invocation);
int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0);
final RpcStatus rpcStatus = R... | @Test
void testInvokeNoActives() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
activeLimitFilter.invoke... |
public Set<TaskId> standbyTasks() {
return unmodifiableSet(assignedStandbyTasks.taskIds());
} | @Test
public void shouldNotModifyStandbyView() {
final ClientState clientState = new ClientState(1);
final Set<TaskId> taskIds = clientState.standbyTasks();
assertThrows(UnsupportedOperationException.class, () -> taskIds.add(TASK_0_0));
assertThat(clientState, hasStandbyTasks(0));
... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateMultiStatsWhenAllAvailable() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3");
ColumnStatisticsData data1 = new ColStatsBuilder<>(double.class).numNulls(1).numDVs(3)
.low(1d).high(3d).hll(1, 2, 3).build();
ColumnStatisticsDat... |
public static boolean isUUID(CharSequence value) {
return isMatchRegex(UUID, value) || isMatchRegex(UUID_SIMPLE, value);
} | @Test
public void isUUIDTest() {
assertTrue(Validator.isUUID(IdUtil.randomUUID()));
assertTrue(Validator.isUUID(IdUtil.fastSimpleUUID()));
assertTrue(Validator.isUUID(IdUtil.randomUUID().toUpperCase()));
assertTrue(Validator.isUUID(IdUtil.fastSimpleUUID().toUpperCase()));
} |
@Override
public void onChangeLogParsed(Run<?, ?> run, SCM scm, TaskListener listener, ChangeLogSet<?> changelog) throws Exception {
try {
JiraSite jiraSite = JiraSite.get(run.getParent());
if (jiraSite == null) {
return;
}
Collection<String> ... | @Test
public void changeSetHasNoJiraIssue() throws Exception {
JiraSCMListener listener = new JiraSCMListener();
Job job = mock(Job.class);
Run run = mock(Run.class);
ChangeLogSet logSet = mock(ChangeLogSet.class);
final ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.cla... |
ConsumerRecord<Object, Object> deserialize(final ProcessorContext<?, ?> processorContext,
final ConsumerRecord<byte[], byte[]> rawRecord) {
try {
return new ConsumerRecord<>(
rawRecord.topic(),
rawRecord.partition(),
... | @Test
public void shouldFailWhenDeserializationFailsAndExceptionHandlerThrows() {
try (final Metrics metrics = new Metrics()) {
final RecordDeserializer recordDeserializer = new RecordDeserializer(
new TheSourceNode(
sourceNodeName,
... |
private LinkKey(ConnectPoint src, ConnectPoint dst) {
this.src = checkNotNull(src);
this.dst = checkNotNull(dst);
} | @Test
public void testCompareEquals() {
LinkKey k1 = LinkKey.linkKey(SRC1, DST2);
LinkKey k2 = LinkKey.linkKey(SRC1, DST2);
assertThat(k1, is(equalTo(k2)));
} |
@Override
public void consume(Update update) {
super.consume(update);
} | @Test
void canProcessUpdatesWithoutUserInfo() {
Update update = mock(Update.class);
// At the moment, only poll updates carry no user information
when(update.hasPoll()).thenReturn(true);
bot.consume(update);
} |
public List<JournalReadEntry> readNext(long startOffset, long requestedMaximumCount) {
// Capture the log end offset early for the failure handling below. The end offset will change during the
// runtime of the retry loop because new messages are written to the journal. If we would use the changing
... | @Test
@Ignore
public void readNext() throws Exception {
final LocalKafkaJournal journal = new LocalKafkaJournal(journalDirectory.toPath(),
scheduler, Size.kilobytes(1L),
Duration.standardHours(1),
Size.kilobytes(10L),
Duration.standardDays(... |
public static <E> FilterIter<E> filtered(final Iterator<? extends E> iterator, final Filter<? super E> filter) {
return new FilterIter<>(iterator, filter);
} | @Test
public void filteredTest(){
final List<String> obj2 = ListUtil.toList("3");
final List<String> obj = ListUtil.toList("1", "3");
final FilterIter<String> filtered = IterUtil.filtered(obj.iterator(), obj2::contains);
assertEquals("3", filtered.next());
assertFalse(filtered.hasNext());
} |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void parseWxworkMobileTest() {
final String uaString = "Mozilla/5.0 (Linux; Android 10; JSN-AL00 Build/HONORJSN-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045710 Mobile Safari/537.36 wxwork/3.1.10 ColorScheme/Light MicroMessenger/7.0.1 NetType/WI... |
@Override
public Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey,
SubscriberPermissionsOnProject subscriberPermissionsOnProject) {
verifyProjectKey(projectKey);
try (DbSession dbSession = dbClient.openSession(false)) {
Set<EmailSubscriberDto> emailSubscribe... | @Test
public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_projectKey_is_null() {
String dispatcherKey = randomAlphabetic(12);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerE... |
@Override
public Set<K8sNode> nodes() {
return nodeStore.nodes();
} | @Test
public void testGetAllNodes() {
assertEquals(ERR_SIZE, 2, target.nodes().size());
assertTrue(ERR_NOT_FOUND, target.nodes().contains(MINION_2));
assertTrue(ERR_NOT_FOUND, target.nodes().contains(MINION_3));
} |
@Override
public AlterConsumerGroupOffsetsResult alterConsumerGroupOffsets(
String groupId,
Map<TopicPartition, OffsetAndMetadata> offsets,
AlterConsumerGroupOffsetsOptions options
) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, Errors>> future =
Alte... | @Test
public void testAlterConsumerGroupOffsetsNonRetriableErrors() throws Exception {
// Non-retriable errors throw an exception
final TopicPartition tp1 = new TopicPartition("foo", 0);
final List<Errors> nonRetriableErrors = asList(
Errors.GROUP_AUTHORIZATION_FAILED, Errors.IN... |
public boolean isExpired() {
return super.isExpired();
} | @Test
public void testAnonymous() {
Assert.assertNotNull(AuthenticationToken.ANONYMOUS);
Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getUserName());
Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getName());
Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getType());
A... |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void create_query_on_qualifier() {
ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("APP").build()),
emptySet());
assertThat(query.getQualifiers().get()).containsOnly("APP");
} |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringWithDelimiterAndEmptyEnclosure() {
String mask = "Hello%s world";
String[] chunks = {"Hello", " world"};
String stringToSplit = String.format( mask, DELIMITER1 );
String[] result = Const.splitString( stringToSplit, DELIMITER1, "" );
assertSplit( result, chunks );
... |
public static String[] tokenizeOnSpace(String s)
{
return Arrays.stream(s.split("(?<=" + StringUtil.PATTERN_SPACE + ")|(?=" + StringUtil.PATTERN_SPACE + ")"))
.toArray(String[]::new);
} | @Test
void testTokenizeOnSpace_onlySpacesWithText()
{
String[] result = StringUtil.tokenizeOnSpace(" a ");
assertArrayEquals(new String[] {" ", " ", "a", " ", " "}, result);
} |
public static double add(float v1, float v2) {
return add(Float.toString(v1), Float.toString(v2)).doubleValue();
} | @Test
public void addTest3() {
final float a = 3.15f;
final double b = 4.22;
final double result = NumberUtil.add(a, b, a, b).doubleValue();
assertEquals(14.74, result, 0);
} |
public static <E extends Throwable> void withContextClassLoader(
final ClassLoader cl, final ThrowingRunnable<E> r) throws E {
try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(cl)) {
r.run();
}
} | @Test
void testRunWithContextClassLoaderRunnable() {
final ClassLoader aPrioriContextClassLoader =
Thread.currentThread().getContextClassLoader();
try {
final ClassLoader original = new URLClassLoader(new URL[0]);
final ClassLoader temp = new URLClassLoader(n... |
@Override
public ConnectResponse<List<SimpleConnectorPluginInfo>> connectorPlugins() {
try {
LOG.debug("Issuing request to Kafka Connect at URI {} to list connector plugins", connectUri);
final ConnectResponse<List<SimpleConnectorPluginInfo>> connectResponse =
withRetries(() -> Request
... | @Test
public void testListPlugins() throws JsonProcessingException {
// Given:
MAPPER.writeValueAsString(ImmutableList.of(SAMPLE_PLUGIN));
WireMock.stubFor(
WireMock.get(WireMock.urlEqualTo(pathPrefix + "/connector-plugins"))
.withHeader(AUTHORIZATION.toString(), new EqualToPattern(AU... |
public double calculateDensity(Graph graph, boolean isGraphDirected) {
double result;
double edgesCount = graph.getEdgeCount();
double nodesCount = graph.getNodeCount();
double multiplier = 1;
if (!isGraphDirected) {
multiplier = 2;
}
result = (multi... | @Test
public void testDirectedPathGraphDensity() {
GraphModel graphModel = GraphGenerator.generatePathDirectedGraph(2);
DirectedGraph graph = graphModel.getDirectedGraph();
GraphDensity d = new GraphDensity();
double density = d.calculateDensity(graph, true);
assertEquals(den... |
public boolean isInfrastructure(ConnectPoint connectPoint) {
return infrastructurePoints.get().contains(connectPoint);
} | @Test
public void pointRelated() {
assertTrue("should be infrastructure point",
dt.isInfrastructure(new ConnectPoint(D1, P1)));
assertFalse("should not be infrastructure point",
dt.isInfrastructure(new ConnectPoint(D1, P2)));
} |
@Override
public synchronized boolean onActivity() {
if (!firstEventReceived) {
firstEventReceived = true;
return true;
}
return false;
} | @Test
public void testOnActivity_FirstCall() {
assertTrue(strategy.onActivity(), "First call of onActivity() should return true.");
} |
public static Compression.Algorithm getHFileCompressionAlgorithm(Map<String, String> paramsMap) {
String algoName = paramsMap.get(HFILE_COMPRESSION_ALGORITHM_NAME.key());
if (StringUtils.isNullOrEmpty(algoName)) {
return Compression.Algorithm.GZ;
}
return Compression.Algorithm.valueOf(algoName.toU... | @Test
public void testGetHFileCompressionAlgorithmWithEmptyString() {
assertEquals(Compression.Algorithm.GZ, getHFileCompressionAlgorithm(
Collections.singletonMap(HFILE_COMPRESSION_ALGORITHM_NAME.key(), "")));
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchErrorShouldClearPreferredReadReplica() {
buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(), new BytesDeserializer(),
Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED, Duration.ofMinutes(5).toMillis());
subscriptions.ass... |
@Override
public LifecycleConfiguration getConfiguration(final Path file) throws BackgroundException {
final Path container = containerService.getContainer(file);
if(container.isRoot()) {
return LifecycleConfiguration.empty();
}
try {
final Storage.Buckets.Get... | @Test
public void testGetConfigurationAccessDenied() throws Exception {
assertEquals(LifecycleConfiguration.empty(), new GoogleStorageLifecycleFeature(session).getConfiguration(
new Path("bucket", EnumSet.of(Path.Type.directory))
));
} |
@Override
public boolean hasGlobalAdminRole(String username) {
return roleService.hasGlobalAdminRole(username);
} | @Test
void testHasGlobalAdminRole() {
when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true);
boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole("nacos");
assertTrue(hasGlobalAdminRole);
} |
@VisibleForTesting
public int getClusterNodesFailedRetrieved() {
return numGetClusterNodesFailedRetrieved.value();
} | @Test
public void testGetClusterNodesFailed() {
long totalBadBefore = metrics.getClusterNodesFailedRetrieved();
badSubCluster.getClusterNodes();
Assert.assertEquals(totalBadBefore + 1, metrics.getClusterNodesFailedRetrieved());
} |
public static Integer getFirstNumber(CharSequence StringWithNumber) {
return Convert.toInt(get(PatternPool.NUMBERS, StringWithNumber, 0), null);
} | @Test
public void getFirstNumberTest() {
// 找到匹配的第一个数字
final Integer resultGetFirstNumber = ReUtil.getFirstNumber(content);
assertEquals(Integer.valueOf(1234), resultGetFirstNumber);
} |
@VisibleForTesting
JobMeta filterPrivateDatabases( JobMeta jobMeta ) {
Set<String> privateDatabases = jobMeta.getPrivateDatabases();
if ( privateDatabases != null ) {
// keep only private transformation databases
for ( Iterator<DatabaseMeta> it = jobMeta.getDatabases().iterator(); it.hasNext(); ) ... | @Test
public void filterPrivateDatabasesWithOnePrivateDatabaseTest() {
IUnifiedRepository purMock = mock( IUnifiedRepository.class );
JobMeta jobMeta = new JobMeta( );
jobMeta.setDatabases( getDummyDatabases() );
Set<String> privateDatabases = new HashSet<>( );
privateDatabases.add( "database2" ... |
@Override
public SymbolTable getSymbolTable(String symbolTableName)
{
try
{
SymbolTableMetadata metadata = _symbolTableNameHandler.extractMetadata(symbolTableName);
String serverNodeUri = metadata.getServerNodeUri();
String tableName = metadata.getSymbolTableName();
boolean isRemote ... | @Test(expectedExceptions = IllegalStateException.class)
public void testGetRemoteSymbolTableFetchError()
{
RestResponseBuilder builder = new RestResponseBuilder();
builder.setStatus(404);
when(_client.restRequest(eq(new RestRequestBuilder(URI.create("https://OtherHost:100/service/symbolTable/Test--33200... |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeDatetime() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.DATETIME), instanceOf(MySQLDateBinaryProtocolValue.class));
} |
public void start() {
LOG.info("Running process from " + executable.toAbsolutePath());
CommandLine cmdLine = new CommandLine(executable.toAbsolutePath().toString());
arguments.forEach(it -> cmdLine.addArgument(it, true));
try {
createExecutor().execute(cmdLine, environment.... | @Test
void testExitCode() throws ExecutionException, InterruptedException, TimeoutException {
final CompletableFuture<Integer> exitCodeFuture = new CompletableFuture<>();
final ProcessListener listener = new ProcessListener() {
@Override
public void onStart() {
}... |
@Override
public Num calculate(BarSeries series, Position position) {
if (position == null || !position.isClosed()) {
return series.zero();
}
Returns returns = new Returns(series, position, Returns.ReturnType.LOG);
return calculateVaR(returns, confidence);
} | @Test
public void calculateOnlyWithLossPositions() {
series = new MockBarSeries(numFunction, 100d, 95d, 100d, 80d, 85d, 70d);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series),
Trade.buyAt(2, series), Trade.sellAt(5, series));
... |
protected void setMethod() {
boolean activateBody = RestMeta.isActiveBody( wMethod.getText() );
boolean activateParams = RestMeta.isActiveParameters( wMethod.getText() );
wlBody.setEnabled( activateBody );
wBody.setEnabled( activateBody );
wApplicationType.setEnabled( activateBody );
wlParamet... | @Test
public void testSetMethod_GET() {
doReturn( RestMeta.HTTP_METHOD_GET ).when( method ).getText();
dialog.setMethod();
verify( bodyl, times( 1 ) ).setEnabled( false );
verify( body, times( 1 ) ).setEnabled( false );
verify( type, times( 1 ) ).setEnabled( false );
verify( paramsl, times(... |
public static void updateHadoopConfig(org.apache.hadoop.conf.Configuration hadoopConfig) {
LOG.info("Updating Hadoop configuration");
String providers = hadoopConfig.get(PROVIDER_CONFIG_NAME, "");
if (!providers.contains(DynamicTemporaryAWSCredentialsProvider.NAME)) {
if (providers.... | @Test
public void updateHadoopConfigShouldSetProviderWhenEmpty() {
org.apache.hadoop.conf.Configuration hadoopConfiguration =
new org.apache.hadoop.conf.Configuration();
hadoopConfiguration.set(PROVIDER_CONFIG_NAME, "");
AbstractS3DelegationTokenReceiver.updateHadoopConfig(ha... |
@NotNull
public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) {
// 优先从 DB 中获取,因为 code 有且可以使用一次。
// 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次
SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state);
i... | @Test
public void testAuthSocialUser_notNull() {
// mock 数据
SocialUserDO socialUser = randomPojo(SocialUserDO.class,
o -> o.setType(SocialTypeEnum.GITEE.getType()).setCode("tudou").setState("yuanma"));
socialUserMapper.insert(socialUser);
// 准备参数
Integer socia... |
@Override
public Health health() {
if (registerCenterService == null) {
registerCenterService = PluginServiceManager.getPluginService(RegisterCenterService.class);
}
return Health.status(new Status(registerCenterService.getRegisterCenterStatus(), "Service Center is alive"))
... | @Test
public void health() {
try (final MockedStatic<PluginServiceManager> pluginServiceManagerMockedStatic = Mockito.mockStatic(PluginServiceManager.class);){
pluginServiceManagerMockedStatic.when(() -> PluginServiceManager.getPluginService(RegisterCenterService.class))
.the... |
@Override
public Table getTable(String dbName, String tblName) {
return get(tableCache, OdpsTableName.of(dbName, tblName));
} | @Test
public void testGetTable() throws ExecutionException {
OdpsTable table = (OdpsTable) odpsMetadata.getTable("project", "tableName");
Assert.assertTrue(table.isOdpsTable());
Assert.assertEquals("tableName", table.getName());
Assert.assertEquals("project", table.getDbName());
... |
private Collection<String> getDataSourceNames(final Collection<ShardingTableRuleConfiguration> tableRuleConfigs,
final Collection<ShardingAutoTableRuleConfiguration> autoTableRuleConfigs, final Collection<String> dataSourceNames) {
if (tableRuleConfigs.isEmpty()... | @Test
void assertGetDataSourceNamesWithoutShardingTablesAndShardingAutoTables() {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
ShardingRule shardingRule = new ShardingRule(shardingRuleConfig, createDataSources(), mock(ComputeNodeInstanceContext.class));
ass... |
@Override
public Integer clusterGetSlotForKey(byte[] key) {
RFuture<Integer> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.KEYSLOT, key);
return syncFuture(f);
} | @Test
public void testClusterGetSlotForKey() {
Integer slot = connection.clusterGetSlotForKey("123".getBytes());
assertThat(slot).isNotNull();
} |
public static GaussianProcessRegression<double[]> fit(double[][] x, double[] y, Properties params) {
MercerKernel<double[]> kernel = MercerKernel.of(params.getProperty("smile.gaussian_process.kernel", "linear"));
double noise = Double.parseDouble(params.getProperty("smile.gaussian_process.noise", "1E-10... | @Test
public void testHPO() {
System.out.println("HPO longley");
MathEx.setSeed(19650218); // to get repeatable results.
double[][] longley = MathEx.clone(Longley.x);
MathEx.standardize(longley);
GaussianProcessRegression<double[]> model = GaussianProcessRegression.fit(lon... |
@Override
public int hashCode() {
int result = principalType != null ? principalType.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
} | @Test
public void testEqualsAndHashCode() {
String name = "KafkaUser";
KafkaPrincipal principal1 = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, name);
KafkaPrincipal principal2 = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, name);
assertEquals(principal1.hashCode(), principal2.hashC... |
public static Optional<String> getSystemProperty(String propertyName) {
return Optional.ofNullable(getSystemProperty(propertyName, null));
} | @Test
public void getSystemProperty_whenPropertyNotExists_returnsEmptyOptional() {
assertThat(TsunamiConfig.getSystemProperty(TEST_PROPERTY)).isEmpty();
} |
public long getExpireTimeInSeconds(String token) throws AccessException {
return NacosSignatureAlgorithm.getExpiredTimeInSeconds(token, key);
} | @Test
void testGetExpireTimeInSeconds() throws AccessException {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
long expiredTimeSec... |
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName, boolean maintainType) {
return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType);
} | @Test
public void testNullTypeFieldName() {
assertThatThrownBy(() -> RuntimeTypeAdapterFactory.of(BillingInstrument.class, null))
.isInstanceOf(NullPointerException.class);
} |
@Override
public void handlerPlugin(final PluginData pluginData) {
super.getWasmExtern(HANDLER_PLUGIN_METHOD_NAME)
.ifPresent(handlerPlugin -> callWASI(pluginData, handlerPlugin));
} | @Test
public void handlerPluginTest() {
pluginDataHandler.handlerPlugin(pluginData);
testWasmPluginDataHandler.handlerPlugin(pluginData);
} |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testEarlyAndAtWatermark() throws Exception {
tester =
TriggerStateMachineTester.forTrigger(
AfterWatermarkStateMachine.pastEndOfWindow().withEarlyFirings(mockEarly),
FixedWindows.of(Duration.millis(100)));
injectElements(1);
IntervalWindow window = new In... |
static <K, V> StateSerdes<K, V> prepareStoreSerde(final StateStoreContext context,
final String storeName,
final String changelogTopic,
final Serde<K> keySerd... | @Test
public void shouldThrowStreamsExceptionWithExplicitErrorMessageForStateStoreContext() {
final MockInternalNewProcessorContext<String, String> context = new MockInternalNewProcessorContext<>();
utilsMock.when(() -> WrappingNullableUtils.prepareValueSerde(any(), any())).thenThrow(new StreamsExc... |
public static Schema create(Type type) {
switch (type) {
case STRING:
return new StringSchema();
case BYTES:
return new BytesSchema();
case INT:
return new IntSchema();
case LONG:
return new LongSchema();
case FLOAT:
return new FloatSchema();
case DOUBLE:
... | @Test
void longDefaultValue() {
Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", 1L);
assertTrue(field.hasDefaultValue());
assertEquals(1L, field.defaultVal());
assertEquals(1L, GenericData.get().getDefaultValue(field));
field = new Schema.Field("myField", ... |
public static CsvMapper createCsvMapper() {
final CsvMapper csvMapper = new CsvMapper();
registerModules(csvMapper);
return csvMapper;
} | @Test
void testCsvMapperOptionalSupportedEnabled() throws Exception {
final CsvMapper mapper =
JacksonMapperFactory.createCsvMapper()
// ensures symmetric read/write behavior for empty optionals/strings
// ensures: Optional.empty() --write-->... |
public static boolean isPubKeyCompressed(byte[] encoded) {
if (encoded.length == 33 && (encoded[0] == 0x02 || encoded[0] == 0x03))
return true;
else if (encoded.length == 65 && encoded[0] == 0x04)
return false;
else
throw new IllegalArgumentException(ByteUtils... | @Test(expected = IllegalArgumentException.class)
public void isPubKeyCompressed_tooShort() {
ECKey.isPubKeyCompressed(ByteUtils.parseHex("036d"));
} |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
ScannerReport.LineCoverage reportCoverage = getNextLineCoverageIfMatchLine(lineBuilder.getLine());
if (reportCoverage != null) {
processCoverage(lineBuilder, reportCoverage);
coverage = null;
}
return Optio... | @Test
public void set_coverage() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(ScannerReport.LineCoverage.newBuilder()
.setLine(1)
.setConditions(10)
.setHits(true)
.setCoveredConditions(2)
.build()).iterator());
DbFileSources.Line.Builder lineBu... |
public void setPreservePathElements(boolean preservePathElements) {
this.preservePathElements = preservePathElements;
} | @Test
public void testTarWithPreservedPathElements() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:tar");
mock.expectedMessageCount(1);
mock.expectedHeaderReceived(FILE_NAME, "poem.txt.tar");
tar.setPreservePathElements(true);
template.sendBodyAndHeader("dire... |
@Override
public TimeSeriesEntry<V, L> pollLastEntry() {
return get(pollLastEntryAsync());
} | @Test
public void testPollLastEntry() {
RTimeSeries<String, String> t = redisson.getTimeSeries("test");
t.add(1, "10", "100");
t.add(2, "20");
t.add(3, "30");
TimeSeriesEntry<String, String> e = t.pollLastEntry();
assertThat(e).isEqualTo(new TimeSeriesEntry<>(3, "30"... |
@SneakyThrows
@Override
public Integer call() throws Exception {
super.call();
PicocliRunner.call(App.class, "template", "namespace", "--help");
return 0;
} | @Test
void runWithNoParam() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) {
String[] args = {};
Integer call = PicocliRunner... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(true);
}
boolean result = true;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
ret... | @Test
void invokeListParamReturnTrue() {
FunctionTestUtil.assertResult(nnAllFunction.invoke(Arrays.asList(Boolean.TRUE, Boolean.TRUE)), true);
} |
public static String describe(List<org.apache.iceberg.expressions.Expression> exprs) {
return exprs.stream().map(Spark3Util::describe).collect(Collectors.joining(", "));
} | @Test
public void testDescribeExpression() {
Expression refExpression = equal("id", 1);
assertThat(Spark3Util.describe(refExpression)).isEqualTo("id = 1");
Expression yearExpression = greaterThan(year("ts"), 10);
assertThat(Spark3Util.describe(yearExpression)).isEqualTo("year(ts) > 10");
Express... |
public static <T> TimeLimiterOperator<T> of(TimeLimiter timeLimiter) {
return new TimeLimiterOperator<>(timeLimiter);
} | @Test
public void otherErrorUsingMono() {
given(timeLimiter.getTimeLimiterConfig())
.willReturn(toConfig(Duration.ofMinutes(1)));
given(helloWorldService.returnHelloWorld())
.willThrow(new Error("BAM!"));
Mono<?> mono = Mono.fromCallable(helloWorldService::returnHell... |
int compareSegmentedKeys(final Bytes cacheKey, final Bytes storeKey) {
final long storeSegmentId = segmentId(storeKey);
final long cacheSegmentId = ByteBuffer.wrap(cacheKey.get()).getLong();
final int segmentCompare = Long.compare(cacheSegmentId, storeSegmentId);
if (segmentCompare == 0... | @Test
public void compareSegmentedKeys() {
assertThat(
"same key in same segment should be ranked the same",
cacheFunction.compareSegmentedKeys(
cacheFunction.cacheKey(THE_KEY),
THE_KEY
) == 0
);
final Bytes sameKeyInPriorS... |
@Override
public Optional<IndexMetaData> revise(final String tableName, final IndexMetaData originalMetaData, final ShardingRule rule) {
if (shardingTable.getActualDataNodes().isEmpty()) {
return Optional.empty();
}
IndexMetaData result = new IndexMetaData(IndexMetaDataUtils.getL... | @Test
void assertReviseWhenActualDataNodeIsEmpty() {
shardingRule = createShardingRule();
ShardingTable shardingTable = mock(ShardingTable.class);
when(shardingTable.getActualDataNodes()).thenReturn(Collections.emptyList());
shardingIndexReviser = new ShardingIndexReviser(shardingTab... |
public static OpenGaussErrorResponsePacket newInstance(final Exception cause) {
Optional<ServerErrorMessage> serverErrorMessage = findServerErrorMessage(cause);
return serverErrorMessage.map(OpenGaussErrorResponsePacket::new).orElseGet(() -> createErrorResponsePacket(SQLExceptionTransformEngine.toSQLExc... | @Test
void assertNewInstanceWithServerErrorMessage() {
String encodedMessage = "SFATAL\0C3D000\0Mdatabase \"test\" does not exist\0c-1\0Ddetail\0Hhint\0P1\0p2\0qinternal query\0Wwhere\0Ffile\0L3\0Rroutine\0a0.0.0.0:1";
PSQLException cause = new PSQLException(new ServerErrorMessage(encodedMessage));
... |
public BlobConfiguration getConfiguration() {
return configuration;
} | @Test
void testCreateEndpointWithChangeFeedConfig() {
context.getRegistry().bind("creds", storageSharedKeyCredential());
context.getRegistry().bind("metadata", Collections.emptyMap());
context.getRegistry().bind("starttime",
OffsetDateTime.of(LocalDate.of(2021, 8, 4), LocalTi... |
static void checkValidTableId(String idToCheck) {
if (idToCheck.length() < MIN_TABLE_ID_LENGTH) {
throw new IllegalArgumentException("Table ID " + idToCheck + " cannot be empty.");
}
if (idToCheck.length() > MAX_TABLE_ID_LENGTH) {
throw new IllegalArgumentException(
"Table ID "
... | @Test
public void testCheckValidTableIdWhenIdContainsIllegalCharacter() {
assertThrows(IllegalArgumentException.class, () -> checkValidTableId("table-id%"));
} |
@Override
void execute() {
Set<String> hdfsRoots = getObjectStore().listFSRoots();
if (hdfsRoots != null) {
System.out.println("Listing FS Roots..");
for (String s : hdfsRoots) {
System.out.println(s);
}
} else {
System.err.println("Encountered error during listFSRoot");
... | @Test
public void testListFSRoot() throws Exception {
String fsRoot1 = "hdfs://abc.de";
String fsRoot2 = "hdfs://fgh.ji";
ObjectStore mockObjectStore = Mockito.mock(ObjectStore.class);
when(mockObjectStore.listFSRoots()).thenReturn(Sets.newHashSet(fsRoot1, fsRoot2));
OutputStream os = new ByteAr... |
static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure {
if (!a.exists()) {
throw new IllegalArgumentException("File [" + a + "] does not exist.");
}
if (!b.exists()) {
throw new IllegalArgumentException("File [" + b + "] does not exist.");
}
// Implements the follo... | @Ignore
@Test
public void manual_filesOnDifferentVolumesShouldBeDetectedAsSuch() throws RolloverFailure {
if(!EnvUtil.isJDK7OrHigher())
return;
// author's computer has two volumes
File c = new File("c:/tmp/");
File d = new File("d:/");
assertFalse(FileStoreUtil.areOnSameFileStore(c, d));... |
@VisibleForTesting
void submit(long requestId, DispatchableSubPlan dispatchableSubPlan, long timeoutMs, Map<String, String> queryOptions)
throws Exception {
Deadline deadline = Deadline.after(timeoutMs, TimeUnit.MILLISECONDS);
// Serialize the stage plans in parallel
List<DispatchablePlanFragment> ... | @Test
public void testQueryDispatcherThrowsWhenQueryServerTimesOut() {
String sql = "SELECT * FROM a WHERE col1 = 'foo'";
QueryServer failingQueryServer = _queryServerMap.values().iterator().next();
CountDownLatch neverClosingLatch = new CountDownLatch(1);
Mockito.doAnswer(invocationOnMock -> {
... |
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(keyType, "keyType may not be null");
requireNonNull(valueType, "valueType may not be null");
if (dataTable.isEmpty()) {... | @Test
void to_map_of_unknown_value_type__throws_exception() {
DataTable table = parse("",
" | Annie M. G. Schmidt | 1911-03-20 |",
" | Roald Dahl | 1916-09-13 |",
" | Astrid Lindgren | 1907-11-14 |");
CucumberDataTableException exception = assertThrow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.