focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Future<RestResponse> restRequest(RestRequest request) { return restRequest(request, new RequestContext()); }
@Test public void testRestRetry() throws Exception { SimpleLoadBalancer balancer = prepareLoadBalancer(Arrays.asList("http://test.linkedin.com/retry1", "http://test.linkedin.com/good"), HttpClientFactory.UNLIMITED_CLIENT_REQUEST_RETRY_RATIO); DynamicClient dynamicClient = new DynamicClient(balancer...
@Override public ExecuteContext doAfter(ExecuteContext context) { final Object result = context.getResult(); if (result != null) { // The original registry is restored RegisterContext.INSTANCE.compareAndSet(false, true); } return context; }
@Test public void doAfter() throws NoSuchMethodException { final ExecuteContext context = buildContext(); context.changeResult(new Object()); interceptor.doAfter(context); Assert.assertTrue(RegisterContext.INSTANCE.isAvailable()); RegisterContext.INSTANCE.compareAndSet(true, ...
@Override public Result responseMessageForCheckConnectionToPackage(String responseBody) { return jsonResultMessageHandler.toResult(responseBody); }
@Test public void shouldBuildFailureResultFromCheckPackageConnectionResponse() throws Exception { String responseBody = "{\"status\":\"failure\",messages=[\"message-one\",\"message-two\"]}"; Result result = messageHandler.responseMessageForCheckConnectionToPackage(responseBody); assertFailur...
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) { return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs)); }
@Test public void testGroupingKeyTypeWithSpecEvolutionInV2Tables() { TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V2_FORMAT_VERSION); table.updateSpec().addField(Expressions.bucket("category", 8)).commit(); assertThat(table.specs()).hasSize(2); Stru...
public static Read read() { return new AutoValue_RedisIO_Read.Builder() .setConnectionConfiguration(RedisConnectionConfiguration.create()) .setKeyPattern("*") .setBatchSize(1000) .setOutputParallelization(true) .build(); }
@Test public void testRead() { List<KV<String, String>> data = buildIncrementalData("bulkread", 10); data.forEach(kv -> client.set(kv.getKey(), kv.getValue())); PCollection<KV<String, String>> read = p.apply( "Read", RedisIO.read() .withEndpoint(REDIS_HOST,...
public static List<Validation> computeFlagsFromCSVString(String csvString, Log log) { List<Validation> flags = new ArrayList<>(); boolean resetFlag = false; for (String p : csvString.split(",")) { try { flag...
@Test public void testFlagsDisable() { List<DMNValidator.Validation> result = DMNValidationHelper.computeFlagsFromCSVString("disabled", log); assertThat(result).isNotNull() .hasSize(0); }
@Operation(summary = "createProcessDefinition", description = "CREATE_PROCESS_DEFINITION_NOTES") @Parameters({ @Parameter(name = "name", description = "PROCESS_DEFINITION_NAME", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "locations", description = "P...
@Test public void testCreateProcessDefinition() { String relationJson = "[{\"name\":\"\",\"pre_task_code\":0,\"pre_task_version\":0,\"post_task_code\":123456789,\"post_task_version\":1," + "\"condition_type\":0,\"condition_params\":\"{}\"},{\"name\":\"\",\"pre_task_co...
@Override public List<HouseTable> findAllByDatabaseId(String databaseId) { Map<String, String> params = new HashMap<>(); if (Strings.isNotEmpty(databaseId)) { params.put("databaseId", databaseId); } return getHtsRetryTemplate( Arrays.asList( HouseTableRepositoryState...
@Test public void testListWithEmptyResult() { // Shouldn't expect failure but gracefully getting an empty list. List<UserTable> tables = new ArrayList<>(); GetAllEntityResponseBodyUserTable listResponse = new GetAllEntityResponseBodyUserTable(); Field resultField = ReflectionUtils.findField(Ge...
@Override public void write(OutputStream os) throws IOException { IOUtils.skipFully(is, offset); long bytes = 0L; if (len == -1) { // Use the configured buffer size instead of hardcoding to 4k bytes = FSOperations.copyBytes(is, os); } else { bytes = FSOperations.copyBytes(is, os, len...
@Test public void test() throws Exception { InputStream is = new ByteArrayInputStream("abc".getBytes()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStreamEntity i = new InputStreamEntity(is); i.write(baos); baos.close(); assertEquals(new String(baos.toByteArray()), "abc"); ...
public static LinkedHashSet<Class<?>> listBeansRecursiveInclusive(Class<?> beanClass) { return listBeansRecursiveInclusive(beanClass, new LinkedHashSet<>()); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void listBeansCyclic() { LinkedHashSet<Class<?>> classes = TypeUtils.listBeansRecursiveInclusive(Cyclic.class); // System.out.println(classes); assertEquals(classes.size(), 2); }
@Override public ExecuteContext doBefore(ExecuteContext context) { DatabaseInfo databaseInfo = getDataBaseInfo(context); String database = databaseInfo.getDatabaseName(); Query query = (Query) context.getArguments()[0]; String sql = query.toString((ParameterList) context.getArguments...
@Test public void testDoBefore() throws Exception { // Database write prohibition switch turned off GLOBAL_CONFIG.setEnableOpenGaussWriteProhibition(false); ExecuteContext context = ExecuteContext.forMemberMethod(queryExecutor, methodMock, argument, null, null); queryExecutorImplInte...
public List<Long> getAggregatedSubpartitionBytes() { checkState(aggregatedSubpartitionBytes != null, "Not all partition infos are ready"); return Collections.unmodifiableList(aggregatedSubpartitionBytes); }
@Test void testGetAggregatedSubpartitionBytes() { AllToAllBlockingResultInfo resultInfo = new AllToAllBlockingResultInfo(new IntermediateDataSetID(), 2, 2, false); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L})); resultInfo.recordPartitionIn...
PMML4Result getPMML4Result(final KiePMMLMiningModel toEvaluate, final LinkedHashMap<String, KiePMMLNameValueProbabilityMapTuple> inputData, final PMMLRuntimeContext pmmlContext) { final MULTIPLE_MODEL_METHOD multipleModelMethod = toEvaluate.getSegmen...
@Test void getPMML4ResultOK() { String fileName = "FILENAME"; String name = "NAME"; String targetField = "TARGET"; String prediction = "FIRST_VALUE"; KiePMMLSegmentation kiePMMLSegmentation = KiePMMLSegmentation.builder("SEGM_1", Collections.emptyList(), SELECT_FIRST).build()...
public static void toast(Context context, @StringRes int message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } ...
@Test public void testToastWithStringRes() { AppConfig.toast(ApplicationProvider.getApplicationContext(), R.string.ok); shadowOf(getMainLooper()).idle(); await().atMost(5, TimeUnit.SECONDS).until(() -> ShadowToast.getLatestToast() != null); assertEquals( ApplicationProvider.getApplicationConte...
@Get(uri = "inputs") @ExecuteOn(TaskExecutors.IO) @Operation( tags = {"Plugins"}, summary = "Get all types for an inputs" ) public List<InputType> inputs() throws ClassNotFoundException { return Stream.of(Type.values()) .map(throwFunction(type -> new InputType(type.na...
@Test void inputs() throws URISyntaxException { Helpers.runApplicationContext((applicationContext, embeddedServer) -> { ReactorHttpClient client = ReactorHttpClient.create(embeddedServer.getURL()); List<InputType> doc = client.toBlocking().retrieve( HttpRequest.GET("/...
public static <T> T fillBean(String className, Map<List<String>, Object> params, ClassLoader classLoader) { return fillBean(errorEmptyMessage(), className, params, classLoader); }
@Test(expected = ScenarioException.class) public void fillBeanLoadClassTest() { ScenarioBeanUtil.fillBean(errorEmptyMessage(), "FakeCanonicalName", new HashMap<>(), classLoader); }
@VisibleForTesting static Instant getCreationTime(String configuredCreationTime, ProjectProperties projectProperties) throws DateTimeParseException, InvalidCreationTimeException { try { switch (configuredCreationTime) { case "EPOCH": return Instant.EPOCH; case "USE_CURRENT_T...
@Test public void testGetCreationTime_invalidValue() { InvalidCreationTimeException exception = assertThrows( InvalidCreationTimeException.class, () -> PluginConfigurationProcessor.getCreationTime("invalid format", projectProperties)); assertThat(exception).hasM...
@Nullable static String channelName(@Nullable Destination destination) { if (destination == null) return null; boolean isQueue = isQueue(destination); try { if (isQueue) { return ((Queue) destination).getQueueName(); } else { return ((Topic) destination).getTopicName(); } ...
@Test void channelName_queueAndTopic_queueOnQueueName() throws JMSException { QueueAndTopic destination = mock(QueueAndTopic.class); when(destination.getQueueName()).thenReturn("queue-foo"); assertThat(MessageParser.channelName(destination)) .isEqualTo("queue-foo"); }
@VisibleForTesting void validateCaptcha(AuthLoginReqVO reqVO) { // 如果验证码关闭,则不进行校验 if (!captchaEnable) { return; } // 校验验证码 ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class); CaptchaVO captchaVO = new CaptchaVO(); capt...
@Test public void testValidateCaptcha_successWithDisable() { // 准备参数 AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); // mock 验证码关闭 ReflectUtil.setFieldValue(authService, "captchaEnable", false); // 调用,无需断言 authService.validateCaptcha(reqVO); }
@Override public URL getURL(final int columnIndex) throws SQLException { return (URL) mergeResultSet.getValue(columnIndex, URL.class); }
@Test void assertGetURLWithColumnLabel() throws SQLException, MalformedURLException { when(mergeResultSet.getValue(1, URL.class)).thenReturn(new URL("http://xxx.xxx")); assertThat(shardingSphereResultSet.getURL("label"), is(new URL("http://xxx.xxx"))); }
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter, MetricsRecorder metricsRecorder, BufferSupplier bufferSupplier) { if (sourceCompressionType == Co...
@Test public void testInvalidCreateTimeCompressedV2() { long now = System.currentTimeMillis(); Compression compression = Compression.gzip().build(); MemoryRecords records = createRecords( RecordBatch.MAGIC_VALUE_V2, now - 1001L, compression ...
public boolean isValid() { return sizeInBytes() >= RECORD_BATCH_OVERHEAD && checksum() == computeChecksum(); }
@Test public void testInvalidRecordSize() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, Compression.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes()...
@Override public <VOut> KStream<K, VOut> processValues( final FixedKeyProcessorSupplier<? super K, ? super V, VOut> processorSupplier, final String... stateStoreNames ) { return processValues( processorSupplier, Named.as(builder.newProcessorName(PROCESSVALUES_NAME...
@Test public void shouldNotAllowNullNamedOnProcessValuesWithStores() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.processValues(fixedKeyProcessorSupplier, (Named) null, "storeName")); assertThat(exception.getMessage(), eq...
@Override public StorageObject upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.ge...
@Test public void testUploadBucketInHostname() throws Exception { final S3AccessControlListFeature acl = new S3AccessControlListFeature(virtualhost); final S3MultipartUploadService service = new S3MultipartUploadService(virtualhost, new S3WriteFeature(virtualhost, acl), acl, 5 * 1024L * 1024L, 2); ...
public CompletableFuture<RemotingCommand> forwardMessageToDeadLetterQueue(ProxyContext ctx, ReceiptHandle handle, String messageId, String groupName, String topicName, long timeoutMillis) { CompletableFuture<RemotingCommand> future = new CompletableFuture<>(); try { if (handle.getCom...
@Test public void testForwardMessageToDeadLetterQueue() throws Throwable { ArgumentCaptor<ConsumerSendMsgBackRequestHeader> requestHeaderArgumentCaptor = ArgumentCaptor.forClass(ConsumerSendMsgBackRequestHeader.class); when(this.messageService.sendMessageBack(any(), any(), anyString(), requestHeader...
public static StatementExecutorResponse execute( final ConfiguredStatement<TerminateQuery> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final TerminateQuery terminateQuery = statement.getStatement...
@Test public void shouldFailToTerminateTransientQuery() { // When: final Exception e = assertThrows( KsqlException.class, () -> CustomExecutors.TERMINATE_QUERY.execute( engine.configure("TERMINATE TRANSIENT_QUERY;"), mock(SessionProperties.class), engine.get...
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void fail_if_no_component_provided_with_since_leak_period() { assertThatThrownBy(() -> underTest.create(new SearchRequest().setInNewCodePeriod(true))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("One and only one component must be provided when searching in new cod...
@ScalarFunction(value = "construct_tdigest", visibility = EXPERIMENTAL) @Description("Create a TDigest by passing in its internal state.") @SqlType("tdigest(double)") public static Slice constructTDigest( @SqlType("array(double)") Block centroidMeansBlock, @SqlType("array(double)") B...
@Test public void testConstructTDigest() { TDigest tDigest = createTDigest(STANDARD_COMPRESSION_FACTOR); ImmutableList<Double> values = ImmutableList.of(0.0d, 1.0d, 2.0d, 3.0d, 4.0d, 5.0d, 6.0d, 7.0d, 8.0d, 9.0d); values.stream().forEach(tDigest::add); List<Double> weights = Col...
public void align() throws IOException { int zeros = (-getPosition()) & 3; if (zeros > 0) { write(zeroBuf, 0, zeros); } }
@Test public void testAlign() throws IOException { // create a new writer so we can start at file position 0 startPosition = 0; writer = new DexDataWriter(output, startPosition, 256); writer.align(); writer.write(1); writer.align(); writer.align(); w...
public String tables(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns), "tables"); }
@Test public void testTables() { Namespace ns = Namespace.of("ns"); assertThat(withPrefix.tables(ns)).isEqualTo("v1/ws/catalog/namespaces/ns/tables"); assertThat(withoutPrefix.tables(ns)).isEqualTo("v1/namespaces/ns/tables"); }
@VisibleForTesting @Override List<String> cancelNonTerminalTasks(Workflow workflow) { List<String> erroredTasks = new ArrayList<>(); // Update non-terminal tasks' status to CANCELED for (Task task : workflow.getTasks()) { if (!task.getStatus().isTerminal()) { // Cancel the ones which are n...
@Test public void testFinalizedFailure() { Task startTask = new Task(); startTask.setTaskId(UUID.randomUUID().toString()); startTask.setTaskType(Constants.DEFAULT_START_STEP_NAME); startTask.setStatus(Task.Status.IN_PROGRESS); Task maestroTask = new Task(); maestroTask.setTaskId(UUID.randomUU...
@DeleteMapping("/nodes") @Secured(action = ActionTypes.WRITE, resource = "nacos/admin", signType = SignType.CONSOLE) public RestResult<Void> deleteNodes(@RequestParam("addresses") List<String> addresses) throws Exception { return RestResultUtils.failed(405, null, "DELETE /v2/core/cluster/nodes API not a...
@Test void testLeave() throws Exception { RestResult<Void> result = nacosClusterControllerV2.deleteNodes(Collections.singletonList("1.1.1.1")); assertFalse(result.ok()); assertEquals(405, result.getCode()); }
public static boolean exists(String name) { name = getWellFormName(name); return STRING_ENV_MAP.containsKey(name); }
@Test public void exist() { assertFalse(Env.exists("xxxyyy234")); assertTrue(Env.exists("local")); assertTrue(Env.exists("dev")); }
@Override @Transactional public boolean checkForPreApproval(Long userId, Integer userType, String clientId, Collection<String> requestedScopes) { // 第一步,基于 Client 的自动授权计算,如果 scopes 都在自动授权中,则返回 true 通过 OAuth2ClientDO clientDO = oauth2ClientService.validOAuthClientFromCache(clientId); Asse...
@Test public void checkForPreApproval_approve() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); String clientId = randomString(); List<String> requestedScopes = Lists.newArrayList("read"); // mock 方法 when...
public Response downloadDumpFile(String topologyId, String hostPort, String fileName, String user) throws IOException { String[] hostPortSplit = hostPort.split(":"); String host = hostPortSplit[0]; String portStr = hostPortSplit[1]; Path rawFile = logRoot.resolve(topologyId).resolve(port...
@Test public void testDownloadDumpFileTraversalInPort() throws IOException { try (TmpPath rootPath = new TmpPath()) { LogviewerProfileHandler handler = createHandlerTraversalTests(rootPath.getFile().toPath()); Response topoAResponse = handler.downloadDumpFile("../", "localhost:../l...
@Override public BroadcastRuleConfiguration buildToBeAlteredRuleConfiguration(final DropBroadcastTableRuleStatement sqlStatement) { BroadcastRuleConfiguration result = new BroadcastRuleConfiguration(new HashSet<>(rule.getConfiguration().getTables())); Collection<String> toBeDroppedTableNames = new C...
@Test void assertUpdateCurrentRuleConfiguration() { BroadcastRuleConfiguration config = new BroadcastRuleConfiguration(new LinkedList<>()); config.getTables().add("t_address"); BroadcastRule rule = mock(BroadcastRule.class); when(rule.getConfiguration()).thenReturn(config); e...
@VisibleForTesting protected RESTRequestInterceptor createRequestInterceptorChain() { return RouterServerUtil.createRequestInterceptorChain(conf, YarnConfiguration.ROUTER_WEBAPP_INTERCEPTOR_CLASS_PIPELINE, YarnConfiguration.DEFAULT_ROUTER_WEBAPP_INTERCEPTOR_CLASS, RESTRequestInterceptor.cl...
@Test public void testRequestInterceptorChainCreation() throws Exception { RESTRequestInterceptor root = super.getRouterWebServices().createRequestInterceptorChain(); int index = 0; while (root != null) { // The current pipeline is: // PassThroughRESTRequestInterceptor - index = 0 ...
public static RSAPublicKey parseRSAPublicKey(String pem) throws ServletException { String fullPem = PEM_HEADER + pem + PEM_FOOTER; PublicKey key = null; try { CertificateFactory fact = CertificateFactory.getInstance("X.509"); ByteArrayInputStream is = new ByteArrayInputStream( fullPem....
@Test public void testCorruptPEM() throws Exception { String pem = "MIICOjCCAaOgAwIBAgIJANXi/oWxvJNzMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAlVTMQ0w" + "CwYDVQQIEwRUZXN0MQ0wCwYDVQQHEwRUZXN0MQ8wDQYDVQQKEwZIYWRvb3AxDTALBgNVBAsTBFRl" + "c3QxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xNTAxMDIyMTE5MjRaFw0xNjAxMDIyMTE5...
static ByteSource asByteSource(ZipFile file, ZipEntry entry) { return new ZipEntryByteSource(file, entry); }
@Test public void testAsByteSource() throws Exception { File zipDir = new File(tmpDir, "zip"); assertTrue(zipDir.mkdirs()); createFileWithContents(zipDir, "myTextFile.txt", "Simple Text"); ZipFiles.zipDirectory(tmpDir, zipFile); try (ZipFile zip = new ZipFile(zipFile)) { ZipEntry entry = z...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedRead() { String[] forwardedFields = {"f0->f0;f1->f2"}; String[] readFields = {"f0; f2"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, forwardedFields, null, readF...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path f : files.keySet()) { if(f.isPlaceholder()) { log.warn(String.format("Ignore placeholder %s", f)); con...
@Test public void testDeleteMultipleFiles() throws Exception { final DriveFileIdProvider fileid = new DriveFileIdProvider(session); final Path folder = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), Enu...
public static URI parse(String featureIdentifier) { requireNonNull(featureIdentifier, "featureIdentifier may not be null"); if (featureIdentifier.isEmpty()) { throw new IllegalArgumentException("featureIdentifier may not be empty"); } // Legacy from the Cucumber Eclipse plug...
@Test void can_parse_eclipse_plugin_default_glue() { // The eclipse plugin uses `classpath:` as the default URI uri = FeaturePath.parse("classpath:"); assertAll( () -> assertThat(uri.getScheme(), is("classpath")), () -> assertThat(uri.getSchemeSpecificPart(), is("/")...
public String getTableCat() { return tableCat; }
@Test public void testGetTableCat() { ColumnMeta columnMeta = new ColumnMeta(); columnMeta.setTableCat("tableCat"); assertEquals(columnMeta.getTableCat(), "tableCat".trim()); }
@Override public ExecuteContext before(ExecuteContext context) { Object object = context.getObject(); if (object instanceof BaseLoadBalancer) { List<Object> serverList = getServerList(context.getMethod().getName(), object); if (CollectionUtils.isEmpty(serverList)) { ...
@Test public void testBeforeWhenInvalid() { // configService.setInvalid(true); interceptor.before(context); BaseLoadBalancer loadBalancer = (BaseLoadBalancer) context.getObject(); List<Server> servers = loadBalancer.getAllServers(); Assert.assertNotNull(servers); ...
@Override public SchemaKTable<K> select( final List<ColumnName> keyColumnNames, final List<SelectExpression> selectExpressions, final Stacker contextStacker, final PlanBuildContext buildContext, final FormatInfo valueFormat ) { final TableSelect<K> step = ExecutionStepFactory.table...
@Test public void testSelectWithExpression() { // Given: final String selectQuery = "SELECT col0, col3*3+5 FROM test2 WHERE col0 > 100 EMIT CHANGES;"; final PlanNode logicalPlan = buildLogicalPlan(selectQuery); final ProjectNode projectNode = (ProjectNode) logicalPlan.getSources().get(0); initialS...
@Override public String getConfigDirectory() { final String configDir = flinkConfig .getOptional(DeploymentOptionsInternal.CONF_DIR) .orElse(flinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR)); checkNotNull(configDir); ret...
@Test void getConfigDirectoryFallbackToPodConfDir() { final String confDirInPod = flinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR); assertThat(testingKubernetesParameters.getConfigDirectory()).isEqualTo(confDirInPod); }
public TaskRunHistory getTaskRunHistory() { return taskRunManager.getTaskRunHistory(); }
@Test public void testForceGC2() { TaskRunManager taskRunManager = new TaskRunManager(); for (int i = 0; i < 10; i++) { TaskRunStatus taskRunStatus = new TaskRunStatus(); taskRunStatus.setQueryId("test" + i); taskRunStatus.setTaskName("test" + i); task...
@Override public StorageObject upload(final Path file, Local local, final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final ConnectionCallback prompt) throws BackgroundException { if(this.threshold(status)) { try { ...
@Test public void testUploadSinglePartEuCentral() throws Exception { final S3ThresholdUploadService service = new S3ThresholdUploadService(session, new S3AccessControlListFeature(session), 5 * 1024L); final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path...
@Override @ManagedOperation(description = "Adds the key to the store") public boolean add(String key) { if (cache.asMap().containsKey(key)) { return false; } else { cache.put(key, true); return true; } }
@Test void testAdd() { // add first key assertTrue(repo.add(key01)); assertTrue(repo.getCache().asMap().containsKey(key01)); // try to add the same key again assertFalse(repo.add(key01)); // try to add another one assertTrue(repo.add(key02)); assertT...
public static <T> void forward(CompletableFuture<T> source, CompletableFuture<T> target) { source.whenComplete(forwardTo(target)); }
@Test void testForwardExceptionally() { final CompletableFuture<String> source = new CompletableFuture<>(); final CompletableFuture<String> target = new CompletableFuture<>(); FutureUtils.forward(source, target); assertThat(source).isNotDone(); assertThat(target).isNotDone(...
public static CompletableFuture<Map<String, String>> labelFailure( final Throwable cause, final Context context, final Executor mainThreadExecutor, final Collection<FailureEnricher> failureEnrichers) { // list of CompletableFutures to enrich failure with labels fr...
@Test public void testLabelFailureWithInvalidEnricher() { // validate labelFailure by enricher with wrong outputKeys final Throwable cause = new RuntimeException("test exception"); final String invalidEnricherKey = "invalidKey"; final Set<FailureEnricher> failureEnrichers = new HashS...
@Override public Set<Tuple> zRangeWithScores(byte[] key, long start, long end) { if (executorService.getServiceManager().isResp3()) { return read(key, ByteArrayCodec.INSTANCE, ZRANGE_ENTRY_V2, key, start, end, "WITHSCORES"); } return read(key, ByteArrayCodec.INSTANCE, ZRANGE_ENTR...
@Test public void testZRangeWithScores() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTe...
String getJwtFromBearerAuthorization(HttpServletRequest req) { String authorizationHeader = req.getHeader(HttpHeader.AUTHORIZATION.asString()); if (authorizationHeader == null || !authorizationHeader.startsWith(BEARER)) { return null; } else { return authorizationHeader.substring(BEARER.length()...
@Test public void testParseTokenFromAuthHeaderNoBearer() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(BASIC_SCHEME + " " + EXPECTED_T...
@Override public boolean isInStates(Set<String> statesFilter, long committedOffset) { return statesFilter.contains(state.toLowerCaseString()); }
@Test public void testIsInStates() { ClassicGroup group = new ClassicGroup(new LogContext(), "groupId", EMPTY, Time.SYSTEM, mock(GroupCoordinatorMetricsShard.class)); assertTrue(group.isInStates(Collections.singleton("empty"), 0)); group.transitionTo(PREPARING_REBALANCE); assertTrue...
@Override protected Future<KafkaBridgeStatus> createOrUpdate(Reconciliation reconciliation, KafkaBridge assemblyResource) { KafkaBridgeStatus kafkaBridgeStatus = new KafkaBridgeStatus(); String namespace = reconciliation.namespace(); KafkaBridgeCluster bridge; try { bri...
@Test public void testCreateOrUpdateThrowsWhenCreateServiceThrows(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true); var mockBridgeOps = supplier.kafkaBridgeOperator; DeploymentOperator mockDcOps = supplier.deploymentOperations; Pod...
public void cleanup(QueryId queryId) { queryPartitionFileCounterMap.remove(queryId); queryHiveMetadataResultMap.remove(queryId); }
@Test public void testCleanup() { HiveFileRenamer hiveFileRenamer = new HiveFileRenamer(); List<ConnectorMetadataUpdateHandle> requests = ImmutableList.of(TEST_HIVE_METADATA_UPDATE_REQUEST); List<ConnectorMetadataUpdateHandle> results = hiveFileRenamer.getMetadataUpdateResults(requests, ...
@Override public String pluginNamed() { return PluginEnum.LOGGING_TENCENT_CLS.getName(); }
@Test public void testPluginNamed() { Assertions.assertEquals(loggingTencentClsPluginDataHandler.pluginNamed(), PluginEnum.LOGGING_TENCENT_CLS.getName()); }
@Override public boolean implies(Permission permission) { if (permission instanceof FilePermission requestPermission) { return !blockedFilePermission.implies(requestPermission) || tmpFilePermission.implies(requestPermission); } return true; }
@Test public void policy_restricts_modifying_home() { assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "write"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "execute"))).isFalse(); ...
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testPartitionedTruncateString() throws Exception { createPartitionedTable(spark, tableName, "truncate(4, data)"); SparkScanBuilder builder = scanBuilder(); TruncateFunction.TruncateString function = new TruncateFunction.TruncateString(); UserDefinedScalarFunc udf = toUDF(fu...
static long sizeOf(Mutation m) { if (m.getOperation() == Mutation.Op.DELETE) { return sizeOf(m.getKeySet()); } long result = 0; for (Value v : m.getValues()) { switch (v.getType().getCode()) { case ARRAY: result += estimateArrayValue(v); break; case STRUCT...
@Test public void protos() throws Exception { Mutation empty = Mutation.newInsertOrUpdateBuilder("test") .set("one") .to(ByteArray.fromBase64(""), "customer.app.TestMessage") .build(); Mutation nullValue = Mutation.newInsertOrUpdateBuilder("test") ...
void release() { Arrays.stream(subpartitionCacheManagers).forEach(SubpartitionDiskCacheManager::release); partitionFileWriter.release(); }
@Test void testRelease() { AtomicBoolean isReleased = new AtomicBoolean(false); TestingTieredStorageMemoryManager memoryManager = new TestingTieredStorageMemoryManager.Builder().build(); TestingPartitionFileWriter partitionFileWriter = new TestingPartitionFile...
public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException { if ((defaultManagedBean == null && customManagedBean == null) || objectName == null) return null; // skip proxy classes if (defaultManagedBean != null && P...
@Test public void testNullInputs() throws JMException { // at least one of the first parameters should be not null assertThat(mbeanInfoAssembler.getMBeanInfo(null, null, "")).isNull(); // mbean should be not null assertThat(mbeanInfoAssembler.getMBeanInfo(testMbean, testMbean, null...
public String getShare() { return share; }
@Test void shareForValidURIShouldBeExtracted4() { var remoteConf = context.getEndpoint("azure-files://account/share/path", FilesEndpoint.class).getConfiguration(); assertEquals("share", remoteConf.getShare()); }
public void readChapterSubFrame(@NonNull FrameHeader frameHeader, @NonNull Chapter chapter) throws IOException, ID3ReaderException { Log.d(TAG, "Handling subframe: " + frameHeader.toString()); int frameStartPosition = getPosition(); switch (frameHeader.getId()) { case FRA...
@Test public void testReadTitleWithGarbage() throws IOException, ID3ReaderException { byte[] titleSubframeContent = { ID3Reader.ENCODING_ISO, 'A', // Title 0, // Null-terminated 42, 42, 42, 42 // Garbage, should be ignored }; Fr...
@Override public Optional<Request.RequestType> getRequestType() { return Optional.of(Request.RequestType.READ); }
@Test void testRequestType() throws Exception { IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1); generateComponentsConfigForActive(); configurer.reloadConfig(); SearchHandler newSearchHandler = fetchSearchHandler(configurer); try (RequestHandlerT...
public static Value that(Object actual) { return new Value(parseIfJsonOrXmlString(actual), true); }
@Test void testJavaSet() { Set<String> set = new HashSet(); set.add("foo"); set.add("bar"); Match.that(set).containsOnly("['foo', 'bar']"); }
@Override public CompletableFuture<T> toCompletableFuture() { return _task.toCompletionStage().toCompletableFuture(); }
@Test public void testToCompletableFuture_fail() throws Exception { CompletableFuture completableFuture = createTestFailedStage(EXCEPTION).toCompletableFuture(); try { completableFuture.get(); } catch (Exception e) { assertEquals(e.getCause(), EXCEPTION); } }
@Override protected TableOperations newTableOps(TableIdentifier tableIdentifier) { String fileIOImpl = DEFAULT_FILE_IO_IMPL; if (catalogProperties.containsKey(CatalogProperties.FILE_IO_IMPL)) { fileIOImpl = catalogProperties.get(CatalogProperties.FILE_IO_IMPL); } // Initialize a fresh FileIO fo...
@Test public void testTableNameFromTableOperations() { SnowflakeTableOperations castedTableOps = (SnowflakeTableOperations) catalog.newTableOps(TableIdentifier.of("DB_1", "SCHEMA_1", "TAB_1")); assertThat(castedTableOps.fullTableName()).isEqualTo("slushLog.DB_1.SCHEMA_1.TAB_1"); }
@Override public Flux<BooleanResponse<ExpireCommand>> expire(Publisher<ExpireCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Mono<Boolean> m = write(keyB...
@Test public void testExpiration() { RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson); ReactiveStringRedisTemplate t = new ReactiveStringRedisTemplate(factory); t.opsForValue().set("123", "4343").block(); t.expire("123", Duration.ofMillis(1001)).block(); ...
public static MongoSinkConfig load(String yamlFile) throws IOException { final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final MongoSinkConfig cfg = mapper.readValue(new File(yamlFile), MongoSinkConfig.class); return cfg; }
@Test public void testLoadYamlConfig() throws IOException { final File yaml = TestHelper.getFile(MongoSinkConfigTest.class, "mongoSinkConfig.yaml"); final MongoSinkConfig cfg = MongoSinkConfig.load(yaml.getAbsolutePath()); assertEquals(cfg.getMongoUri(), TestHelper.URI); assertEqual...
@Override public Boolean trySample(MessagingRequest request) { return delegate.trySample(request); }
@Test void nullOnNull() { assertThat(sampler.trySample(null)) .isNull(); }
@Override public MetricsCollector create(final MetricConfiguration metricConfig) { switch (metricConfig.getType()) { case COUNTER: return new PrometheusMetricsCounterCollector(metricConfig); case GAUGE: return new PrometheusMetricsGaugeCollector(metric...
@Test void assertCreateSummaryCollector() { MetricConfiguration config = new MetricConfiguration("test_summary", MetricCollectorType.SUMMARY, null, Collections.emptyList(), Collections.emptyMap()); assertThat(new PrometheusMetricsCollectorFactory().create(config), instanceOf(PrometheusMetricsSummary...
@VisibleForTesting static byte[] padBigEndianBytes(byte[] bigEndianBytes, int newLength) { if (bigEndianBytes.length == newLength) { return bigEndianBytes; } else if (bigEndianBytes.length < newLength) { byte[] result = new byte[newLength]; if (bigEndianBytes.length == 0) { return re...
@Test public void testPadBigEndianBytesNegative() { BigInteger bigInt = new BigInteger("-12345"); byte[] bytes = bigInt.toByteArray(); byte[] paddedBytes = DecimalVectorUtil.padBigEndianBytes(bytes, 16); assertThat(paddedBytes).hasSize(16); BigInteger result = new BigInteger(paddedBytes); ass...
public static <T> CompletionStage<T> recover(CompletionStage<T> completionStage, Function<Throwable, T> exceptionHandler){ return completionStage.exceptionally(exceptionHandler); }
@Test public void shouldReturnExceptionFromRecoveryMethod() { CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException("bla")); RuntimeException exception = new RuntimeException("blub"); Function<Throwable, String> fallback = (...
@Nonnull @Override public ILogger getLogger(@Nonnull String name) { checkNotNull(name, "name must not be null"); return getOrPutIfAbsent(mapLoggers, name, loggerConstructor); }
@Test public void testLog_whenGetLevel_thenDefaultLevelIsReturned() { ILogger logger = loggingService.getLogger("test"); assertNotNull(logger.getLevel()); }
static Map<Address, List<Shard>> assignShards(Collection<Shard> shards, Collection<Address> addresses) { Map<String, List<String>> assignment = addresses.stream() // host -> [indexShard...] .map(Address::getHost).distinct().collect(toMap(identity(), a -> new ArrayList<>())); Map<String,...
@Test public void given_multipleReplicasForEachShard_when_assignShards_then_shouldAssignOneReplicaOnly() { List<Shard> shards = newArrayList( new Shard("elastic-index", 0, Prirep.p, 10, "STARTED", "10.0.0.1", "10.0.0.1:9200", "node1"), new Shard("elastic-index", 0, Prirep.r, ...
public RepositoryElementInterface dataNodeToElement( DataNode rootNode ) throws KettleException { SlaveServer slaveServer = new SlaveServer(); dataNodeToElement( rootNode, slaveServer ); return slaveServer; }
@Test public void testDataNodeToElement() throws KettleException { SlaveServer slaveServer = new SlaveServer(); slaveDelegate.dataNodeToElement( mockDataNode, slaveServer ); Assert.assertEquals( PROP_HOST_NAME_VALUE, slaveServer.getHostname() ); Assert.assertEquals( PROP_USERNAME_VALUE, slaveServer.ge...
public static void trimRecordTemplate(RecordTemplate recordTemplate, MaskTree override, final boolean failOnMismatch) { trimRecordTemplate(recordTemplate.data(), recordTemplate.schema(), override, failOnMismatch); }
@Test public void testUnionDataMap() throws CloneNotSupportedException { UnionTest foo = new UnionTest(); foo.setUnionEmpty(new UnionTest.UnionEmpty()); UnionTest expected = foo.copy(); ((DataMap) foo.getUnionEmpty().data()).put("foo", "bar"); RestUtils.trimRecordTemplate(foo, false); Asse...
public long minOffset(MessageQueue mq) throws MQClientException { return this.mQClientFactory.getMQAdminImpl().minOffset(mq); }
@Test public void testMinOffset() throws MQClientException { assertEquals(0, defaultMQPushConsumerImpl.minOffset(createMessageQueue())); }
public CompletionStage<Void> migrate(MigrationSet set) { InterProcessLock lock = new InterProcessSemaphoreMutex(client.unwrap(), ZKPaths.makePath(lockPath, set.id())); CompletionStage<Void> lockStage = lockAsync(lock, lockMax.toMillis(), TimeUnit.MILLISECONDS, executor); return lockStage.thenCom...
@Test public void testChecksumPathError() { CuratorOp op1 = client.transactionOp().create().forPath("/test2"); CuratorOp op2 = client.transactionOp().create().forPath("/test2/bar"); Migration migration = () -> Arrays.asList(op1, op2); MigrationSet migrationSet = MigrationSet.build("1...
@VisibleForTesting static Document buildQuery(TupleDomain<ColumnHandle> tupleDomain) { Document query = new Document(); if (tupleDomain.getDomains().isPresent()) { for (Map.Entry<ColumnHandle, Domain> entry : tupleDomain.getDomains().get().entrySet()) { MongoColumnHan...
@Test public void testBuildQueryOr() { TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of( COL1, Domain.create(ValueSet.ofRanges(lessThan(BIGINT, 100L), greaterThan(BIGINT, 200L)), false))); Document query = MongoSession.buildQuery(tupleDomain)...
void cleanExpiredRequestInQueue(final BlockingQueue<Runnable> blockingQueue, final long maxWaitTimeMillsInQueue) { while (true) { try { if (!blockingQueue.isEmpty()) { final Runnable runnable = blockingQueue.peek(); if (null == runnable) { ...
@Test public void testCleanExpiredRequestInQueue() throws Exception { BrokerFastFailure brokerFastFailure = new BrokerFastFailure(brokerController); BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); brokerFastFailure.cleanExpiredRequestInQueue(queue, 1); assertThat(queue....
public Map<String, String> build() { Map<String, String> builder = new HashMap<>(); configureFileSystem(builder); configureNetwork(builder); configureCluster(builder); configureSecurity(builder); configureOthers(builder); LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]", ...
@Test public void configureSecurity_whenHttpKeystoreProvided_shouldAddHttpProperties() throws Exception { Props props = minProps(true); File keystore = temp.newFile("keystore.p12"); File truststore = temp.newFile("truststore.p12"); File httpKeystore = temp.newFile("http-keystore.p12"); props.set(C...
@Override public void initialize(PulsarClient client) { this.pulsarClient = (PulsarClientImpl) client; ClientConfigurationData config = pulsarClient.getConfiguration(); if (config != null) { this.primaryAuthentication = config.getAuthentication(); this.primaryTlsTrust...
@Test public void testInitialize() throws Exception { String primary = "pulsar://localhost:6650"; String secondary = "pulsar://localhost:6651"; long failoverDelay = 10; long switchBackDelay = 10; long checkInterval = 1_000; ClientConfigurationData configurationData =...
@Override public Iterable<Link> getLinks() { checkPermission(LINK_READ); return store.getLinks(); }
@Test public void getLinks() { Link l1 = addLink(DID1, P1, DID2, P2, DIRECT); Link l2 = addLink(DID2, P2, DID1, P1, DIRECT); Link l3 = addLink(DID3, P3, DID2, P1, DIRECT); Link l4 = addLink(DID2, P1, DID3, P3, DIRECT); assertEquals("incorrect link count", 4, service.getLinkCo...
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test void testChainedGenericsNotInSuperclass() { // use TypeExtractor RichMapFunction<?, ?> function = new RichMapFunction<ChainedTwo<Integer>, ChainedTwo<Integer>>() { private static final long serialVersionUID = ...
public static List<String> getServerIdentities(X509Certificate x509Certificate) { List<String> names = new ArrayList<>(); for (CertificateIdentityMapping mapping : serverCertMapping) { List<String> identities = mapping.mapIdentity(x509Certificate); Log.debug("Certificate...
@Test public void testServerIdentitiesDnsSrv() throws Exception { // Setup fixture. final String subjectCommonName = "MySubjectCommonName"; final String subjectAltNameDnsSrv = "MySubjectAltNameXmppAddr"; final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( ...
public McastConfig setEgressInnerVlan(VlanId vlanId) { if (vlanId == null) { object.remove(EGRESS_INNER_VLAN); } else { object.put(EGRESS_INNER_VLAN, vlanId.toString()); } return this; }
@Test public void setEgressInnerVlan() { config.setEgressInnerVlan(EGRESS_INNER_VLAN_2); VlanId egressInnerVlan = config.egressInnerVlan(); assertNotNull("egressInnerVlan should not be null", egressInnerVlan); assertThat(egressInnerVlan, is(EGRESS_INNER_VLAN_2)); }
@Override public Map<String, Object> encode(Object object) throws EncodeException { if (object == null) { return Collections.emptyMap(); } try { ObjectParamMetadata metadata = getMetadata(object.getClass()); Map<String, Object> propertyNameToValue = new HashMap<String, Object>(); f...
@Test void defaultEncoder_acceptNullValue() { assertThat(encoder.encode(null)).as("Empty map should be returned") .isEqualTo(Collections.EMPTY_MAP); }
@Override public SelType binaryOps(SelOp op, SelType rhs) { if (rhs.type() == SelTypes.NULL) { if (op == SelOp.EQUAL || op == SelOp.NOT_EQUAL) { return rhs.binaryOps(op, this); } else { throw new UnsupportedOperationException( this.type() + " DO NOT support " + op + " for r...
@Test public void testBinaryOps() { SelType obj = SelLong.of(2); SelType res = one.binaryOps(SelOp.EQUAL, obj); assertEquals("BOOLEAN: false", res.type() + ": " + res); res = one.binaryOps(SelOp.NOT_EQUAL, obj); assertEquals("BOOLEAN: true", res.type() + ": " + res); res = one.binaryOps(SelOp....
@Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) throws Exception { if (ObjectHelper.isEmpty(remaining)) { throw new IllegalArgumentException("You must provide a channel for the Dynamic Router"); } ...
@Test void testCreateEndpointWithEmptyRemainingError() { component.setCamelContext(context); assertThrows(IllegalArgumentException.class, () -> component.createEndpoint("dynamic-router:testname", "", Collections.emptyMap())); }
@NonNull @Override public ConnectionFileName toPvfsFileName( @NonNull FileName providerFileName, @NonNull T details ) throws KettleException { // Determine the part of provider file name following the connection "root". // Use the transformer to generate the connection root provider uri. // Both uri...
@Test public void testToPvfsFileNameHandlesConnectionsWithDomainAndBuckets() throws Exception { // Example: SMB mockDetailsWithDomain( details1, "my-domain:8080" ); when( details1.hasBuckets() ).thenReturn( true ); String connectionRootProviderUriPrefix = "scheme1://my-domain:8080"; String restP...
@Override public Local create(final Path file) { return this.create(new UUIDRandomStringService().random(), file); }
@Test public void testCreateContainer() { final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator); final String s = System.getProperty("file.separator"); final Path file = new Path("/container", EnumSet.of(Path.Type.directory)); file.attributes...
@Override public Num calculate(BarSeries series, Position position) { Num stdDevPnl = standardDeviationCriterion.calculate(series, position); if (stdDevPnl.isZero()) { return series.zero(); } // SQN = (Average (PnL) / StdDev(PnL)) * SquareRoot(NumberOfTrades) Num ...
@Test public void calculateWithLosingLongPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series), Trade.buyAt(2, series), Trade.sellAt(5, series)...
@Override public void hardStop() { if (nodeLifecycle.tryToMoveTo(HARD_STOPPING)) { LOG.info("Hard stopping SonarQube"); hardStopImpl(); } }
@Test public void awaitTermination_blocks_until_all_processes_are_stopped() throws Exception { TestAppSettings settings = new TestAppSettings(); Scheduler underTest = startAll(settings); Thread awaitingTermination = new Thread(underTest::awaitTermination); awaitingTermination.start(); assertThat(...
public static void main( String[] args ) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ExtractText()).execute(args); System.exit(exitCode); }
@Test void testPDFBoxRepeatableSubcommandAddFileNameOutfileAppend(@TempDir Path tempDir) throws Exception { Path path = null; try { path = tempDir.resolve("outfile.txt"); Files.deleteIfExists(path); } catch (InvalidPathException ipe) ...
public static ParameterizedType collectionOf(Type elementType) { return parameterizedType(Collection.class, elementType); }
@Test public void createCollectionType() { ParameterizedType type = Types.collectionOf(Person.class); assertThat(type.getRawType()).isEqualTo(Collection.class); assertThat(type.getActualTypeArguments()).isEqualTo(new Type[] {Person.class}); }
public BlockFilter(Web3j web3j, Callback<String> callback) { super(web3j, callback); }
@Test public void testBlockFilter() throws Exception { EthLog ethLog = objectMapper.readValue( "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":[" + "\"0x31c2342b1e0b8ffda1507fbffddf213c4b3c1e819ff6a84b943faabb0ebf2403\"," ...
public Set<KsqlTopic> getSourceTopics() { return Collections.unmodifiableSet(sourceTopics); }
@Test public void shouldExtractJoinTopicsFromJoinSelect() { // Given: final Statement statement = givenStatement(String.format( "SELECT * FROM %s A JOIN %s B ON A.F1 = B.F1;", STREAM_TOPIC_1, STREAM_TOPIC_2 )); // When: extractor.process(statement, null); // Then: assertThat(extr...
@Deprecated public PassiveCompletableFuture<TaskExecutionState> deployLocalTask( @NonNull TaskGroup taskGroup) { return deployLocalTask( taskGroup, Thread.currentThread().getContextClassLoader(), emptyList()); }
@Test public void testThrowException() throws InterruptedException { TaskExecutionService taskExecutionService = server.getTaskExecutionService(); AtomicBoolean stopMark = new AtomicBoolean(false); long t1Sleep = 100; long t2Sleep = 50; long lowLagSleep = 50; long ...