src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
Upgrade { @VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; } Upgrade(DACConfig dacConfig, ScanResult classPathScan, boolean verbose); void run(); void run(boolean noDBOpenRetry); @VisibleForTesting void validateUpgrade(final LegacyKVStoreProvider storeProvider, final String curEdi... | @Test public void testMaxTaskVersion() { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); final Optional<Version> tasksGreatestMaxVersion = upgrade.getUpgradeTasks().stream() .filter((v) -> v instanceof LegacyUpgradeTask) .map((v) -> ((LegacyUpgradeTas... |
ReflectionResource { @POST public Reflection createReflection(Reflection reflection) { ReflectionGoal newReflection = reflectionServiceHelper.createReflection(reflection.toReflectionGoal()); String id = newReflection.getId().getId(); return new Reflection(newReflection, reflectionServiceHelper.getStatusForReflection(id... | @Test public void testUpdateReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); String betterName = "much better name"; response.setName(betterName); Reflect... |
ReflectionResource { @DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); @GET @Path("/{... | @Test public void testDeleteReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response... |
SourceResource { @GET @RolesAllowed({"admin", "user"}) public ResponseList<Source> getSources() { final ResponseList<Source> sources = new ResponseList<>(); final List<SourceConfig> sourceConfigs = sourceService.getSources(); for (SourceConfig sourceConfig : sourceConfigs) { Source source = fromSourceConfig(sourceConfi... | @Test public void testListSources() throws Exception { ResponseList<SourceResource.SourceDeprecated> sources = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH)).buildGet(), new GenericType<ResponseList<SourceResource.SourceDeprecated>>() {}); assertEquals(sources.getData().size(), newSourceService().getSourc... |
SourceResource { @POST @RolesAllowed({"admin"}) public SourceDeprecated addSource(SourceDeprecated source) { try { SourceConfig newSourceConfig = sourceService.createSource(source.toSourceConfig()); return fromSourceConfig(newSourceConfig); } catch (NamespaceException | ExecutionSetupException e) { throw new ServerErro... | @Test public void testAddSource() throws Exception { SourceResource.SourceDeprecated newSource = new SourceResource.SourceDeprecated(); newSource.setName("Foopy"); newSource.setType("NAS"); NASConf config = new NASConf(); config.path = "/"; newSource.setConfig(config); SourceResource.SourceDeprecated source = expectSuc... |
SourceResource { @PUT @RolesAllowed({"admin"}) @Path("/{id}") public SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source) { SourceConfig sourceConfig; try { sourceConfig = sourceService.updateSource(id, source.toSourceConfig()); return fromSourceConfig(sourceConfig); } catch (NamespaceExce... | @Test public void testUpdateSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy2"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig ... |
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @Inject SourceResource(SourceService sourceService, Sa... | @Test public void testUpdateSourceErrors() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy5"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceC... |
SourceResource { @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") public SourceDeprecated getSource(@PathParam("id") String id) throws NamespaceException { SourceConfig sourceConfig = sourceService.getById(id); return fromSourceConfig(sourceConfig); } @Inject SourceResource(SourceService sourceService, SabotContex... | @Test public void testGetSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy4"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = n... |
SetTableauDefaults extends UpgradeTask { @VisibleForTesting static boolean updateOptionsIfNeeded(Version previousVersion, Supplier<SystemOptionManager> optionManagerSupplier, boolean isOptionManagerOpen) throws Exception { if (Upgrade.UPGRADE_VERSION_ORDERING.compare(previousVersion, VERSION_460) >= 0) { return false; ... | @Test public void testPost460Version() throws Exception { final Version version = new Version("4.6.1", 4, 6, 1, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@Test public void testPost4x0Version() throws Exception { final Version version = new Version("5.2.0", 5, 2... |
SourceResource { @VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<So... | @Test public void testRemovingSensitiveFields() throws Exception { SourceConfig config = new SourceConfig(); config.setName("Foopy"); config.setId(new EntityId("id")); config.setTag("0"); config.setAccelerationGracePeriod(0L); config.setAccelerationRefreshPeriod(0L); APrivateSource priv = new APrivateSource(); priv.pas... |
JobResource extends BaseResourceWithAllocator { @POST @Path("/{id}/cancel") public void cancelJob(@PathParam("id") String id) throws JobException { final String username = securityContext.getUserPrincipal().getName(); try { jobs.cancel(CancelJobRequest.newBuilder() .setUsername(username) .setJobId(JobsProtoUtil.toBuf(n... | @Test public void testCancelJob() throws InterruptedException { JobsService jobs = l(JobsService.class); SqlQuery query = new SqlQuery("select * from sys.version", Collections.emptyList(), SystemUser.SYSTEM_USERNAME); final String id = submitAndWaitUntilSubmitted( JobRequest.newBuilder() .setSqlQuery(query) .setQueryTy... |
UserStatsResource { @GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(... | @Test public void testActiveUserStats() { EditionProvider editionProvider = mock(EditionProvider.class); when(editionProvider.getEdition()).thenReturn("oss-test"); LocalDate now = LocalDate.now(); List<JobSummary> testJobResults = new ArrayList<>(); testJobResults.add(newJob("testuser1", QueryType.ODBC, now)); testJobR... |
ClusterStatsResource { @VisibleForTesting public static Stats getSources(List<SourceConfig> allSources, SabotContext context){ final Stats resource = new Stats(); for (SourceConfig sourceConfig : allSources) { int pdsCount = -1; String type = sourceConfig.getType(); if(type == null && sourceConfig.getLegacySourceTypeEn... | @Test public void testListSources() throws Exception { ClusterStatsResource.ClusterStats stats = expectSuccess(getBuilder(getPublicAPI(3).path(PATH)).buildGet(), ClusterStatsResource.ClusterStats.class); assertNotNull(stats); assertEquals(stats.getSources().size(), newSourceService().getSources().size()); }
@Test publi... |
CatalogResource { @GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); } @Inject CatalogResource(CatalogServiceHelper catalogServiceHelper); @GET ResponseList<? extends ... | @Test public void testListTopLevelCatalog() throws Exception { int topLevelCount = newSourceService().getSources().size() + newNamespaceService().getSpaces().size() + 1; ResponseList<CatalogItem> items = getRootEntities(null); assertEquals(items.getData().size(), topLevelCount); int homeCount = 0; int spaceCount = 0; i... |
UserResource { @GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET ... | @Test public void testGetUserById() throws Exception { final UserService userService = l(UserService.class); com.dremio.service.users.User user1 = userService.getUser("user1"); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(user1.getUID().getId())).buildGet(), User.class); assertEquals(user.g... |
UserResource { @RolesAllowed({"admin"}) @POST public User createUser(User user) throws IOException { final com.dremio.service.users.User userConfig = UserResource.addUser(of(user, Optional.empty()), user.getPassword(), userGroupService, namespaceService); return User.fromUser(userConfig); } @Inject UserResource(UserSe... | @Test public void testCreateUser() throws Exception { UserInfoRequest userInfo = new UserInfoRequest(null, "test_new_user", "test", "new user", "bla@bla.bla", "0", "123some_password", null); User savedUser = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH)) .buildPost(Entity.json(userInfo)), User.class); assert... |
UserResource { @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") public User updateUser(User user, @PathParam("id") String id) throws UserNotFoundException, IOException, DACUnauthorizedException { if (Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("No user id provided"); } final com.dremio.service.u... | @Test public void testUpdateUser() { UserInfoRequest userInfo = new UserInfoRequest(createdUser.getUID().getId(), createdUser.getUserName(), "a new firstName", " a new last name", "new_email@mail.com", createdUser.getVersion(), null, null); User savedUser = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(... |
UserResource { @GET @Path("/by-name/{name}") public User getUserByName(@PathParam("name") String name) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(name)); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityCo... | @Test public void testGetUserByName() throws Exception { final UserService userService = l(UserService.class); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path("by-name").path(createdUser.getUserName())).buildGet(), User.class); assertEquals(user.getId(), createdUser.getUID().getId()); assertEq... |
UserStats { public String getEdition() { return edition; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetEdition() { UserStats.Builder stats = new UserStats.Builder(); stats.setEdition("oss"); String expected = "dremio-oss-" + DremioVersionInfo.getVersion(); assertEquals(expected, stats.build().getEdition()); } |
UserStats { public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetStatsByDate() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusDays(11)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "UI", "testuser1"); statsBuilder.addUserStat(toEpoc... |
UserStats { public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetStatsByWeek() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(3)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpo... |
UserStats { public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetStatsByMonth() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "UI", "testuser1"); statsBuilder.addUserStat(to... |
MediaTypeFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { final UriInfo info = requestContext.getUriInfo(); MultivaluedMap<String, String> parameters = info.getQueryParameters(); String format = parameters.getFirst("format"); if (format... | @Test public void testHeaderChange() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("unit", "test"), request.getAcc... |
ClasspathHealthMonitor implements LiveHealthMonitor { @Override public boolean isHealthy() { logger.debug("Checking jars {}", necessaryJarFoldersSet.size()); for(String jarFolderPath : necessaryJarFoldersSet) { File jarFolder = new File(jarFolderPath); boolean folderAccessible = false; try { folderAccessible = Files.is... | @Test public void testIsHealthy() { assertTrue(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).setExecutable(false); assertFalse(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).setExecutable(true); assertTrue(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).delete(); assertFa... |
JSONJobDataFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (!APPLICATION_JSON_TYPE.equals(responseContext.getMediaType()) || !WebServer.X_DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_SUPPORTED_VALUE ... | @Test public void testJSONGeneratorUntouched() throws IOException { JSONJobDataFilter filter = new JSONJobDataFilter(); ContainerRequestBuilder request = ContainerRequestBuilder.from("http: if (testData.getHeaderKey() != null) { request.header(testData.getHeaderKey(), testData.getHeaderValue()); } ContainerResponse res... |
JSONPrettyPrintFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { UriInfo info = requestContext.getUriInfo(); if (!info.getQueryParameters().containsKey("pretty")) { return; } ObjectWriterInjecto... | @Test public void testJSONGeneratorConfigured() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWrit... |
Doc { void generateDoc(String linkPrefix, PrintStream out) throws JsonMappingException, JsonProcessingException { Set<Class<?>> classes = new TreeSet<>(new Comparator<Class<?>>() { @Override public int compare(Class<?> o1, Class<?> o2) { return o1.getName().compareTo(o2.getName()); } }); classes.addAll(this.classes); f... | @Test public void test() throws Exception { Doc docv2 = new Doc(asList(DatasetVersionResource.class)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); docv2.generateDoc("V2", out); assertTrue(baos.toString(), baos.toString().contains(DatasetVersionResource.class.getNam... |
HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet) { if (hostProcessingRateSet == null || hostProcessingRateSet.isEmpty()) { return new TreeSet<>(); } Table<String, String, BigInteger> hostToColumnToValueTable = ... | @Test public void testComputeRecordProcRateAtPhaseHostLevel() { int major = 1; String hostname1 = "hostname1"; String hostname2 = "hostname2"; HostProcessingRate hpr1 = new HostProcessingRate(major, hostname1, BigInteger.valueOf(5), BigInteger.valueOf(5_000_000_000L), BigInteger.valueOf(1)); HostProcessingRate hpr2 = n... |
HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major, List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops, Table<Integer, Integer, String> majorMinorHostTable) { Table<String, String, BigInteger> hostToColumnToValueTable = HashBasedTable.crea... | @Test public void testComputeRecordProcRateAtPhaseOperatorHostLevel() { int major = 1; int minor1 = 1; int minor2 = 2; int minor3 = 3; String hostname1 = "hostname1"; String hostname2 = "hostname2"; Table<Integer, Integer, String> majorMinorHostTable = HashBasedTable.create(); majorMinorHostTable.put(major, minor1, hos... |
OperatorWrapper { public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); ... | @Test public void testGetMetricsTableHandlesNotRegisteredMetrics() throws IOException { OperatorProfile op = OperatorProfile .newBuilder().addMetric( UserBitShared.MetricValue.newBuilder() .setMetricId(1) .setDoubleValue(200)) .addMetric( UserBitShared.MetricValue.newBuilder() .setMetricId(3) .setDoubleValue(21)) .setO... |
SimpleDurationFormat { static String formatNanos(long durationInNanos) { if (durationInNanos < 1) { return "0s"; } final long days = TimeUnit.NANOSECONDS.toDays(durationInNanos); final long hours = TimeUnit.NANOSECONDS.toHours(durationInNanos) - TimeUnit.DAYS.toHours(TimeUnit.NANOSECONDS.toDays(durationInNanos)); final... | @Test public void testFormatNanos() { assertEquals("123us", SimpleDurationFormat.formatNanos(123456)); assertEquals("456ns", SimpleDurationFormat.formatNanos(456)); assertEquals("825ms", SimpleDurationFormat.formatNanos(825435267)); assertEquals("1.825s", SimpleDurationFormat.formatNanos(1825435267)); assertEquals("30m... |
JobResultToLogEntryConverter implements Function<Job, LoggedQuery> { @Override public LoggedQuery apply(Job job) { final JobInfo info = job.getJobAttempt().getInfo(); final List<String> contextList = info.getContextList(); String outcomeReason = null; switch(job.getJobAttempt().getState()) { case CANCELED: outcomeReaso... | @Test public void testOutcomeReasonCancelled() throws Exception { JobResultToLogEntryConverter converter = new JobResultToLogEntryConverter(); Job job = mock(Job.class); JobAttempt jobAttempt = new JobAttempt(); JobInfo jobInfo = new JobInfo(); JobId jobId = new JobId(); jobId.setId("testId"); final String cancelReason... |
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer... | @Test public void testToBuf() { JobProtobuf.JobAttempt resultJobAttempt = toBuf(jobAttemptProtostuff); assertEquals(resultJobAttempt, jobAttemptProtobuf); JobProtobuf.JobFailureInfo jobFailureInfo = toBuf(jobFailureInfoProtoStuff); assertEquals(jobFailureInfoProtoBuf, jobFailureInfo); JobProtobuf.JobCancellationInfo jo... |
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> T toStuff(Schema<T> protostuffSchema, M protobuf) { T message = protostuffSchema.newMessage(); ProtobufIOUtil.mergeFrom(protobuf.toByteArray(), message, protostuffSchema); return message; } private JobsProtoUtil(); static J... | @Test public void testToStuff() { JobAttempt resultJobAttempt = toStuff(jobAttemptProtobuf); assertEquals(resultJobAttempt, jobAttemptProtostuff); JobFailureInfo jobFailureInfo = toStuff(jobFailureInfoProtoBuf); assertEquals(jobFailureInfoProtoStuff, jobFailureInfo); JobCancellationInfo jobCancellationInfo = toStuff(jo... |
DatasetConfigUpgrade extends UpgradeTask implements LegacyUpgradeTask { @VisibleForTesting byte[] convertFromOldSchema(OldSchema oldSchema) { FlatBufferBuilder builder = new FlatBufferBuilder(); int[] fieldOffsets = new int[oldSchema.fieldsLength()]; for (int i = 0; i < oldSchema.fieldsLength(); i++) { fieldOffsets[i] ... | @Test public void testArrowSchemaConversion() { byte[] schema = Base64.getDecoder().decode(OLD_SCHEMA); try { BatchSchema.deserialize(schema); fail("Should not be able to process old Schema"); } catch (IndexOutOfBoundsException e) { } ByteString schemaBytes = ByteString.copyFrom(schema); DatasetConfigUpgrade datasetCon... |
AttemptsHelper { public static long getLegacyEnqueuedTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final ResourceSchedulingInfo schedulingInfo = jobInfo.getResourceSchedulingInfo(); if (schedulingInfo == null) { return 0; } final Long schedulingStart = sc... | @Test public void testGetEnqueuedTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final Jo... |
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttemp... | @Test public void testGetPlanningTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final Jo... |
AttemptsHelper { public static long getLegacyExecutionTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final JobDetails jobDetails = jobAttempt.getDetails(); if (jobDetails == null) { return 0; } final long startTime = Optional.ofNullable(jobInfo.getStartTim... | @Test public void testGetExecutionTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final J... |
AttemptsHelper { public Long getPendingTime() { return getDuration(State.PENDING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt)... | @Test public void testGetPendingTime() { Preconditions.checkNotNull(attemptsHelper.getPendingTime()); assertTrue(1L == attemptsHelper.getPendingTime()); } |
AttemptsHelper { public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(J... | @Test public void testGetMetadataRetrievalTime() { Preconditions.checkNotNull(attemptsHelper.getMetadataRetrievalTime()); assertTrue(1L == attemptsHelper.getMetadataRetrievalTime()); } |
AttemptsHelper { public Long getEngineStartTime() { return getDuration(State.ENGINE_START); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jo... | @Test public void testGetEngineStartTime() { Preconditions.checkNotNull(attemptsHelper.getEngineStartTime()); assertTrue(1L == attemptsHelper.getEngineStartTime()); } |
AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); ... | @Test public void testGetQueuedTime() { Preconditions.checkNotNull(attemptsHelper.getQueuedTime()); assertTrue(1L == attemptsHelper.getQueuedTime()); } |
AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(J... | @Test public void testGetExecutionPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getExecutionPlanningTime()); assertTrue(1L == attemptsHelper.getExecutionPlanningTime()); } |
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks... | @Test public void testDependencySort() throws Exception { UpgradeTask1 upgradeTask1 = new UpgradeTask1(ImmutableList.of()); UpgradeTask2 upgradeTask2 = new UpgradeTask2(ImmutableList.of(upgradeTask1.getTaskUUID())); UpgradeTask3 upgradeTask3 = new UpgradeTask3(ImmutableList.of(upgradeTask1.getTaskUUID(), upgradeTask2.g... |
AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttemp... | @Test public void testGetStartingTime() { Preconditions.checkNotNull(attemptsHelper.getStartingTime()); assertTrue(1L == attemptsHelper.getStartingTime()); } |
AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt)... | @Test public void testGetRunningTime() { Preconditions.checkNotNull(attemptsHelper.getRunningTime()); assertTrue(1L == attemptsHelper.getRunningTime()); } |
SimpleUserService implements UserService { @Override public Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order, Integer limit) throws IOException { limit = limit == null ? 10000 : limit; if (searchTerm == null || searchTerm.isEmpty()) { return getAllUsers(limit); } final SearchQu... | @Test public void testSearch() throws Exception { try(final LegacyKVStoreProvider kvstore = LegacyKVStoreProviderAdapter.inMemory(DremioTest.CLASSPATH_SCAN_RESULT)) { kvstore.start(); final SimpleUserService userGroupService = new SimpleUserService(() -> kvstore); initUserStore(kvstore, userGroupService); assertEquals(... |
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); } | @Test public void testCombine() { CoordExecRPC.QueryProgressMetrics metrics1 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(100) .build(); CoordExecRPC.QueryProgressMetrics metrics2 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(120) .build(); assertEquals(0, MetricsCombiner.co... |
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile,
Stre... | @Test public void testMergeWithOnlyPlanningProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.COMPLETED) .addStateList(AttemptEvent.newBuilder() .setState(State.COMPL... |
ReconnectingConnection implements Closeable { public <R extends MessageLite, C extends RpcCommand<R, CONNECTION_TYPE>> void runCommand(C cmd) { if (closed.get()) { cmd.connectionFailed(FailureType.CONNECTION, new IOException("Connection has been closed: " + toString())); } ConnectionRunner r = new ConnectionRunner(); c... | @Test public void ensureDirectFailureOnRpcException() { conn().runCommand(Cmd.expectFail()); }
@Test public void ensureSecondSuccess() { conn( r -> r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()), r -> r.connectionSucceeded(newRemoteConnection()) ).runCommand(Cmd.expectSucceed()); }
@Test public... |
RpcException extends IOException { public static <T extends Throwable> void propagateIfPossible(@Nullable RpcException e, Class<T> clazz) throws T { if (e == null) { return; } Throwable cause = e.getCause(); if (!(cause instanceof UserRemoteException)) { return; } UserRemoteException ure = (UserRemoteException) e.getCa... | @Test public void testNullException() throws Exception { RpcException.propagateIfPossible(null, Exception.class); }
@Test public void testNonRemoteException() throws Exception { RpcException e = new RpcException("Test message", new Exception()); RpcException.propagateIfPossible(e, Exception.class); }
@Test public void ... |
KeyPair extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2> KeyPair<K1, K2> of(List<Object> list) { checkArgument(list.size() == 2, "list should be of size 2, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1);... | @Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } KeyPair<String, String> keyPair = KeyPair.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values, keyPair); } |
KeyUtils { public static boolean equals(Object left, Object right) { if (left instanceof byte[] && right instanceof byte[]) { return Arrays.equals((byte[]) left, (byte[]) right); } return Objects.equals(left, right); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys... | @Test public void testEqualsReturnsFalseAllNull() { assertTrue(KeyUtils.equals(null, null)); }
@Test public void testEqualsReturnsFalseLeftNull() { assertFalse(KeyUtils.equals(null, Boolean.TRUE)); }
@Test public void testEqualsReturnsFalseRightNull() { assertFalse(KeyUtils.equals(Boolean.TRUE, null)); }
@Test public v... |
Clean { public static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); final Options options = Options.parse(args); if(options.help) { return; } if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Cleanup should be run on master node"); } Optional<LocalKVStore... | @Test public void runWithOptions() throws Exception { getCurrentDremioDaemon().close(); Clean.go(new String[] {}); Clean.go(new String[] {"-o", "-i", "-c", "-j=30", "-p"}); Clean.go(new String[] {"-h"}); } |
KeyUtils { public static String toString(Object key) { if (null == key) { return null; } return (key instanceof byte[] ? Arrays.toString((byte[]) key) : key.toString()); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); } | @Test public void testToStringNull() { assertNull(KeyUtils.toString(null)); }
@Test public void testToStringBytes() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString(new byte[]{1, 2, 3, 4})); }
@Test public void testToStringString() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString("[1, 2, 3, 4]")); }
@Test public void t... |
AdminCommandRunner { static void runCommand(String commandName, Class<?> command, String[] commandArgs) throws Exception { final Method mainMethod = command.getMethod("main", String[].class); Preconditions.checkState(Modifier.isStatic(mainMethod.getModifiers()) && Modifier.isPublic(mainMethod.getModifiers()), "#main(St... | @Test public void runCommand() throws Exception { assertFalse(TestCommand.invokedCorrectly); AdminCommandRunner.runCommand("test-command", TestCommand.class, new String[]{"arg0", "arg1"}); assertTrue(TestCommand.invokedCorrectly); } |
KeyUtils { public static int hash(Object... keys) { if (null == keys) { return 0; } int result = 1; for (Object key : keys) { result = 31 * result + hashCode(key); } return result; } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key... | @Test public void testHashBytes() { assertEquals(918073283, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6})); }
@Test public void testHashBytesAndString() { assertEquals(214780274, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string")); }
@Test public void testHashBytesAndStringAndNull() { assertEquals(-193174609... |
KeyTriple extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2, K3> KeyTriple<K1, K2, K3> of(List<Object> list) { checkArgument(list.size() == 3, "list should be of size 3, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) ... | @Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } final KeyTriple<String, String, String> keyPair = KeyTriple.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values.get(2), keyPair.... |
ReIndexer implements ReplayHandler { @Override public void put(String tableName, byte[] key, byte[] value) { if (!isIndexed(tableName)) { logger.trace("Ignoring put: {} on table '{}'", key, tableName); return; } final KVStoreTuple<?> keyTuple = keyTuple(tableName, key); final Document document = toDoc(tableName, keyTup... | @Test public void add() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] added = {false}; doAnswer(invocation -> { added[0] = true; return null; }).when(index).update(any(Term.class), any(Document.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reInde... |
ExportProfiles { private static void exportOffline(ExportProfilesOptions options, DACConfig dacConfig) throws Exception { Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No database found. Profiles are not export... | @Test public void testOffline() throws Exception { final String tmpPath = folder0.newFolder("testOffline").getAbsolutePath(); final LegacyKVStoreProvider localKVStoreProvider = l(LegacyKVStoreProvider.class); final LegacyKVStoreProvider spy = spy(localKVStoreProvider); Mockito.doNothing().when(spy).close(); final Strin... |
ReIndexer implements ReplayHandler { @Override public void delete(String tableName, byte[] key) { if (!isIndexed(tableName)) { logger.trace("Ignoring delete: {} on table '{}'", key, tableName); return; } indexManager.getIndex(tableName) .deleteDocuments(keyAsTerm(keyTuple(tableName, key))); metrics(tableName).deletes++... | @Test public void delete() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] deleted = {false}; doAnswer(invocation -> { deleted[0] = true; return null; }).when(index).deleteDocuments(any(Term.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.d... |
TracingKVStore implements KVStore<K, V> { @Override public Document<K, V> get(K key, GetOption... options) { return trace("get", () -> delegate.get(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate... | @Test public void testTypedReturnMethod() { setupLegitParentSpan(); when(delegate.get("myKey")).thenReturn(new TestDocument("myKey","yourValue")); Document<String, String> ret = underTest.get("myKey"); assertEquals("yourValue", ret.getValue()); assertChildSpanMethod("get"); } |
TracingKVStore implements KVStore<K, V> { @Override public void delete(K key, DeleteOption... options) { trace("delete", () -> delegate.delete(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @O... | @Test public void testVoidReturnMethod() { setupLegitParentSpan(); underTest.delete("byebye"); verify(delegate).delete("byebye"); assertChildSpanMethod("delete"); } |
KVStoreOptionUtility { public static void validateOptions(KVStore.KVStoreOption... options) { if (null == options || options.length <= 1) { return; } boolean foundVersion = false; boolean foundCreate = false; for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { if (foundCreate) { thr... | @Test public void testValidateOptionsNull() { KVStoreOptionUtility.validateOptions((KVStore.PutOption[]) null); }
@Test public void testValidateOptionsEmpty() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{}); }
@Test public void testValidateOptionsSingleCreate() { KVStoreOptionUtility.validateOptions(n... |
ResetCatalogSearch { static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); parse(args); if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Reset catalog search should be run on master node"); } final Optional<LocalKVStoreProvider> providerOptional = CmdUtil... | @Test public void testResetCatalogSearchCommand() throws Exception { getCurrentDremioDaemon().close(); ResetCatalogSearch.go(new String[] {}); final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(getDACConfig().getConfig()); if (!providerOptional.isPresent()) { throw new Exception("No KVS... |
KVStoreOptionUtility { public static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options) { if (null == options || options.length == 0) { return; } for (KVStore.KVStoreOption option : options) { if (option instanceof IndexPutOption) { throw new IllegalArgumentException("IndexPutOption not supported."); }... | @Test public void testIndexPutOptionNotSupportedNull() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(); }
@Test public void testIndexPutOptionNotSupportedEmpty() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{}); }
@Test public void testIndexPutOptionNotSupportedSingleCreate() { KVSto... |
SystemStoragePluginInitializer implements Initializer<Void> { @VisibleForTesting void createOrUpdateSystemSource(final CatalogService catalogService, final NamespaceService ns, final SourceConfig config) throws Exception { try { config.setAllowCrossSourceSelection(true); final boolean isCreated = catalogService.createS... | @Test public void refreshSystemPluginsTest() throws Exception { SystemStoragePluginInitializer systemInitializer = new SystemStoragePluginInitializer(); SourceConfig c = new SourceConfig(); InternalFileConf conf = new InternalFileConf(); conf.connection = "classpath: conf.path = "/"; conf.isInternal = false; conf.prope... |
KVStoreOptionUtility { public static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options) { validateOptions(options); if (null == options || options.length == 0) { return Optional.empty(); } for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { return... | @Test public void testGetCreateOrVersionOptionNull() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(); assertFalse(ret.isPresent()); }
@Test public void testGetCreateOrVersionOptionEmpty() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(ne... |
DateUtils { public static long getStartOfLastMonth() { LocalDate now = LocalDate.now(); LocalDate targetDate = now.minusDays(now.getDayOfMonth() - 1).minusMonths(1); Instant instant = targetDate.atStartOfDay().toInstant(ZoneOffset.UTC); return instant.toEpochMilli(); } static long getStartOfLastMonth(); static LocalDa... | @Test public void testGetStartOfLastMonth() { LocalDate dateLastMonth = LocalDate.now().minusMonths(1); long startOfLastMonth = DateUtils.getStartOfLastMonth(); LocalDate dateStartOfLastMonth = DateUtils.fromEpochMillis(startOfLastMonth); assertEquals(dateLastMonth.getMonthValue(), dateStartOfLastMonth.getMonthValue())... |
KVStoreOptionUtility { public static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options) { if (null == options) { return null; } return Arrays .stream(options) .filter(option -> !(option instanceof IndexPutOption)) .toArray(KVStore.PutOption[]::new); } static void validateOptions(KVStore.KVStoreOpti... | @Test public void testRemoveIndexPutOption() { testRemoveIndexPutOptions( new KVStore.PutOption[]{indexPutOption}, new KVStore.PutOption[]{}); } |
LegacyProtobufSerializer extends ProtobufSerializer<T> { public static <M extends Message> M parseFrom(Parser<M> parser, ByteString bytes) throws InvalidProtocolBufferException { return rewriteProtostuff(parser.parseFrom(bytes)); } LegacyProtobufSerializer(Class<T> clazz, Parser<T> parser); @Override T revert(byte[] by... | @Test public void testParse() throws InvalidProtocolBufferException { final UnknownFieldSet term1 = UnknownFieldSet.newBuilder() .addField(SearchQuery.Term.FIELD_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("foo")).build()) .addField(SearchQuery.Term.VALUE_FIELD_NUMBER, Field.newBuilder()... |
ReflectionManager implements Runnable { @VisibleForTesting void handleGoal(ReflectionGoal goal) { final ReflectionEntry entry = reflectionStore.get(goal.getId()); if (entry == null) { if (goal.getState() == ReflectionGoalState.ENABLED) { reflectionStore.save(create(goal)); } } else if (reflectionGoalChecker.isEqual(goa... | @Test public void handleGoalWithNoEntry(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String reflectionGoalName = "name"; String dataSetId = "dataSetId"; String tag = "rgTag"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setI... |
ReflectionManager implements Runnable { @VisibleForTesting void sync(){ long lastWakeupTime = System.currentTimeMillis(); final long previousLastWakeupTime = lastWakeupTime - WAKEUP_OVERLAP_MS; final long deletionGracePeriod = optionManager.getOption(REFLECTION_DELETION_GRACE_PERIOD) * 1000; final long deletionThreshol... | @Test public void testSyncDoesNotUpdateReflectionWhenOnlyBoostIsToggle(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String reflectionGoalName = "name"; String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoa... |
DateUtils { public static LocalDate getLastSundayDate(final LocalDate dateWithinWeek) { int dayOfWeek = dateWithinWeek.getDayOfWeek().getValue(); dayOfWeek = (dayOfWeek == 7) ? 0 : dayOfWeek; return dateWithinWeek.minusDays(dayOfWeek); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final Local... | @Test public void testGetLastSundayDate() { LocalDate testDate1 = LocalDate.parse("2020-03-29"); LocalDate date1LastSunday = DateUtils.getLastSundayDate(testDate1); assertEquals(testDate1, date1LastSunday); LocalDate testDate2 = LocalDate.parse("2020-03-28"); LocalDate date2LastSunday = DateUtils.getLastSundayDate(test... |
DependencyGraph { public synchronized void loadFromStore() { for (Map.Entry<ReflectionId, ReflectionDependencies> entry : dependenciesStore.getAll()) { final List<ReflectionDependencyEntry> dependencies = entry.getValue().getEntryList(); if (dependencies == null || dependencies.isEmpty()) { continue; } try { setPredece... | @Test public void testLoadFromStore() throws Exception { final DependenciesStore dependenciesStore = Mockito.mock(DependenciesStore.class); final DependencyGraph graph = new DependencyGraph(dependenciesStore); final Multimap<String, String> dependencyMap = MultimapBuilder.hashKeys().arrayListValues().build(); dependenc... |
ReflectionGoalChecker { public static boolean checkGoal(ReflectionGoal goal, Materialization materialization) { return Instance.isEqual(goal, materialization.getReflectionGoalVersion()); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, Reflectio... | @Test public void testMatchesTag() { final String testTag = "testTag"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag(testTag); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMatchesVersion() { final String ... |
ReflectionGoalChecker { public boolean checkHash(ReflectionGoal goal, ReflectionEntry entry){ if(null == entry.getReflectionGoalHash()){ return false; } return entry.getReflectionGoalHash().equals(calculateReflectionGoalVersion(goal)); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal);... | @Test public void testCheckHashAgainstHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry() .setReflectionGoalHash(new ReflectionGoalHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); assertTrue(ReflectionGoalChecker.Instance.checkHash(goal, entry)); }... |
ReflectionGoalChecker { public ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal){ HasherOutput hasherOutput = new HasherOutput(); Output blackListedOutput = reflectionGoalMaterializationBlackLister.apply(hasherOutput); try { reflectionGoal.writeTo(blackListedOutput, reflectionGoal); retur... | @Test public void testHashingEmptyGoal(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionGoalHash actual = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal); assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", actual.getHash()); }
@Test public void testHashingEmptyI... |
DateUtils { public static LocalDate getMonthStartDate(final LocalDate dateWithinMonth) { int dayOfMonth = dateWithinMonth.getDayOfMonth(); return dateWithinMonth.minusDays((dayOfMonth - 1)); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMon... | @Test public void testGetMonthStartDate() { LocalDate testDate1 = LocalDate.parse("2020-03-01"); LocalDate monthStartDate = DateUtils.getMonthStartDate(testDate1); assertEquals(testDate1, monthStartDate); LocalDate testDate2 = LocalDate.parse("2020-03-31"); LocalDate date2MonthStartDate = DateUtils.getMonthStartDate(te... |
OptionList extends ArrayList<OptionValue> { public void mergeIfNotPresent(OptionList list) { final Set<OptionValue> options = Sets.newTreeSet(this); for (OptionValue optionValue : list) { if (options.add(optionValue)) { this.add(optionValue); } } } void merge(OptionList list); void mergeIfNotPresent(OptionList list); ... | @Test public void testMergeOptionLists() { final OptionValue optionValue0 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", false); final OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option1", 2); final OptionValue optionValue2 = OptionValue.createLong(... |
BoundCommandPool implements CommandPool { @Override public <V> CompletableFuture<V> submit(Priority priority, String descriptor, Command<V> command, boolean runInSameThread) { final long time = System.currentTimeMillis(); final CommandWrapper<V> wrapper = new CommandWrapper<>(priority, descriptor, time, command); logge... | @Test public void testSamePrioritySuppliers() throws Exception { final CommandPool pool = newTestCommandPool(); final BlockingCommand blocking = new BlockingCommand(); pool.submit(CommandPool.Priority.HIGH, "test", blocking, false); Future<Integer> future1 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis)... |
PartitionChunkId implements Comparable<PartitionChunkId> { @JsonCreator public static PartitionChunkId of(String partitionChunkId) { final String[] ids = partitionChunkId.split(DELIMITER, 3); Preconditions.checkArgument(ids.length == 3 && !ids[0].isEmpty() && !ids[1].isEmpty() && !ids[2].isEmpty(), "Invalid dataset spl... | @Test public void testInvalidIdFromString() throws Exception { try { PartitionChunkId split = PartitionChunkId.of("ds1_1"); fail("ds1_1 is an invalid dataset split id"); } catch (IllegalArgumentException e) { } try { PartitionChunkId split = PartitionChunkId.of("ds2_2_"); fail("ds2_2_ is an invalid dataset split id"); ... |
FileFormat { public String toTableOptions() throws IllegalArgumentException { final StringBuilder stringBuilder = new StringBuilder(); switch (getFileType()) { case TEXT: case CSV: case TSV: case PSV: final TextFileConfig textFileConfig = (TextFileConfig)this; stringBuilder.append("type => 'text', "); stringBuilder.app... | @Test public void testDefaultTextFileFormatOptions() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'text'", tableOptions); assertContains("fieldDelimiter => ','", tableOptions); assertContains("comment => '#'", tableOption... |
DateUtils { public static LocalDate fromEpochMillis(final long epochMillis) { return Instant.ofEpochMilli(epochMillis).atZone(ZoneOffset.UTC).toLocalDate(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWi... | @Test public void testFromEpochMillis() { LocalDate extractedDate = DateUtils.fromEpochMillis(System.currentTimeMillis()); assertEquals(LocalDate.now(), extractedDate); } |
DatasetStateMutator { public TransformResult apply(String oldCol, String newCol, ExpressionBase newExp, boolean dropSourceColumn) { return apply(oldCol, newCol, newExp.wrap(), dropSourceColumn); } DatasetStateMutator(String username, VirtualDatasetState virtualDatasetState, boolean preview); void setSql(QueryMetadata m... | @Test public void testMutatorApplyNoDropNonPreview() { boolean preview = false; TransformResult result = mutator(preview).apply("foo", "foo2", newValue, false); assertEquals(newHashSet("foo2"), result.getAddedColumns()); assertEquals(newHashSet(), result.getModifiedColumns()); assertEquals(newHashSet(), result.getRemov... |
PathUtils { public static final String join(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part:parts) { Preconditions.checkNotNull(part, "parts cannot contain null"); if (!Strings.isNullOrEmpty(part)) { sb.append(part).append("/"); } } if (sb.length() > 0) { sb.deleteCharAt(sb... | @Test(expected = NullPointerException.class) public void testNullSegmentThrowsNPE() { PathUtils.join("", null, ""); }
@Test public void testJoinPreservesAbsoluteOrRelativePaths() { final String actual = PathUtils.join("/a", "/b", "/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, act... |
PathUtils { public static final String normalize(final String path) { if (Strings.isNullOrEmpty(Preconditions.checkNotNull(path))) { return path; } final StringBuilder builder = new StringBuilder(); char last = path.charAt(0); builder.append(last); for (int i=1; i<path.length(); i++) { char cur = path.charAt(i); if (la... | @Test public void testNormalizeRemovesRedundantForwardSlashes() { final String actual = PathUtils.normalize("/a/b/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.normalize(" final String expected2 = "/a/b/c"; Assert.assertEquals("invalid pat... |
QueueProcessor implements AutoCloseable { public QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer) { this.name = name; this.lockSupplier = lockSupplier; this.consumer = consumer; this.queue = new LinkedBlockingQueue<>(); this.workerThread = null; this.isClosed = false; this.com... | @Test public void testQueueProcessor() throws Exception { Pointer<Long> counter = new Pointer<>(0L); final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); Lock readLock = rwlock.readLock(); Lock writeLock = rwlock.writeLock(); QueueProcessor<Long> qp = new QueueProcessor<>("queue-processor", () -> new Aut... |
JmxConfigurator extends ReporterConfigurator { @Override public void configureAndStart(String name, MetricRegistry registry, MetricFilter filter) { reporter = JmxReporter.forRegistry(registry).convertRatesTo(rateUnit).convertDurationsTo(durationUnit).filter(filter).build(); reporter.start(); } @JsonCreator JmxConfigur... | @Test public void testConfigureAndStart() throws IOException, InterruptedException, MalformedObjectNameException { final MetricRegistry metrics = new MetricRegistry(); metrics.counter(NAME, () -> { Counter counter = new Counter(); counter.inc(1234); return counter; }); final JmxConfigurator configurator = new JmxConfig... |
LocalSchedulerService implements SchedulerService { @Override public void close() throws Exception { LOGGER.info("Stopping SchedulerService"); AutoCloseables.close(AutoCloseables.iter(executorService), taskLeaderElectionServiceMap.values()); LOGGER.info("Stopped SchedulerService"); } LocalSchedulerService(int corePoolS... | @Test public void close() throws Exception { final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); final LocalSchedulerService service = new LocalSchedulerService(executorService, null, null, false); service.close(); verify(executorService).close(); } |
LocalSchedulerService implements SchedulerService { @VisibleForTesting public CloseableSchedulerThreadPool getExecutorService() { return executorService; } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProv... | @Test public void newThread() { LocalSchedulerService service = new LocalSchedulerService(1); final Runnable runnable = mock(Runnable.class); final Thread thread = service.getExecutorService().getThreadFactory().newThread(runnable); assertTrue("thread should be a daemon thread", thread.isDaemon()); assertTrue("thread n... |
LocalSchedulerService implements SchedulerService { @Override public Cancellable schedule(Schedule schedule, Runnable task) { if (!assumeTaskLeadership) { return plainSchedule(schedule, task); } if (!schedule.isDistributedSingleton()) { return plainSchedule(schedule, task); } final TaskLeaderElection taskLeaderElection... | @Test public void schedule() throws Exception { final List<MockScheduledFuture<?>> futures = Lists.newArrayList(); final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); doAnswer(new Answer<ScheduledFuture<Object>>() { @Override public ScheduledFuture<Object> answer(InvocationOnM... |
IncludesExcludesFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (includes.isEmpty() || matches(name, includes)) { return allowedViaExcludes(name); } return false; } IncludesExcludesFilter(List<String> includes, List<String> excludes); @Override boolean matches(String n... | @Test public void onlyExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList("a.*")); assertFalse(f.matches("alpha", null)); assertTrue(f.matches("beta", null)); }
@Test public void onlyInclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arra... |
MutableVarcharVector extends BaseVariableWidthVector { @Override public void close() { this.clear(); } MutableVarcharVector(String name, BufferAllocator allocator, double compactionThreshold); MutableVarcharVector(String name, FieldType fieldType, BufferAllocator allocator, double compactionThreshold); final void setC... | @Test public void TestInterleavedMidToSmall() { LinkedList<String> l1 = GetRandomStringList(TOTAL_STRINGS, midAvgSize); LinkedList<String> l2 = GetRandomStringList(TOTAL_STRINGS, smallAvgSize); final double threshold = 1.0D; System.out.println("TestInterleavedMidToSmall: threshold: " + threshold + " (only forcecompact)... |
UserRPCServer extends BasicServer<RpcType, UserRPCServer.UserClientConnectionImpl> { @Override protected Response handle(UserClientConnectionImpl connection, int rpcType, byte[] pBody, ByteBuf dBody) throws RpcException { throw new IllegalStateException("UserRPCServer#handle must not be invoked without ResponseSender")... | @Test public void testHandlePassesNoopTracesByDefault() throws RpcException { setup(false); server.handle(connection, GET_CATALOGS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_CATALOGS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().si... |
QueriesClerk { QueriesClerk(final WorkloadTicketDepot workloadTicketDepot) { this.workloadTicketDepot = workloadTicketDepot; } QueriesClerk(final WorkloadTicketDepot workloadTicketDepot); void buildAndStartQuery(final PlanFragmentFull firstFragment, final SchedulingInfo schedulingInfo,
... | @Test public void testQueriesClerk() throws Exception{ WorkloadTicketDepot ticketDepot = new WorkloadTicketDepot(mockedRootAlloc, mock(SabotConfig.class), DUMMY_GROUP_MANAGER); QueriesClerk clerk = makeClerk(ticketDepot); assertLivePhasesCount(clerk, 0); int baseNumAllocators = getNumAllocators(); UserBitShared.QueryId... |
QueriesClerk { Collection<FragmentTicket> getFragmentTickets(QueryId queryId) { List<FragmentTicket> fragmentTickets = new ArrayList<>(); for (WorkloadTicket workloadTicket : getWorkloadTickets()) { QueryTicket queryTicket = workloadTicket.getQueryTicket(queryId); if (queryTicket != null) { for (PhaseTicket phaseTicket... | @Test public void testGetFragmentTickets() throws Exception { WorkloadTicketDepot ticketDepot = new WorkloadTicketDepot(mockedRootAlloc, mock(SabotConfig.class), DUMMY_GROUP_MANAGER); QueriesClerk clerk = makeClerk(ticketDepot); UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder().setPart1(12).setPart2(23... |
ThreadsStatsCollector extends Thread implements AutoCloseable { public Integer getCpuTrailingAverage(long id, int seconds) { return cpuStat.getTrailingAverage(id, seconds); } ThreadsStatsCollector(Set<Long> slicingThreadIds); ThreadsStatsCollector(long collectionIntervalInMilliSeconds, Set<Long> slicingThreadIds); @Ov... | @Test public void testOldThreadsArePruned() throws InterruptedException { Thread t = new Thread() { public void run () { try { sleep(400l); } catch (InterruptedException e) { } } }; Thread t1 = new Thread() { public void run () { try { sleep(400l); } catch (InterruptedException e) { } } }; t.start(); t1.start(); Thread... |
VectorizedHashJoinOperator implements DualInputOperator { @VisibleForTesting void sendRuntimeFilterToProbeScan(RuntimeFilter filter, Optional<BloomFilter> partitionColFilter) { logger.debug("Sending join runtime filter to probe scan {}:{}, Filter {}", filter.getProbeScanOperatorId(), filter.getProbeScanMajorFragmentId(... | @Test public void testSendRuntimeFilterToProbeScan() { int probeScanId = 2; int probeOpId = 131074; int buildMajorFragment = 1; int buildMinorFragment = 2; int buildOpId = 65541; QueryId queryId = QueryId.newBuilder().build(); try (ArrowBuf recvBuffer = bfTestAllocator.buffer(64)) { recvBuffer.setBytes(0, new byte[64])... |
MatchBitSet implements AutoCloseable { public void set(final int index) { final int wordNum = index >>> LONG_TO_BITS_SHIFT; final int bit = index & BIT_OFFSET_MUSK; final long bitMask = 1L << bit; final long wordAddr = bufferAddr + wordNum * BYTES_PER_WORD; PlatformDependent.putLong(wordAddr, PlatformDependent.getLong(... | @Test public void randomBits() throws Exception { final int count = 8*1024*1024; BitSet bitSet = new BitSet(count); final Random rand = new Random(); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i ++) { int val = rand.nextInt(10); if (val > 3) { bitSet.set(i); matchBitS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.