focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void addPartitions(String dbName, String tableName, List<HivePartitionWithStats> partitions) { try { metastore.addPartitions(dbName, tableName, partitions); } catch (Exception e) { LOG.warn("Failed to execute metastore.addPartitions", e); throw e; } fin...
@Test public void testAddPartitionFailed() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); HivePartition hivePartition = HivePartition.builder() // Unsupported type ...
@ScalarOperator(BETWEEN) @SqlType(StandardTypes.BOOLEAN) public static boolean between(@SqlType(StandardTypes.BOOLEAN) boolean value, @SqlType(StandardTypes.BOOLEAN) boolean min, @SqlType(StandardTypes.BOOLEAN) boolean max) { return (value && max) || (!value && !min); }
@Test public void testBetween() { assertFunction("true BETWEEN true AND true", BOOLEAN, true); assertFunction("true BETWEEN true AND false", BOOLEAN, false); assertFunction("true BETWEEN false AND true", BOOLEAN, true); assertFunction("true BETWEEN false AND false", BOOLEAN, fals...
static boolean acknowledge(MessageIdAdv msgId, boolean individual) { if (!isBatch(msgId)) { return true; } final BitSet ackSet = msgId.getAckSet(); if (ackSet == null) { // The internal MessageId implementation should never reach here. If users have implemented th...
@Test public void testAcknowledgeIndividualConcurrently() throws InterruptedException { ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pulsar-consumer-%d").build(); @Cleanup("shutdown") ExecutorService executorService = Executors.newCachedThreadPool(threadFactory); ...
@Override public Optional<WorkItem> getWorkItem() throws IOException { List<String> workItemTypes = ImmutableList.of( WORK_ITEM_TYPE_MAP_TASK, WORK_ITEM_TYPE_SEQ_MAP_TASK, WORK_ITEM_TYPE_REMOTE_SOURCE_TASK); // All remote sources require the "remote_source" capabili...
@Test public void testCloudServiceCallNoWorkItem() throws Exception { MockLowLevelHttpResponse response = generateMockResponse(); MockLowLevelHttpRequest request = new MockLowLevelHttpRequest().setResponse(response); MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequ...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_exception_when_executing_unknown_bound_statement() { // Given String queries = "@bind[select_users]='jdoe'"; // When final InterpreterResult actual = interpreter.interpret(queries, intrContext); // Then assertEquals(Code.ERROR, actual.code()); assertEquals("The statemen...
@Override public void addConfiguration(String configName, C configuration) { if (configName.equals(DEFAULT_CONFIG)) { throw new IllegalArgumentException( "You cannot use 'default' as a configuration name as it is preserved for default configuration"); } this.confi...
@Test public void shouldNotAllowToOverwriteDefaultConfiguration() { TestRegistry testRegistry = new TestRegistry(); assertThatThrownBy(() -> testRegistry.addConfiguration("default", "test")) .isInstanceOf(IllegalArgumentException.class); }
@VisibleForTesting protected void copyFromHost(MapHost host) throws IOException { // reset retryStartTime for a new host retryStartTime = 0; // Get completed maps on 'host' List<TaskAttemptID> maps = scheduler.getMapsForHost(host); // Sanity check to catch hosts with only 'OBSOLETE' maps, ...
@Test public void testCopyFromHostConnectionRejected() throws Exception { when(connection.getResponseCode()) .thenReturn(Fetcher.TOO_MANY_REQ_STATUS_CODE); Fetcher<Text, Text> fetcher = new FakeFetcher<>(job, id, ss, mm, r, metrics, except, key, connection); fetcher.copyFromHost(host); ...
public String getId(String name) { // Use the id directly if it is unique and the length is less than max if (name.length() <= maxHashLength && usedIds.add(name)) { return name; } // Pick the last bytes of hashcode and use hex format final String hexString = Integer.toHexString(name.hashCode(...
@Test public void testSameNames() { final HashIdGenerator idGenerator = new HashIdGenerator(); String id1 = idGenerator.getId(Count.perKey().getName()); String id2 = idGenerator.getId(Count.perKey().getName()); Assert.assertNotEquals(id1, id2); }
@Override public TableBuilder buildTable(TableIdentifier identifier, Schema schema) { return new ViewAwareTableBuilder(identifier, schema); }
@Test public void testCreateTableCustomSortOrder() { TableIdentifier tableIdent = TableIdentifier.of("db", "ns1", "ns2", "tbl"); SortOrder order = SortOrder.builderFor(SCHEMA).asc("id", NULLS_FIRST).build(); Table table = catalog .buildTable(tableIdent, SCHEMA) .withPartiti...
protected void createNewWorkerId() { type.assertFull(); if (workerId != null) { String err = "Incorrect usage of createNewWorkerId(), current workerId is " + workerId + ", expecting null"; LOG.error(err); throw new AssertionError(err); } synchronized ...
@Test public void testCreateNewWorkerId() throws Exception { final String topoId = "test_topology"; final int supervisorPort = 6628; final int port = 8080; LocalAssignment la = new LocalAssignment(); la.set_topology_id(topoId); Map<String, Object> superConf = new Has...
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious) { if (!type.isOrderable()) { throw new IllegalStateException("Type is not orderable: " + type); } requireNonNull(value, "value is null"); if (type.equals(BIGINT) || type instance...
@Test public void testPreviousValueForTimestamp() { long minValue = Long.MIN_VALUE; long maxValue = Long.MAX_VALUE; assertThat(getAdjacentValue(TIMESTAMP, minValue, true)) .isEqualTo(Optional.empty()); assertThat(getAdjacentValue(TIMESTAMP, minValue + 1, true)) ...
@InterfaceAudience.Private public static String bashQuote(String arg) { StringBuilder buffer = new StringBuilder(arg.length() + 2); buffer.append('\'') .append(arg.replace("'", "'\\''")) .append('\''); return buffer.toString(); }
@Test public void testBashQuote() { assertEquals("'foobar'", Shell.bashQuote("foobar")); assertEquals("'foo'\\''bar'", Shell.bashQuote("foo'bar")); assertEquals("''\\''foo'\\''bar'\\'''", Shell.bashQuote("'foo'bar'")); }
@Override public String buildRemoteURL(String baseRepositoryURL, String referencePath) { // https://gitlab.com/api/v4/projects/35980862/repository/files/folder%2Fsubfolder%2Ffilename/raw?ref=branch // https://gitlab.com/api/v4/projects/35980862/repository/files String rootURL = baseRepositoryURL.s...
@Test void testBuildRemoteURL() { GitLabReferenceURLBuilder builder = new GitLabReferenceURLBuilder(); assertEquals("https://gitlab.com/api/v4/projects/35980862/repository/files/pastry%2Fschema-ref.yml/raw?ref=main", builder.buildRemoteURL(BASE_URL, "schema-ref.yml")); assertEquals("ht...
public static void validate( FederationPolicyInitializationContext policyContext, String myType) throws FederationPolicyInitializationException { if (myType == null) { throw new FederationPolicyInitializationException( "The myType parameter" + " should not be null."); } if (pol...
@Test(expected = FederationPolicyInitializationException.class) public void nullConf() throws Exception { context.setSubClusterPolicyConfiguration(null); FederationPolicyInitializationContextValidator.validate(context, MockPolicyManager.class.getCanonicalName()); }
@Override public Long incrementCounter(String name) { return incrementCounter(name, 1L); }
@Test @org.junit.Ignore("flaky test HIVE-23692") public void testFileReporting() throws Exception { int runs = 5; String counterName = "count2"; // on the first write the metrics writer should initialize stuff MetricsFactory.getInstance().incrementCounter(counterName); sleep(5 * REPORT_INTERVA...
@Override public Set<String> names() { if (isEmpty()) { return Collections.emptySet(); } Set<String> names = new LinkedHashSet<String>(size()); for (int i = 0; i < nameValuePairs.length; i += 2) { names.add(nameValuePairs[i].toString()); } retu...
@Test public void names() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, CONNECTION, CLOSE); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); Set<String> names = headers.names(); as...
public static Transaction read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return Transaction.read(payload, ProtocolVersion.CURRENT.intValue()); }
@Test public void parseTransactionWithHugeDeclaredOutputsSize() { Transaction tx = new HugeDeclaredSizeTransaction(false, true, false); byte[] serializedTx = tx.serialize(); try { Transaction.read(ByteBuffer.wrap(serializedTx)); fail("We expect BufferUnderflowExceptio...
public static int bytesToInt(byte[] ary) { return (ary[3] & 0xFF) | ((ary[2] << 8) & 0xFF00) | ((ary[1] << 16) & 0xFF0000) | ((ary[0] << 24) & 0xFF000000); }
@Test public void bytesToInt() { int i = CodecUtils.bytesToInt(new byte[] { 0, 0, 0, 0 }); Assert.assertEquals(0, i); i = CodecUtils.bytesToInt(new byte[] { 0, 0, 3, -24 }); Assert.assertEquals(1000, i); int s = CodecUtils.bytesToInt(new byte[] { 1, 0, 0, 2 }); Ass...
@VisibleForTesting static void instantiateHeapMemoryMetrics(final MetricGroup metricGroup) { instantiateMemoryUsageMetrics( metricGroup, () -> ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()); }
@Test void testHeapMetricUsageNotStatic() throws Exception { final InterceptingOperatorMetricGroup heapMetrics = new InterceptingOperatorMetricGroup(); MetricUtils.instantiateHeapMemoryMetrics(heapMetrics); @SuppressWarnings("unchecked") final Gauge<Long> used = (Gauge<Long>) heapM...
@Private @VisibleForTesting static void checkResourceRequestAgainstAvailableResource(Resource reqResource, Resource availableResource) throws InvalidResourceRequestException { for (int i = 0; i < ResourceUtils.getNumberOfCountableResourceTypes(); i++) { final ResourceInformation requestedRI = ...
@Test public void testCustomResourceRequestedUnitIsSameAsAvailableUnit2() throws InvalidResourceRequestException { Resource requestedResource = ResourceTypesTestHelper.newResource(1, 1, ImmutableMap.of("custom-resource-1", "110M")); Resource availableResource = ResourceTypesTestHelper.n...
public static String getRelativePath(Path sourceRootPath, Path childPath) { String childPathString = childPath.toUri().getPath(); String sourceRootPathString = sourceRootPath.toUri().getPath(); return sourceRootPathString.equals("/") ? childPathString : childPathString.substring(sourceRootPathString...
@Test public void testGetRelativePath() { Path root = new Path("/tmp/abc"); Path child = new Path("/tmp/abc/xyz/file"); assertThat(DistCpUtils.getRelativePath(root, child)).isEqualTo("/xyz/file"); }
static RequestConfigElement parse(String property, String key, Object value) throws RequestConfigKeyParsingException { RequestConfigKeyParsingErrorListener errorListener = new RequestConfigKeyParsingErrorListener(); ANTLRInputStream input = new ANTLRInputStream(key); RequestConfigKeyLexer lexer = new Reques...
@Test(expectedExceptions = {RequestConfigKeyParsingException.class}) public void testParsingInvalidValue() throws RequestConfigKeyParsingException { RequestConfigElement.parse("timeoutMs", "*.*/*.*", true); }
protected String buildSearch(Map<String, MutableInt> vendor, Map<String, MutableInt> product, Set<String> vendorWeighting, Set<String> productWeightings) { final StringBuilder sb = new StringBuilder(); if (!appendWeightedSearch(sb, Fields.PRODUCT, product, productWeightings)) { ...
@Test public void testBuildSearch() { Map<String, MutableInt> vendor = new HashMap<>(); Map<String, MutableInt> product = new HashMap<>(); vendor.put("apache software foundation", new MutableInt(1)); product.put("lucene index", new MutableInt(1)); Set<String> vendorWeighting ...
protected static void validate(final String name) { if (name.isEmpty()) throw new TopologyException("Name is illegal, it can't be empty"); if (name.equals(".") || name.equals("..")) throw new TopologyException("Name cannot be \".\" or \"..\""); if (name.length() > MAX_NAM...
@Test public void shouldThrowExceptionOnInvalidTopicNames() { final char[] longString = new char[250]; Arrays.fill(longString, 'a'); final String[] invalidNames = {"", "foo bar", "..", "foo:bar", "foo=bar", ".", new String(longString)}; for (final String name : invalidNames) { ...
@Override public void update(Service service, ServiceMetadata metadata) throws NacosException { if (!ServiceManager.getInstance().containSingleton(service)) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.SERVICE_NOT_EXIST, String.format("service %s not ...
@Test void testUpdate() throws NacosException { serviceOperatorV2.update(Service.newService("A", "B", "C"), new ServiceMetadata()); Mockito.verify(metadataOperateService).updateServiceMetadata(Mockito.any(), Mockito.any()); }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void creates_default_summary_printer_if_not_disabled() { RuntimeOptions options = parser .parse() .addDefaultSummaryPrinterIfNotDisabled() .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugins.setEventBusOnEventLi...
@Udf(description = "Returns the base 10 logarithm of an INT value.") public Double log( @UdfParameter( value = "value", description = "the value get the base 10 logarithm of." ) final Integer value ) { return log(value == null ? null : value.doubleValue())...
@Test public void shouldHandleZeroBase() { assertThat(Double.isNaN(udf.log(0, 13)), is(true)); assertThat(Double.isNaN(udf.log(0L, 13L)), is(true)); assertThat(Double.isNaN(udf.log(0.0, 13.0)), is(true)); }
@Override public boolean isResponsibleClient(Client client) { return true; }
@Test void testIsResponsibleClient() { assertTrue(persistentIpPortClientManager.isResponsibleClient(client)); }
public void addMetadataUpdateRequest(String schemaName, String tableName, Optional<String> partitionName, int writerIndex) { UUID requestId = UUID.randomUUID(); requestFutureMap.put(requestId, SettableFuture.create()); writerRequestMap.put(writerIndex, requestId); // create a reques...
@Test public void testAddMetadataUpdateRequest() { HiveMetadataUpdater hiveMetadataUpdater = new HiveMetadataUpdater(EXECUTOR); // add Request hiveMetadataUpdater.addMetadataUpdateRequest(TEST_SCHEMA_NAME, TEST_TABLE_NAME, Optional.of(TEST_PARTITION_NAME), TEST_WRITER_INDEX); Li...
public static String localHostIP() { if (PREFER_IPV6_ADDRESSES) { return LOCAL_HOST_IP_V6; } return LOCAL_HOST_IP_V4; }
@Test void testLocalHostIP() throws NoSuchFieldException, IllegalAccessException { Field field = InternetAddressUtil.class.getField("PREFER_IPV6_ADDRESSES"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final StoregateApiClient client = session.getClient(); final HttpUriRequest request = new HttpGet(String.format("%s/v4.2/download/file...
@Test public void testReadInterrupt() throws Exception { final byte[] content = RandomUtils.nextBytes(32769); final TransferStatus writeStatus = new TransferStatus(); writeStatus.setLength(content.length); final StoregateIdProvider nodeid = new StoregateIdProvider(session); f...
@VisibleForTesting String buildBody(Stream stream, AlertCondition.CheckResult checkResult, List<Message> backlog) { final String template; if (pluginConfig == null || pluginConfig.getString("body") == null) { template = bodyTemplate; } else { template = pluginConfig.g...
@Test public void buildBodyContainsInfoMessageIfWebInterfaceURLIsIncomplete() throws Exception { final EmailConfiguration configuration = new EmailConfiguration() { @Override public URI getWebInterfaceUri() { return URI.create(""); } }; thi...
@Override @Nullable public BlobHttpContent getContent() { return null; }
@Test public void testGetContent() { Assert.assertNull(testBlobPuller.getContent()); }
@Override public Optional<FieldTypes> get(final String fieldName) { return Optional.ofNullable(get(ImmutableSet.of(fieldName)).get(fieldName)); }
@Test public void getMultipleFieldsWithIndexScope() { dbService.save(createDto("graylog_0", "abc", Collections.emptySet())); dbService.save(createDto("graylog_1", "xyz", Collections.emptySet())); dbService.save(createDto("graylog_2", "xyz", of( FieldTypeDTO.create("yolo1", "b...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return areNewFieldsEqual((Request<?>) obj); }
@Test(dataProvider = "toRequestFieldsData") public void testRequestMetadataFieldsEqual(List<PathSpec> pathSpecs1, List<PathSpec> pathSpecs2, Map<String,String> param1, Map<String,String> param2, boolean expect) { GetRequestBuilder<Long, TestRecord> builder1 = generateDummyRequestBuilder(); GetRequestBuilde...
@Override public Collection<String> getJdbcUrlPrefixes() { return Collections.singletonList(String.format("jdbc:%s:", getType().toLowerCase())); }
@Test void assertGetJdbcUrlPrefixes() { assertThat(TypedSPILoader.getService(DatabaseType.class, "PostgreSQL").getJdbcUrlPrefixes(), is(Collections.singletonList("jdbc:postgresql:"))); }
@Override public void logoutSuccess(HttpRequest request, @Nullable String login) { checkRequest(request); if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug("logout success [IP|{}|{}][login|{}]", request.getRemoteAddr(), getAllIps(request), preventLogFlood(emptyIfNull(login))); ...
@Test public void logout_success_creates_DEBUG_log_with_empty_login_if_login_argument_is_null() { underTest.logoutSuccess(mockRequest(), null); verifyLog("logout success [IP||][login|]", Set.of("login", "logout failure")); }
@PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); }
@Test @Sql("/insert_car.sql") void updateCar() throws Exception { // given CarDto carDto = CarDto.builder() .id(UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80")) .name("vw") .color("white") .build(); // when ...
public Optional<Account> getByAccountIdentifier(final UUID uuid) { return checkRedisThenAccounts( getByUuidTimer, () -> redisGetByAccountIdentifier(uuid), () -> accounts.getByAccountIdentifier(uuid) ); }
@Test void testGetAccountByUuidNotInCache() { UUID uuid = UUID.randomUUID(); UUID pni = UUID.randomUUID(); Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); when(commands.get(eq("Account...
@Override public Iterator<LongStatistic> getLongStatistics() { return new LongIterator(); }
@Test public void testGetLongStatistics() { short iterations = 0; // number of the iter.hasNext() final Iterator<LongStatistic> iter = statistics.getLongStatistics(); while (iter.hasNext()) { final LongStatistic longStat = iter.next(); assertNotNull(longStat); final OpType opType = OpTy...
@Override public SeriesSpec apply(final Metric metric) { metricValidator.validate(metric); return switch (metric.functionName()) { case Average.NAME -> Average.builder().field(metric.fieldName()).build(); case Cardinality.NAME -> Cardinality.builder().field(metric.fieldName(...
@Test void throwsExceptionWhenValidatorThrowsException() { doThrow(ValidationException.class).when(metricValidator).validate(any()); assertThrows(ValidationException.class, () -> toTest.apply(new Metric("unknown", "http_method"))); }
@Override @PublicAPI(usage = ACCESS) public void check(JavaClasses classes) { getArchRule().check(classes); }
@Test public void should_allow_empty_should_if_configured() { configurationRule.setFailOnEmptyShould(false); ruleWithEmptyShould().check(new ClassFileImporter().importClasses(getClass())); }
@Override public void onMsg(TbContext ctx, TbMsg msg) { EntityType originatorType = msg.getOriginator().getEntityType(); ctx.tellNext(msg, config.getOriginatorTypes().contains(originatorType) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); }
@Test void givenAsset_whenOnMsg_then_False() { // GIVEN AssetId assetId = new AssetId(UUID.randomUUID()); TbMsg msg = getTbMsg(assetId); // WHEN node.onMsg(ctx, msg); // THEN ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); ...
public void logAndProcessFailure( String computationId, ExecutableWork executableWork, Throwable t, Consumer<Work> onInvalidWork) { if (shouldRetryLocally(computationId, executableWork.work(), t)) { // Try again after some delay and at the end of the queue to avoid a tight loop. ...
@Test public void logAndProcessFailure_doesNotRetryWhenWorkItemCancelled() { Set<Work> executedWork = new HashSet<>(); ExecutableWork work = createWork(executedWork::add); WorkFailureProcessor workFailureProcessor = createWorkFailureProcessor(streamingEngineFailureReporter()); Set<Work> invali...
public static KafkaUserModel fromCrd(KafkaUser kafkaUser, String secretPrefix, boolean aclsAdminApiSupported) { KafkaUserModel result = new KafkaUserModel(kafkaUser.getMetadata().getNamespace(), kafkaUser.getMetada...
@Test public void testFromCrdScramShaUserWithMissingPasswordKeyThrows() { KafkaUser missingKey = new KafkaUserBuilder(scramShaUser) .editSpec() .withNewKafkaUserScramSha512ClientAuthentication() .withNewPassword() .wi...
boolean isWriteEnclosureForValueMetaInterface( ValueMetaInterface v ) { return ( isWriteEnclosed( v ) ) || isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( v.getName().getBytes() ); }
@Test public void testWriteEnclosedForValueMetaInterface() { TextFileOutputData data = new TextFileOutputData(); data.binarySeparator = new byte[1]; data.binaryEnclosure = new byte[1]; data.writer = new ByteArrayOutputStream(); TextFileOutputMeta meta = getTextFileOutputMeta(); meta.setEnclosu...
public Object getParameter(String key) { return param.get(key); }
@Test void testGetParameterWithNullDefaultValue() { assertThrows(IllegalArgumentException.class, () -> { identityContext.getParameter(TEST, null); }); }
public static boolean isShuttingDown() { return shuttingDown; }
@Test public void isShuttingDown() throws Exception { Assert.assertEquals(RpcRunningState.isShuttingDown(), RpcRunningState.shuttingDown); }
@Override public boolean storesUpperCaseIdentifiers() { return false; }
@Test void assertStoresUpperCaseIdentifiers() { assertFalse(metaData.storesUpperCaseIdentifiers()); }
@Override @PublicAPI(usage = ACCESS) public JavaClass toErasure() { return erasure; }
@Test public void erased_wildcard_bound_by_single_class_is_this_class() { @SuppressWarnings("unused") class ClassWithBoundTypeParameterWithSingleClassBound<T extends List<? extends Serializable>> { } JavaWildcardType type = importWildcardTypeOf(ClassWithBoundTypeParameterWithSingleC...
@Override public List<String> getChildrenKeys(final String key) { try ( Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(repositorySQL.getSelectByParentKeySQL())) { preparedStatement.setString(1,...
@Test void assertPersistAndGetChildrenKeysFailure() throws SQLException { when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByParentKeySQL())).thenReturn(mockPreparedStatement); when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet); when(mockResultSet.next()).the...
@Override public byte[] readArray(int size) { int remaining = buf.remaining(); if (size > remaining) { throw new RuntimeException("Error reading byte array of " + size + " byte(s): only " + remaining + " byte(s) available"); } byte[] arr = new byte[siz...
@Test public void testReadArray() { ByteBuffer buf = ByteBuffer.allocate(1024); ByteBufferAccessor accessor = new ByteBufferAccessor(buf); final byte[] testArray = new byte[] {0x4b, 0x61, 0x46}; accessor.writeByteArray(testArray); accessor.writeInt(12345); accessor.fl...
public static List<Path> pluginUrls(Path topPath) throws IOException { boolean containsClassFiles = false; Set<Path> archives = new TreeSet<>(); LinkedList<DirectoryEntry> dfs = new LinkedList<>(); Set<Path> visited = new HashSet<>(); if (isArchive(topPath)) { return...
@Test public void testPluginUrlsWithClasses() throws Exception { Files.createDirectories(pluginPath.resolve("org/apache/kafka/converters")); Files.createDirectories(pluginPath.resolve("com/mycompany/transforms")); Files.createDirectories(pluginPath.resolve("edu/research/connectors")); ...
public int compare(boolean b1, boolean b2) { throw new UnsupportedOperationException( "compare(boolean, boolean) was called on a non-boolean comparator: " + toString()); }
@Test public void testFloatComparator() { Float[] valuesInAscendingOrder = { null, Float.NEGATIVE_INFINITY, -Float.MAX_VALUE, -1234.5678F, -Float.MIN_VALUE, 0.0F, Float.MIN_VALUE, 1234.5678F, Float.MAX_VALUE, Float.POSITIVE_INFINITY }; for (int ...
Configuration getEffectiveConfiguration(String[] args) throws CliArgsException { final CommandLine commandLine = cli.parseCommandLineOptions(args, true); final Configuration effectiveConfiguration = new Configuration(baseConfiguration); effectiveConfiguration.addAll(cli.toConfiguration(commandLi...
@Test void testDynamicProperties() throws Exception { final KubernetesSessionCli cli = new KubernetesSessionCli( new Configuration(), confDirPath.toAbsolutePath().toString()); final String[] args = new String[] { "-e", ...
public static List<String> parseScope(String spaceDelimitedScope) throws OAuthBearerConfigException { List<String> retval = new ArrayList<>(); for (String individualScopeItem : Objects.requireNonNull(spaceDelimitedScope).split(" ")) { if (!individualScopeItem.isEmpty()) { if ...
@Test public void invalidScope() { for (String invalidScope : new String[] {"\"foo", "\\foo"}) { try { OAuthBearerScopeUtils.parseScope(invalidScope); fail("did not detect invalid scope: " + invalidScope); } catch (OAuthBearerConfigException expected) ...
public static Calendar getLongFromDateTime(String date, String dateFormat, String time, String timeFormat) { Calendar cal = Calendar.getInstance(); Calendar cDate = Calendar.getInstance(); Calendar cTime = Calendar.getInstance(); SimpleDateFormat sdfDate = new SimpleDateFormat(dateFormat); Sim...
@Test public void getLongFromDateTimeTest() { String date = "2020-03-12"; String dateformat = "yyyy-MM-dd"; String time = "15:15:15"; String timeformat = "HH:mm:ss"; Calendar calendar = DateUtils.getLongFromDateTime(date, dateformat, time, timeformat); assertEquals(calendar.get(Calendar.YEAR),...
private int hash(String key) { int klen = key.length(); int out = klen; if (select == null) { for (int i = 0; i < klen; i++) { int c = key.charAt(i) - min; if (c < 0) return -1; if (c >= kvals.length) return -2; out += k...
@Test public void testHash() { System.out.println("PerfectHash"); PerfectHash hash = new PerfectHash("abc", "great", "hash"); assertEquals(0, hash.get("abc")); assertEquals(1, hash.get("great")); assertEquals(2, hash.get("hash")); assertEquals(-1, hash.get("perfect"))...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testUnauthorizedTopic() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertEquals(1, sendFetches()); client.prepareResponse(fullFetchResponse(tidp0, records, Errors.TOPIC_AUTHORIZATION_FAILED, 100L, 0)); networkClie...
@Override public DirectPipelineResult run(Pipeline pipeline) { try { options = MAPPER .readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class) .as(DirectOptions.class); } catch (IOException e) { throw new IllegalArgumentException( "Pipeli...
@Test public void testMutatingOutputCoderDoFnError() throws Exception { Pipeline pipeline = getPipeline(); pipeline .apply(Create.of(42)) .apply( ParDo.of( new DoFn<Integer, byte[]>() { @ProcessElement public void processElement(...
@Override @SuppressFBWarnings("AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION") public Object invoke(Object proxy, Method method, Object[] args) { if (args == null && "toString".equals(method.getName())) { return toString(); } else if (args != null && args.length == 1 && "equals".equals(method.getNam...
@Test public void testInvokeWithUnknownMethod() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage( "Unknown method [public abstract void " + "org.apache.beam.sdk.options.ProxyInvocationHandlerTest$UnknownMethod.unknownMethod()] " ...
@Override public List<TransferItem> list(final Session<?> session, final Path remote, final Local directory, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List children for %s", directory))...
@Test public void testChildrenEmpty() throws Exception { final Path root = new Path("/t", EnumSet.of(Path.Type.directory)) { }; Transfer t = new UploadTransfer(new Host(new TestProtocol()), root, new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString())); ...
@Override @Nullable public byte[] readByteArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray); }
@Test public void testReadByteArray() throws Exception { assertNull(reader.readByteArray("NO SUCH FIELD")); }
@Transactional(readOnly = true) public TemplateResponse generateReviewForm(String reviewRequestCode) { ReviewGroup reviewGroup = reviewGroupRepository.findByReviewRequestCode(reviewRequestCode) .orElseThrow(() -> new ReviewGroupNotFoundByReviewRequestCodeException(reviewRequestCode)); ...
@Test void ๋ฆฌ๋ทฐ์ด์—๊ฒŒ_์ž‘์„ฑ๋ _๋ฆฌ๋ทฐ_์–‘์‹_์ƒ์„ฑ_์‹œ_์ €์žฅ๋œ_ํ…œํ”Œ๋ฆฟ์ด_์—†์„_๊ฒฝ์šฐ_์˜ˆ์™ธ๊ฐ€_๋ฐœ์ƒํ•œ๋‹ค() { // given ReviewGroup reviewGroup = new ReviewGroup("๋ฆฌ๋ทฐ์ด๋ช…", "ํ”„๋กœ์ ํŠธ๋ช…", "reviewRequestCode", "groupAccessCode"); reviewGroupRepository.save(reviewGroup); // when, then assertThatThrownBy(() -> templateService.generateRe...
public static ProviderInfo parseProviderInfo(String originUrl) { String url = originUrl; String host = null; int port = 80; String path = null; String schema = null; int i = url.indexOf("://"); // seperator between schema and body if (i > 0) { schema =...
@Test public void parseProviderInfo() throws Exception { String defaultProtocol = RpcConfigs.getStringValue(RpcOptions.DEFAULT_PROTOCOL); // 10.244.22.1:8080?zone=GZ00A&self_app_name=icardcenter&app_name=icardcenter&_TIMEOUT=3000 // 11.166.0.239:12200?_TIMEOUT=3000&p=1&_SERIALIZETYPE=hessian...
@Override public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) { AbstractWALEvent result; byte[] bytes = new byte[data.remaining()]; data.get(bytes); String dataText = new String(bytes, StandardCharsets.UTF_8); if (decodeWithTX)...
@Test void assertDecodeUnknownRowEventType() { MppTableData tableData = new MppTableData(); tableData.setTableName("public.test"); tableData.setOpType("UNKNOWN"); tableData.setColumnsName(new String[]{"data"}); tableData.setColumnsType(new String[]{"character varying"}); ...
private Mono<ServerResponse> installFromUri(ServerRequest request) { var content = request.bodyToMono(InstallFromUriRequest.class) .map(InstallFromUriRequest::uri) .flatMapMany(urlDataBufferFetcher::fetch); return themeService.install(content) .flatMap(theme -> Serve...
@Test void installFromUri() { final URI uri = URI.create("https://example.com/test-theme.zip"); var metadata = new Metadata(); metadata.setName("fake-theme"); var theme = new Theme(); theme.setMetadata(metadata); when(themeService.install(any())).thenReturn(Mono.just...
@Udf public String extractParam( @UdfParameter(description = "a valid URL") final String input, @UdfParameter(description = "the parameter key") final String paramToFind) { final String query = UrlParser.extract(input, URI::getQuery); if (query == null) { return null; } for (final S...
@Test public void shouldReturnNullIfParamNotPresent() { assertThat(extractUdf.extractParam("https://docs.confluent.io?foo%20bar=baz&blank#scalar-functions", "absent"), nullValue()); }
public static UUID fromString(String src) { return UUID.fromString(src.substring(7, 15) + "-" + src.substring(3, 7) + "-1" + src.substring(0, 3) + "-" + src.substring(15, 19) + "-" + src.substring(19)); }
@Test public void basicUuidConversion() { UUID original = UUID.fromString("3dd11790-abf2-11ea-b151-83a091b9d4cc"); Assertions.assertEquals(Uuids.unixTimestamp(original), 1591886749577L); }
@Override public Processor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>> get() { return new ContextualProcessor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>>() { private TimestampedKeyValu...
@Test public void shouldPropagateNullIfNoFKValAvailableV0() { final StoreBuilder<TimestampedKeyValueStore<Bytes, SubscriptionWrapper<String>>> storeBuilder = storeBuilder(); final SubscriptionReceiveProcessorSupplier<String, String> supplier = supplier(storeBuilder); final Processor<String, ...
public T getMetaForEntry( Repository rep, IMetaStore metaStore, VariableSpace space ) throws KettleException { try { T theMeta = null; if ( jobEntryBase.getParentJob() != null ) { metaFileCache = jobEntryBase.getParentJobMeta().getMetaFileCache(); //Get the cache from the parent or create it ...
@Test //A job getting the JobMeta from the repo public void getMetaForEntryAsJobFromRepoTest() throws Exception { setupJobEntryJob(); specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME; MetaFileLoaderImpl metaFileLoader = new MetaFileLoaderImpl<JobMeta>( jobEntryBase, specificati...
@Override public CompletableFuture<TxnOffsetCommitResponseData> commitTransactionalOffsets( RequestContext context, TxnOffsetCommitRequestData request, BufferSupplier bufferSupplier ) { if (!isActive.get()) { return CompletableFuture.completedFuture(TxnOffsetCommitReq...
@Test public void testCommitTransactionalOffsets() throws ExecutionException, InterruptedException { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createCo...
boolean isMapped(String userId) { return idToDirectoryNameMap.containsKey(getIdStrategy().keyFor(userId)); }
@Test public void testDuplicatedUserId() throws IOException { UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE); assertThat(mapper.isMapped("user2"), is(true)); assertThat(mapper.isMapped("user1"), is(true)); }
public static long findMinLegalValue( Function<Long, Boolean> legalChecker, long low, long high) { if (!legalChecker.apply(high)) { return -1; } while (low <= high) { long mid = (low + high) / 2; if (legalChecker.apply(mid)) { high ...
@Test void testFindMinLegalValue() { assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 1, 17)) .isEqualTo(8); assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 8, 17)) .isEqualTo(8); assertThat(BisectionSearc...
@Override public Processor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>> get() { return new ContextualProcessor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>>() { private KT...
@Test public void shouldPropagateOnlyIfFKAvailableV0() { final MockProcessorContext<String, SubscriptionResponseWrapper<String>> context = new MockProcessorContext<>(); processor.init(context); final SubscriptionWrapper<String> newValue = new SubscriptionWrapper<>( new long[]{1L...
public static EthMappingAddress ethMappingAddress(MacAddress mac) { return new EthMappingAddress(mac); }
@Test public void testEthMappingAddressMethod() { MacAddress mac = MacAddress.valueOf("00:00:00:00:00:01"); MappingAddress mappingAddress = MappingAddresses.ethMappingAddress(mac); EthMappingAddress ethMappingAddress = checkAndConvert(mappingAddress, ...
public static DataCleaner<Track<NopHit>> simpleSmoothing() { NopEncoder nopEncoder = new NopEncoder(); DataCleaner<Track<NopHit>> cleaner = coreSmoothing(); ToStringFunction<Track<NopHit>> toString = track -> nopEncoder.asRawNop(track); ExceptionHandler exceptionHandler = new Sequentia...
@Test public void testSimultaneousSmoothing() { /* * The file: starsTrackWithCoastedPoints.txt contains... * * 2 Coasted Points * * 1 Dropped Point * * 1 artifically added vertical outlier (the 43rd point had its altitude set to 000) * ...
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("match") String match) { if ( string == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "string", "cannot be null" ) ); } if ( match == null ) { ret...
@Test void invokeNull() { FunctionTestUtil.assertResultError(substringBeforeFunction.invoke((String) null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(substringBeforeFunction.invoke(null, "test"), InvalidParametersEvent.class); ...
@VisibleForTesting Collection<CompletableFuture<Channel>> getResponseChannelFutures() { return responseChannelFutures; }
@Test void testResponseChannelFuturesResolvedExceptionallyOnClose() throws Exception { try (final RestClient restClient = new RestClient(new Configuration(), Executors.directExecutor())) { CompletableFuture<Channel> responseChannelFuture = new CompletableFuture<>(); ...
@Override public void accept(T t) { updateTimeHighWaterMark(t.time()); shortTermStorage.add(t); drainDueToLatestInput(t); //standard drain policy drainDueToTimeHighWaterMark(); //prevent blow-up when data goes backwards in time sizeHighWaterMark = Math.max(sizeHighWaterMa...
@Test public void testOverflowBug() { /* * It should not be possible to crash an ApproximateTimeSorter by overloading the memory by * continuously providing older and older points. */ Duration maxLag = Duration.ofSeconds(3); //a very small sorting window Consumi...
public static <T> PrefetchableIterable<T> fromArray(T... values) { if (values.length == 0) { return emptyIterable(); } return new Default<T>() { @Override public PrefetchableIterator<T> createIterator() { return PrefetchableIterators.fromArray(values); } }; }
@Test public void testFromArray() { verifyIterable(PrefetchableIterables.fromArray("A", "B", "C"), "A", "B", "C"); verifyIterable(PrefetchableIterables.fromArray()); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindGenericMethodWithStringParam() { // Given: givenFunctions( function(EXPECTED, -1, GENERIC_LIST) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(Collections.singletonList(SqlArgument.of(SqlArray.of(SqlTypes.STRING)))); // Then: assertTha...
@Override public boolean registerAllRequestsProcessedListener(NotificationListener listener) throws IOException { return super.registerAllRequestsProcessedListener(listener); }
@Test void testSubscribeAndClose() throws Exception { final TestNotificationListener listener = new TestNotificationListener(); addRequest(); addRequest(); writer.registerAllRequestsProcessedListener(listener); final CheckedThread asyncCloseThread = new Che...
public TwilioEndpoint(String uri, TwilioComponent component, TwilioApiName apiName, String methodName, TwilioConfiguration endpointConfiguration) { super(uri, component, apiName, methodName, TwilioApiCollection.getCollection().getHelper(apiName), endpointConfiguration); ...
@Test public void testTwilioEndpoint() { // should not use reflection when creating and configuring endpoint final BeanIntrospection beanIntrospection = PluginHelper.getBeanIntrospection(context); long before = beanIntrospection.getInvokedCounter(); TwilioEndpoint te = context.getEn...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testMisc31() { Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true)); Set<Class<?>> classes = new HashSet<>(Arrays.asList(Misc31Resource.class)); OpenAPI openAPI = reader.read(classes); String yaml = "openapi: 3.1.0\n" + ...
@Override public String getPrincipal() { Subject subject = org.apache.shiro.SecurityUtils.getSubject(); String principal; if (subject.isAuthenticated()) { principal = extractPrincipal(subject); if (zConf.isUsernameForceLowerCase()) { if (LOGGER.isDebugEnabled()) { LOGGER.deb...
@Test void testUsernameForceLowerCase() throws IOException, InterruptedException { String expectedName = "java.security.Principal.getName()"; when(zConf.isUsernameForceLowerCase()).thenReturn(true); setupPrincipalName(expectedName); assertEquals(expectedName.toLowerCase(), shiroSecurityService.getPrin...
public static void writeBinaryCodedLengthBytes(byte[] data, ByteArrayOutputStream out) throws IOException { // 1. write length byte/bytes if (data.length < 252) { out.write((byte) data.length); } else if (data.length < (1 << 16L)) { out.write((byte) 252); writ...
@Test public void testWriteBinaryCodedLengthBytes2() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteHelper.writeBinaryCodedLengthBytes(new byte[252], out); byte[] expected = new byte[255]; expected[0] = -4; expected[1] = -4; Assert.assertArrayEquals(expected, (out.toByt...
@Nonnull public static <T> BatchSource<T> list(@Nonnull String listName) { return batchFromProcessor("listSource(" + listName + ')', readListP(listName)); }
@Test public void list_byRef() { // Given List<Integer> input = sequence(itemCount); addToSrcList(input); // When BatchSource<Object> source = Sources.list(srcList); // Then p.readFrom(source).writeTo(sink); execute(); assertEquals(input, sin...
@Override public Object clone() throws CloneNotSupportedException { return new CowSet<>(_map.clone()); }
@Test public void testClone() throws CloneNotSupportedException { final CowSet<String> set1 = new CowSet<>(); set1.add("test"); @SuppressWarnings("unchecked") final CowSet<String> set2 = (CowSet<String>)set1.clone(); @SuppressWarnings("unchecked") final CowSet<String> set3 = (CowSet<String>...
@Override public KTable<Windowed<K>, V> reduce(final Reducer<V> reducer) { return reduce(reducer, NamedInternal.empty()); }
@Test public void shouldThrowNullPointerOnMaterializedReduceIfReducerIsNull() { assertThrows(NullPointerException.class, () -> windowedStream.reduce(null, Materialized.as("store"))); }
@SuppressFBWarnings("EI_EXPOSE_REP") public Comparable[] getComponents() { return components; }
@Test public void testConstruction() { assertThat(new CompositeValue(new Comparable[]{1, 1.1, "1.1"}).getComponents()).isEqualTo(new Object[]{1, 1.1, "1.1"}); assertThat(new CompositeValue(1, "prefix", null).getComponents()) .isEqualTo(new Object[]{"prefix"}); assertThat(new ...
public List<KiePMMLDroolsRule> declareRulesFromCharacteristics(final Characteristics characteristics, final String parentPath, Number initialScore) { logger.trace("declareRulesFromCharacteristics {} {} {}", characteristics, parentPath, initialScore); final List<KiePMMLDroolsRule> toReturn = new ArrayLis...
@Test void declareRulesFromCharacteristics() { Characteristics characteristics = scorecardModel.getCharacteristics(); String parentPath = "_will"; List<KiePMMLDroolsRule> retrieved = getKiePMMLScorecardModelCharacteristicASTFactory() .declareRulesFromCharacteristics(character...
public static long getCurrentPID() { return Long.parseLong(getRuntimeMXBean().getName().split("@")[0]); }
@Test public void getCurrentPidTest() { final long pid = SystemUtil.getCurrentPID(); assertTrue(pid > 0); }
public GlobalTransactional getTransactionAnnotation() { return transactionAnnotation; }
@Test public void testGetTransactionAnnotation() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { MethodDesc methodDesc = getMethodDesc(); assertThat(methodDesc.getTransactionAnnotation()).isEqualTo(transactional); }
void precheckMaxResultLimitOnLocalPartitions(String mapName) { // check if feature is enabled if (!isPreCheckEnabled) { return; } // limit number of local partitions to check to keep runtime constant PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa...
@Test public void testLocalPreCheckEnabledWitDifferentPartitionSizesBelowLimit() { int[] partitionSizes = {566, 1132, Integer.MAX_VALUE}; populatePartitions(partitionSizes); initMocksWithConfiguration(200000, 2); limiter.precheckMaxResultLimitOnLocalPartitions(ANY_MAP_NAME); }
public static <K, V> ProducerRecordCoder<K, V> of(Coder<K> keyCoder, Coder<V> valueCoder) { return new ProducerRecordCoder<>(keyCoder, valueCoder); }
@Test public void testCoderIsSerializableWithWellKnownCoderType() { CoderProperties.coderSerializable( ProducerRecordCoder.of(GlobalWindow.Coder.INSTANCE, GlobalWindow.Coder.INSTANCE)); }
public static List<ConstraintKey> getConstraintKeys( DatabaseMetaData metadata, TablePath tablePath) throws SQLException { // We set approximate to true to avoid querying the statistics table, which is slow. try (ResultSet resultSet = metadata.getIndexInfo( ...
@Test void testConstraintKeysNameWithOutSpecialChar() throws SQLException { List<ConstraintKey> constraintKeys = CatalogUtils.getConstraintKeys( new TestDatabaseMetaData(), TablePath.of("test.test")); Assertions.assertEquals("testfdawe_", constraintKeys.get(0)...
@Override public RecordCursor cursor() { return new PrometheusRecordCursor(columnHandles, byteSource); }
@Test public void testCursorSimple() { RecordSet recordSet = new PrometheusRecordSet( new PrometheusClient(new PrometheusConnectorConfig(), METRIC_CODEC, TYPE_MANAGER), new PrometheusSplit(dataUri), ImmutableList.of( new PrometheusC...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { if(file.isDirectory()) { return this.toAttributes(new FoldersApi(new BoxApiClient(session.getClient())).getFoldersId(fileid.getFileId(file), ...
@Test public void testFindFile() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path folder = new BoxDirectoryFeature(session, fileid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new Tran...
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) { AnalyzerContext context = new AnalyzerContext(); int treeSize = aggregatePredicateStatistics(predicate, false, context); int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.h...
@Test void require_that_minfeature_is_1_for_simple_negative_term() { Predicate p = not(feature("foo").inSet("bar")); PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p); assertEquals(1, r.minFeature); }