focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public ConsumerRecords<K, V> poll(Duration timeout) { return poll(delegate.poll(timeout)); }
@Test void should_add_new_trace_headers_if_b3_missing() { consumer.addRecord(consumerRecord); Consumer<String, String> tracingConsumer = kafkaTracing.consumer(consumer); ConsumerRecords<String, String> poll = tracingConsumer.poll(10); assertThat(poll) .extracting(ConsumerRecord::headers) ....
@Override public Publisher<Exchange> to(String uri, Object data) { String streamName = requestedUriToStream.computeIfAbsent(uri, camelUri -> { try { String uuid = context.getUuidGenerator().generateUuid(); RouteBuilder.addRoutes(context, rb -> rb.from("reactive-st...
@Test public void testToFunctionWithExchange() throws Exception { context.start(); AtomicInteger value = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(1); Function<Object, Publisher<Exchange>> fun = crs.to("bean:hello"); Flowable.just(1, 2, 3).flatMap(fun::...
public String getNextId() { return String.format("%s-%d-%d", prefix, generatorInstanceId, counter.getAndIncrement()); }
@Test public void invalidZnode() throws Exception { store.put("/my/test/invalid", "invalid-number".getBytes(), Optional.of(-1L)); DistributedIdGenerator gen = new DistributedIdGenerator(coordinationService, "/my/test/invalid", "p"); // It should not get exception if content is there ...
@Udf public <T> List<T> except( @UdfParameter(description = "Array of values") final List<T> left, @UdfParameter(description = "Array of exceptions") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> distinctRightValues = new HashSet<>(right); fi...
@Test public void shouldReturnNullForNullExceptionArray() { final List<String> input2 = Arrays.asList("foo"); final List<String> result = udf.except(null, input2); assertThat(result, is(nullValue())); }
@Udf public <T> List<T> concat( @UdfParameter(description = "First array of values") final List<T> left, @UdfParameter(description = "Second array of values") final List<T> right) { if (left == null && right == null) { return null; } final int leftSize = left != null ? left.size() : 0; ...
@Test public void shouldReturnNullForNullLeftInput() { final List<String> input1 = Arrays.asList("foo"); final List<String> result = udf.concat(null, input1); assertThat(result, is(Arrays.asList("foo"))); }
@NotNull @Override public INode enrich(@NotNull INode node) { if (node instanceof AES aes) { return enrich(aes); } return node; }
@Test void oid() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); final AES aes = new AES(256, new ECB(testDetectionLocation), testDetectionLocation); this.logBefore(aes); final AESEnricher aesEnricher...
@Override public ConnectorPageSource createPageSource( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorSplit split, ConnectorTableLayoutHandle layout, List<ColumnHandle> columns, SplitContext splitContext, ...
@Test public void testAggregatedPageSource() { HivePageSourceProvider pageSourceProvider = createPageSourceProvider(); ConnectorPageSource pageSource = pageSourceProvider.createPageSource( new HiveTransactionHandle(), SESSION, getHiveSplit(ORC), ...
@Override public DescribeReplicaLogDirsResult describeReplicaLogDirs(Collection<TopicPartitionReplica> replicas, DescribeReplicaLogDirsOptions options) { final Map<TopicPartitionReplica, KafkaFutureImpl<DescribeReplicaLogDirsResult.ReplicaLogDirInfo>> futures = new HashMap<>(replicas.size()); for (...
@Test public void testDescribeReplicaLogDirsUnexpected() throws ExecutionException, InterruptedException { TopicPartitionReplica expected = new TopicPartitionReplica("topic", 12, 1); TopicPartitionReplica unexpected = new TopicPartitionReplica("topic", 12, 2); try (AdminClientUnitTestEnv en...
@Override public KTable<K, VOut> aggregate(final Initializer<VOut> initializer, final Materialized<K, VOut, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(initializer, NamedInternal.empty(), materialized); }
@Test public void shouldNotHaveNullNamedOnAggregate() { assertThrows(NullPointerException.class, () -> cogroupedStream.aggregate(STRING_INITIALIZER, (Named) null)); }
public synchronized void scheduleRequest(DataSize maxResponseSize) { if (closed || (future != null) || scheduled) { return; } scheduled = true; // start before scheduling to include error delay backoff.startRequest(); long delayNanos = backoff.getBackoff...
@Test public void testHappyPath() throws Exception { Page expectedPage = new Page(100); DataSize expectedMaxSize = new DataSize(11, Unit.MEGABYTE); MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(expectedMaxSize); CyclicBarrier requestCompl...
@Override public int readMediumLE() { int value = readUnsignedMediumLE(); if ((value & 0x800000) != 0) { value |= 0xff000000; } return value; }
@Test public void testReadMediumLEAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().readMediumLE(); } }); }
public CruiseConfig deserializeConfig(String content) throws Exception { String md5 = md5Hex(content); Element element = parseInputStream(new ByteArrayInputStream(content.getBytes())); LOGGER.debug("[Config Save] Updating config cache with new XML"); CruiseConfig configForEdit = classPa...
@Test void shouldLoadExecBuilder() throws Exception { CruiseConfig cruiseConfig = xmlLoader.deserializeConfig(CONFIG_WITH_NANT_AND_EXEC_BUILDER); JobConfig plan = cruiseConfig.jobConfigByName("pipeline1", "mingle", "cardlist", true); ExecTask builder = (ExecTask) plan.tasks().findFirstByTyp...
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}") public ApolloConfig queryConfig(@PathVariable String appId, @PathVariable String clusterName, @PathVariable String namespace, @RequestParam(value = "dataCenter", required = false) String da...
@Test public void testQueryConfigWithPubicNamespaceAndNoAppOverride() throws Exception { String someClientSideReleaseKey = "1"; String someServerSideReleaseKey = "2"; HttpServletResponse someResponse = mock(HttpServletResponse.class); String somePublicAppId = "somePublicAppId"; String somePublicCl...
public MonetaryFormat digits(char zeroDigit) { if (zeroDigit == this.zeroDigit) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed)...
@Test public void testDigits() { assertEquals("١٢.٣٤٥٦٧٨٩٠", NO_CODE.digits('\u0660').format(Coin.valueOf(1234567890l)).toString()); }
public static boolean subjectExists( final SchemaRegistryClient srClient, final String subject ) { return getLatestSchema(srClient, subject).isPresent(); }
@Test public void shouldReturnFalseOnSubjectMissing() throws Exception { // Given: when(schemaRegistryClient.getLatestSchemaMetadata("bar-value")).thenThrow( new RestClientException("foo", 404, SchemaRegistryUtil.SUBJECT_NOT_FOUND_ERROR_CODE) ); // When: final boolean subjectExists = Sche...
@Override public void onSwipeUp() {}
@Test public void testOnSwipeUp() { mUnderTest.onSwipeUp(); Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction); }
public SimpleRabbitListenerContainerFactory decorateSimpleRabbitListenerContainerFactory( SimpleRabbitListenerContainerFactory factory ) { return decorateRabbitListenerContainerFactory(factory); }
@Test void decorateSimpleRabbitListenerContainerFactory_adds_by_default() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .allMatch(advice -> advice instanceof Tra...
@Override public PathAttributes toAttributes(final DavResource resource) { final PathAttributes attributes = new PathAttributes(); final Map<QName, String> properties = resource.getCustomPropsNS(); if(null != properties && properties.containsKey(DAVTimestampFeature.LAST_MODIFIED_CUSTOM_NAMES...
@Test public void testCustomModified_NotSet() { final DAVAttributesFinderFeature f = new DAVAttributesFinderFeature(null); final DavResource mock = mock(DavResource.class); Map<QName, String> map = new HashMap<>(); final Date modified = new DateTime("2018-11-01T15:31:57Z").toDate();...
@VisibleForTesting static Object convertAvroField(Object avroValue, Schema schema) { if (avroValue == null) { return null; } switch (schema.getType()) { case NULL: case INT: case LONG: case DOUBLE: case FLOAT: ...
@Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = "Unsupported avro schema type.*") public void testNotSupportedAvroTypesMap() { BaseJdbcAutoSchemaSink.convertAvroField(new Object(), createFieldAndGetSchema((builder) -> builder.name...
public static final int getTrimTypeByDesc( String tt ) { if ( tt == null ) { return 0; } for ( int i = 0; i < trimTypeDesc.length; i++ ) { if ( trimTypeDesc[i].equalsIgnoreCase( tt ) ) { return i; } } // If this fails, try to match using the code. return getTrimTypeBy...
@Test public void testGetTrimTypeByDesc() { assertEquals( ValueMetaBase.getTrimTypeByDesc( BaseMessages.getString( PKG, "ValueMeta.TrimType.None" ) ), ValueMetaInterface.TRIM_TYPE_NONE ); assertEquals( ValueMetaBase.getTrimTypeByDesc( BaseMessages.getString( PKG, "ValueMeta.TrimType.Left" ) ), Val...
public String getClientReturnId(String sessionId) { Optional<OpenIdSession> session = openIdRepository.findById(sessionId); if (session.isEmpty()) return null; OpenIdSession openIdSession = session.get(); var returnUrl = openIdSession.getRedirectUri() + "?state=" + openIdSession.getSt...
@Test void getNoClientReturnIdTest() { OpenIdSession openIdSession = new OpenIdSession(); openIdSession.setAuthenticationState("success"); when(httpServletRequest.getSession()).thenReturn(httpSession); when(httpSession.getId()).thenReturn(null); when(openIdRepository.findByI...
public static DataPermission get() { return DATA_PERMISSIONS.get().peekLast(); }
@Test public void testGet() { // mock 方法 DataPermission dataPermission01 = mock(DataPermission.class); DataPermissionContextHolder.add(dataPermission01); DataPermission dataPermission02 = mock(DataPermission.class); DataPermissionContextHolder.add(dataPermission02); ...
@Override public int get(PageId pageId, int pageOffset, int bytesToRead, ReadTargetBuffer target, boolean isTemporary) throws IOException, PageNotFoundException { Callable<Integer> callable = () -> mPageStore.get(pageId, pageOffset, bytesToRead, target, isTemporary); try { return mTimeLimt...
@Test public void getTimeout() throws Exception { mPageStore.setGetHanging(true); try { mTimeBoundPageStore.get(PAGE_ID, 0, PAGE.length, new ByteArrayTargetBuffer(mBuf, 0)); fail(); } catch (IOException e) { assertTrue(e.getCause() instanceof TimeoutException); } }
static double estimatePixelCount(final Image image, final double widthOverHeight) { if (image.getHeight() == HEIGHT_UNKNOWN) { if (image.getWidth() == WIDTH_UNKNOWN) { // images whose size is completely unknown will be in their own subgroups, so // any one of them wil...
@Test public void testEstimatePixelCountAllUnknown() { assertEquals(0.0, estimatePixelCount(img(HEIGHT_UNKNOWN, WIDTH_UNKNOWN), 1.0 ), 0.0); assertEquals(0.0, estimatePixelCount(img(HEIGHT_UNKNOWN, WIDTH_UNKNOWN), 12.0 ), 0.0); assertEquals(0.0, estimatePixelCount(img(HEIGHT_UNKNOWN, ...
@Override public Repository getRepository() { //Repository may be null if executing remotely in Pentaho Server Repository repository = super.getRepository(); return repository != null ? repository : getTransMeta().getRepository(); }
@Test public void getRepositoryNotNullTest() { metaInject.setRepository( repository ); //If repository is set in the base step (Local Execution) TransMeta will not be required to get the repository metaInject.getRepository(); verify( metaInject, times( 0 ) ).getTransMeta(); }
protected String getUniqueKey(KeyTypeEnum keyType, String... params) { if (keyType == KeyTypeEnum.PATH) { return getFilePathKey(params); } return getIdentifierKey(params); }
@Test void getUniqueKey() { String uniqueKey = baseServiceMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY, "appName"); Assertions.assertEquals(uniqueKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName"); String uniqueKey2 = baseServiceMetadataIdentifier.getUniqueKey(K...
public TopicStatsImpl add(TopicStats ts) { TopicStatsImpl stats = (TopicStatsImpl) ts; this.count++; this.msgRateIn += stats.msgRateIn; this.msgThroughputIn += stats.msgThroughputIn; this.msgRateOut += stats.msgRateOut; this.msgThroughputOut += stats.msgThroughputOut; ...
@Test public void testAdd_EarliestMsgPublishTimeInBacklogs_Zero() { TopicStatsImpl stats1 = new TopicStatsImpl(); stats1.earliestMsgPublishTimeInBacklogs = 0L; TopicStatsImpl stats2 = new TopicStatsImpl(); stats2.earliestMsgPublishTimeInBacklogs = 0L; TopicStatsImpl aggrega...
@Override public void lock() { try { lockInterruptibly(-1, null); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testConcurrencyLoop_MultiInstance() throws InterruptedException { final int iterations = 100; final AtomicInteger lockedCounter = new AtomicInteger(); testMultiInstanceConcurrency(16, r -> { for (int i = 0; i < iterations; i++) { r.getSpinLock("...
public static <K, V> PTransform<PCollection<KV<K, V>>, PCollection<KV<K, ValueInSingleWindow<V>>>> windowsInValue() { return new WindowInValue<>(); }
@Test @Category(NeedsRunner.class) public void windowsInValueSucceeds() { PCollection<KV<String, Integer>> timestamped = pipeline .apply(Create.of(KV.of("foo", 0), KV.of("foo", 1), KV.of("bar", 2), KV.of("baz", 3))) .apply(TIMESTAMP_FROM_V); PCollection<KV<String, ValueInSin...
static void removeAllFromManagers(Iterable<DoFnLifecycleManager> managers) throws Exception { Collection<Exception> thrown = new ArrayList<>(); for (DoFnLifecycleManager manager : managers) { thrown.addAll(manager.removeAll()); } if (!thrown.isEmpty()) { Exception overallException = new Exce...
@Test public void removeAllWhenManagersThrowSuppressesAndThrows() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); DoFnLifecycleManager first = DoFnLifecycleManager.of(new ThrowsInCleanupFn("foo"), options); DoFnLifecycleManager second = DoFnLifecycleManager.of(new ThrowsInCle...
public Iterator<Optional<Page>> process(SqlFunctionProperties properties, DriverYieldSignal yieldSignal, LocalMemoryContext memoryContext, Page page) { WorkProcessor<Page> processor = createWorkProcessor(properties, yieldSignal, memoryContext, page); return processor.yieldingIterator(); }
@Test public void testProjectEmptyPage() { PageProcessor pageProcessor = new PageProcessor(Optional.of(new SelectAllFilter()), ImmutableList.of(createInputPageProjectionWithOutputs(0, BIGINT, 0))); Page inputPage = new Page(createLongSequenceBlock(0, 0)); LocalMemoryContext memoryConte...
@SuppressWarnings("argument") static Status runSqlLine( String[] args, @Nullable InputStream inputStream, @Nullable OutputStream outputStream, @Nullable OutputStream errorStream) throws IOException { String[] modifiedArgs = checkConnectionArgs(args); SqlLine sqlLine = new SqlLine...
@Test public void testSqlLine_GroupBy() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String[] args = buildArgs( "CREATE EXTERNAL TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test';", "INSERT INTO table_test SELECT '3', '...
protected File getOutputFile(final String path, final String baseFileName) throws IOException { makeDir(path); final String now = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()); final String fileName = baseFileName + "." + now; final File file = Paths.get(path, fileName)....
@Test public void testGetOutputFileWithPath() throws IOException { final String path = "abc"; final File f = getOutputFile(path, "test2.log"); assertTrue(f.exists()); FileUtils.forceDelete(new File(path)); }
public synchronized Stream updateStreamState(String streamId, Stream.State state) { LOG.info("Updating {}'s state to {} in project {}.", streamId, state.name(), projectId); try { Stream.Builder streamBuilder = Stream.newBuilder() .setName(StreamName.format(projectId, location, st...
@Test public void testUpdateStreamStateExecutionExceptionShouldFail() throws ExecutionException, InterruptedException { when(datastreamClient.updateStreamAsync(any(UpdateStreamRequest.class)).get()) .thenThrow(ExecutionException.class); DatastreamResourceManagerException exception = asse...
public boolean accept(final T t) { checkContext(); if (isComplete() || hasSentComplete()) { throw new IllegalStateException("Cannot call accept after complete is called"); } if (!isCancelled() && !isFailed()) { if (getDemand() == 0) { buffer.add(t); } else { doOnNext(t)...
@Test public void shouldAcceptBuffered() throws Exception { publisher = new BufferedPublisher<>(context, 5); AsyncAssert asyncAssert = new AsyncAssert(); for (int i = 0; i < 10; i++) { String record = expectedValue(i); final int index = i; execOnContextAndWait(() -> { boolean buf...
void checkSupportedCipherSuites() { if (getSupportedCipherSuites() == null) { setSupportedCipherSuites(Collections.singletonList(HTTP2_DEFAULT_CIPHER)); } else if (!getSupportedCipherSuites().contains(HTTP2_DEFAULT_CIPHER)) { throw new IllegalArgumentException("HTTP/2 server conf...
@Test void testCustomCiphersAreSupported() { http2ConnectorFactory.setSupportedCipherSuites(Arrays.asList("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")); http2ConnectorFactory.checkSupportedCipherSuites(); assertThat(http2ConnectorFactory...
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) { String json = reader.readLine(); log.debug("Converting response from influxDb: {}", json); Map result = getResultObject...
@Test public void deserializeWithFloatValues() throws Exception { List<InfluxDbResult> results = setupWithFloats(); TypedInput input = new TypedByteArray(MIME_TYPE, EXAMPLE_WITH_FLOATS.getBytes()); List<InfluxDbResult> result = (List<InfluxDbResult>) influxDbResponseConverter.fromBody(input, List....
public void isAssignableTo(Class<?> clazz) { if (!clazz.isAssignableFrom(checkNotNull(actual))) { failWithActual("expected to be assignable to", clazz.getName()); } }
@Test public void testIsAssignableTo_reversed() { expectFailureWhenTestingThat(Object.class).isAssignableTo(String.class); assertFailureValue("expected to be assignable to", "java.lang.String"); }
@VisibleForTesting boolean isThreadDumpCaptured() { return isThreadDumpCaptured; }
@Test(timeout=60000) public void testThreadDumpCaptureAfterNNStateChange() throws Exception { startCluster(); MockNameNodeResourceChecker mockResourceChecker = new MockNameNodeResourceChecker(conf); mockResourceChecker.setResourcesAvailable(false); cluster.getNameNode(0).getNamesystem() ...
protected static boolean isValidValue(Field f, Object value) { if (value != null) { return true; } Schema schema = f.schema(); Type type = schema.getType(); // If the type is null, any value is valid if (type == Type.NULL) { return true; } // If the type is a union that al...
@Test void isValidValueWithPrimitives() { // Verify that a non-null value is valid for all primitives: for (Type type : primitives) { Field f = new Field("f", Schema.create(type), null, null); assertTrue(RecordBuilderBase.isValidValue(f, new Object())); } // Verify that null is not valid ...
public static boolean isApplicationEntity(TimelineEntity te) { return (te == null ? false : te.getType().equals(TimelineEntityType.YARN_APPLICATION.toString())); }
@Test void testIsApplicationEntity() { TimelineEntity te = new TimelineEntity(); te.setType(TimelineEntityType.YARN_APPLICATION.toString()); assertTrue(ApplicationEntity.isApplicationEntity(te)); te = null; assertEquals(false, ApplicationEntity.isApplicationEntity(te)); te = new TimelineEnti...
@Override protected List<Object[]> rows() { List<Object[]> rows = new ArrayList<>(dataConnectionCatalogEntries.size()); for (DataConnectionCatalogEntry dl : dataConnectionCatalogEntries) { final Map<String, String> options; if (!securityEnabled) { options = dl...
@Test public void test_rows() { // given DataConnectionCatalogEntry dc = new DataConnectionCatalogEntry( "dc-name", "dc-type", false, singletonMap("key", "value") ); DataConnectionsTable dcTable = new DataConnectionsTab...
public boolean poll(Timer timer, boolean waitForJoinGroup) { maybeUpdateSubscriptionMetadata(); invokeCompletedOffsetCommitCallbacks(); if (subscriptions.hasAutoAssignedPartitions()) { if (protocol == null) { throw new IllegalStateException("User configured " + Cons...
@Test public void testAutoCommitManualAssignment() { try (ConsumerCoordinator coordinator = buildCoordinator(rebalanceConfig, new Metrics(), assignors, true, subscriptions)) { subscriptions.assignFromUser(singleton(t1p)); subscriptions.seek(t1p, 100); client.prepareRespon...
@Override public void afterMethod(final TargetAdviceObject target, final TargetAdviceMethod method, final Object[] args, final Object result, final String pluginType) { if (null == result) { return; } for (RouteUnit each : ((RouteContext) result).getRouteUnits()) { Me...
@Test void assertCountRouteResult() { RouteContext routeContext = new RouteContext(); RouteMapper dataSourceMapper = new RouteMapper("logic_db", "ds_0"); RouteMapper tableMapper = new RouteMapper("t_order", "t_order_0"); routeContext.getRouteUnits().add(new RouteUnit(dataSourceMapper...
public static void boundsCheck(int capacity, int index, int length) { if (capacity < 0 || index < 0 || length < 0 || (index > (capacity - length))) { throw new IndexOutOfBoundsException(String.format("index=%d, length=%d, capacity=%d", index, length, capacity)); } }
@Test(expected = IndexOutOfBoundsException.class) public void boundsCheck_whenIndexIntegerMax() { //Testing wrapping does not cause false check ArrayUtils.boundsCheck(100, Integer.MAX_VALUE, 1); }
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.0"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName();...
@Test public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { String expiration1 = "2014-09-10T22:49:44.090+00:00"; Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); when(mockedCl...
public boolean isOlderOrEqualTo(VersionNumber versionNumber) { return equals(versionNumber) || isOlderThan(versionNumber); }
@Test void testIsOlderOrEqualTo() { assertThat(v("6.0.0").isOlderOrEqualTo(v("6.0.0"))).isTrue(); assertThat(v("5.0.0").isOlderOrEqualTo(v("6.0.0"))).isTrue(); assertThat(v("9.0.0").isOlderOrEqualTo(v("10.0.0"))).isTrue(); assertThat(v("1.0.0").isOlderOrEqualTo(v("10.0.0"))).isTrue()...
@Override public boolean allowsUsersToSignUp() { return settings.allowUsersToSignUp(); }
@Test public void should_allow_users_to_signup() { assertThat(underTest.allowsUsersToSignUp()).as("default").isFalse(); settings.setProperty("sonar.auth.github.allowUsersToSignUp", true); assertThat(underTest.allowsUsersToSignUp()).isTrue(); }
@PostMapping("/authorize") @Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用") @Parameters({ @Parameter(name = "response_type", required = true, description = "响应类型", example = "code"), @Parameter(name = "client_id", required = true, descr...
@Test // autoApprove = true,通过 + token public void testApproveOrDeny_autoApproveWithToken() { // 准备参数 String responseType = "token"; String clientId = randomString(); String scope = "{\"read\": true, \"write\": false}"; String redirectUri = "https://www.iocoder.cn"; S...
@Override public boolean isFragmentAutoTrackAppViewScreen(Class<?> fragment) { return mFragmentAPI.isFragmentAutoTrackAppViewScreen(fragment); }
@Test public void isFragmentAutoTrackAppViewScreen() { setUp(); mAutoTrackImp.trackFragmentAppViewScreen(); Assert.assertTrue(mAutoTrackImp.isTrackFragmentAppViewScreenEnabled()); }
@Override public double variance() { return k * theta * theta; }
@Test public void testVariance() { System.out.println("variance"); GammaDistribution instance = new GammaDistribution(3, 2.1); instance.rand(); assertEquals(13.23, instance.variance(), 1E-7); }
@Override public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) { ServerHttpResponse response = exchange.getResponse(); long calculatedMaxAgeInSeconds = calculateMaxAgeInSeconds(exchange.getRequest(), cachedResponse, configuredTimeToLive); rewriteCacheControlMaxAge(response.getHeaders...
@Test void otherHeadersAreNotRemoved_whenMaxAgeIsModified() { inputExchange.getResponse().getHeaders().put("X-Custom-Header", List.of("DO-NOT-REMOVE")); Duration timeToLive = Duration.ofSeconds(30); CachedResponse inputCachedResponse = CachedResponse.create(HttpStatus.OK).timestamp(clock.instant()).build(); S...
public ConsumerBuilder<T> batchReceivePolicy(BatchReceivePolicy batchReceivePolicy) { checkArgument(batchReceivePolicy != null, "batchReceivePolicy must not be null."); batchReceivePolicy.verify(); conf.setBatchReceivePolicy(batchReceivePolicy); return this; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testConsumerBuilderImplWhenBatchReceivePolicyIsNotValid() { consumerBuilderImpl.batchReceivePolicy(BatchReceivePolicy.builder() .maxNumMessages(0) .maxNumBytes(0) .timeout(0, TimeUnit.MILLI...
@Override public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() { Iterable<RedisClusterNode> res = clusterGetNodes(); Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>(); for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator....
@Test public void testClusterGetMasterSlaveMap() { Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap(); assertThat(map).hasSize(3); for (Collection<RedisClusterNode> slaves : map.values()) { assertThat(slaves).hasSize(1); } ...
@SuppressWarnings("checkstyle:npathcomplexity") public PartitionServiceState getPartitionServiceState() { PartitionServiceState state = getPartitionTableState(); if (state != SAFE) { return state; } if (!checkAndTriggerReplicaSync()) { return REPLICA_NOT_SYN...
@Test public void shouldNotBeSafe_whenUnknownReplicaOwnerPresent() throws UnknownHostException { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz = factory.newHazelcastInstance(); InternalPartitionServiceImpl partitionService = getNode(hz).partiti...
@Override public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext) { doEvaluateDisruptContext(request, requestContext); return _client.sendRequest(request, requestContext); }
@Test public void testSendRequest3() { when(_controller.getDisruptContext(any(String.class), any(ResourceMethod.class))).thenReturn(_disrupt); _client.sendRequest(_request, _context, _behavior); verify(_underlying, times(1)).sendRequest(eq(_request), eq(_context), eq(_behavior)); verify(_context, ti...
@Override @Cacheable(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#id", unless = "#result == null") public MailAccountDO getMailAccountFromCache(Long id) { return getMailAccount(id); }
@Test public void testGetMailAccountFromCache() { // mock 数据 MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class); mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbMailAccount.getId(); // 调用 MailAccountDO mailAccount =...
@Override public final void isEqualTo(@Nullable Object other) { if (Objects.equal(actual, other)) { return; } // Fail but with a more descriptive message: if (actual == null || !(other instanceof Map)) { super.isEqualTo(other); return; } containsEntriesInAnyOrder((Map<?, ?...
@Test public void isEqualToNonMap() { ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3); expectFailureWhenTestingThat(actual).isEqualTo("something else"); assertFailureKeys("expected", "but was"); }
public static void verifyKafkaBrokers(Properties props) { //ensure bootstrap.servers is assigned String brokerList = getString(BOOTSTRAP_SERVERS_CONFIG, props); //usually = "bootstrap.servers" String[] brokers = brokerList.split(","); for (String broker : brokers) { checkAr...
@Test public void verifyKafkaBrokers_happyPath_multipleBrokers() { Properties props = new Properties(); props.setProperty("bootstrap.servers", "localhost:9092,myhost.com:9091"); //does nothing when input is valid verifyKafkaBrokers(props); }
@Override public boolean containsAll(Collection<?> c) { for (Object object : c) { if (!contains(object)) { return false; } } return true; }
@Test public void testContainsAll() { Set<Integer> set = redisson.getSortedSet("set"); for (int i = 0; i < 200; i++) { set.add(i); } Assertions.assertTrue(set.containsAll(Arrays.asList(30, 11))); Assertions.assertFalse(set.containsAll(Arrays.asList(30, 711, 11)))...
@Override public Result analysis( final Result result, final StreamAccessLogsMessage.Identifier identifier, final HTTPAccessLogEntry entry, final Role role ) { switch (role) { case PROXY: return analyzeProxy(result, entry); case SID...
@Test public void testIngressMetric() throws IOException { try (InputStreamReader isr = new InputStreamReader(getResourceAsStream("envoy-ingress.msg"))) { StreamAccessLogsMessage.Builder requestBuilder = StreamAccessLogsMessage.newBuilder(); JsonFormat.parser().merge(isr, requestBuil...
@Override public boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionState) { return state.tryCall( StateWithExecutionGraph.class, stateWithExecutionGraph -> stateWithExecutionGraph.updateTaskExecutionStat...
@Test void testExceptionHistoryWithTaskFailureLabels() throws Exception { final Exception taskException = new Exception("Task Exception"); BiConsumer<AdaptiveScheduler, List<ExecutionAttemptID>> testLogic = (scheduler, attemptIds) -> { final ExecutionAttemptID att...
@Override public void execute(GraphModel graphModel) { Graph graph = graphModel.getGraphVisible(); execute(graph); }
@Test public void testOneNodeDegree() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1); Graph graph = graphModel.getGraph(); Node n = graph.getNode("0"); WeightedDegree d = new WeightedDegree(); d.execute(graph); assertEquals(n.getAttribute(Wei...
public static String getType(String fileStreamHexHead) { if(StrUtil.isBlank(fileStreamHexHead)){ return null; } if (MapUtil.isNotEmpty(FILE_TYPE_MAP)) { for (final Entry<String, String> fileTypeEntry : FILE_TYPE_MAP.entrySet()) { if (StrUtil.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())...
@Test @Disabled public void inputStreamAndFilenameTest() { final File file = FileUtil.file("e:/laboratory/test.xlsx"); final String type = FileTypeUtil.getType(file); assertEquals("xlsx", type); }
@Override public boolean contains(K name) { return false; }
@Test public void testContains() { assertFalse(HEADERS.contains("name1")); }
public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException { UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream))); return parser.parse(); }
@Test public void testSimpleParse2() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(UnifiedDiffReaderTest.class.getResourceAsStream("jsqlparser_patch_1.diff")); System.out.println(diff); assertThat(diff.getFiles().size()).isEqualTo(2); UnifiedDiffFile f...
@JsonCreator public static ClosingRetentionStrategyConfig create(@JsonProperty(TYPE_FIELD) String type, @JsonProperty("max_number_of_indices") @Min(1) int maxNumberOfIndices) { return new AutoValue_ClosingRetentionStrategyConfig(type, maxNumberOfIndice...
@Test public void testSerialization() throws JsonProcessingException { final ClosingRetentionStrategyConfig config = ClosingRetentionStrategyConfig.create(20); final ObjectMapper objectMapper = new ObjectMapperProvider().get(); final String json = objectMapper.writeValueAsString(config); ...
@Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionParser optParser = new OptionParser(); OptionSpec<Long> offsetOpt = optParser.accepts("offset", "offset for reading input").withRequiredArg() .ofType(Long.class).defaultsTo(Long.value...
@Test void limitOutOfBounds() throws Exception { Map<String, String> metadata = new HashMap<>(); metadata.put("myMetaKey", "myMetaValue"); File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE); File output = new File(DIR, name.getMethodName() + ".avro"); output.deleteOnExit(); ...
@Override void executeTask() throws UserException { LOG.info("begin to execute broker pending task. job: {}", callback.getCallbackId()); getAllFileStatus(); }
@Test public void testExecuteTask(@Injectable BrokerLoadJob brokerLoadJob, @Injectable BrokerFileGroup brokerFileGroup, @Injectable BrokerDesc brokerDesc, @Mocked GlobalStateMgr globalStateMgr, ...
public float toFloat(String name) { return toFloat(name, 0.0f); }
@Test public void testToFloat_String() { System.out.println("toFloat"); float expResult; float result; Properties props = new Properties(); props.put("value1", "12345.6789"); props.put("value2", "-9000.001"); props.put("empty", ""); props.put("str", "...
public static boolean isNumber(String text) { final int startPos = findStartPosition(text); if (startPos < 0) { return false; } for (int i = startPos; i < text.length(); i++) { char ch = text.charAt(i); if (!Character.isDigit(ch)) { re...
@Test @DisplayName("Tests that isNumber returns false for empty, space or null") void isNumberEmpty() { assertFalse(ObjectHelper.isNumber("")); assertFalse(ObjectHelper.isNumber(" ")); assertFalse(ObjectHelper.isNumber(null)); }
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldLoadFunctionWithStructSchemaProvider() { // Given: final UdfFactory returnDecimal = FUNC_REG.getUdfFactory(FunctionName.of("KsqlStructUdf")); // When: final List<SqlArgument> args = ImmutableList.of(); final KsqlScalarFunction function = returnDecimal.getFunction(args); ...
static long calculateGrouping(Set<Integer> groupingSet, List<Integer> columns) { long grouping = (1L << columns.size()) - 1; for (int index = 0; index < columns.size(); index++) { int column = columns.get(index); if (groupingSet.contains(column)) { // Leftmo...
@Test public void testGroupingOperationSomeBitsSet() { List<Integer> groupingOrdinals = ImmutableList.of(7, 2, 9, 3, 5); List<Set<Integer>> groupingSetOrdinals = ImmutableList.of(ImmutableSet.of(4, 2), ImmutableSet.of(9, 7, 14), ImmutableSet.of(5, 2, 7), ImmutableSet.of(3)); List<Long> e...
@Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { return inliner .importPolicy() .staticReference( inliner, classIdent().getTopLevelClass(), classIdent().getName(), getName()); }
@Test public void inline() { ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL); assertInlines( "Integer.valueOf", UStaticIdent.create( "java.lang.Integer", "valueOf", UMethodType.create( UClassType.create("java.lang.Integer"), UClassT...
void addIndexSchema(long shadowIdxId, long originIdxId, @NotNull String shadowIndexName, short shadowIdxShortKeyCount, @NotNull List<Column> shadowIdxSchema) { indexIdMap.put(shadowIdxId, originIdxId); indexIdToName.put(shadowIdxId, shadowIndexName); ...
@Test public void testShow() { new MockUp<WarehouseManager>() { @Mock public Warehouse getWarehouseAllowNull(long warehouseId) { return new DefaultWarehouse(WarehouseManager.DEFAULT_WAREHOUSE_ID, WarehouseManager.DEFAULT_WAREHOUSE_NAME); ...
@VisibleForTesting public List<ChunkRange> splitEvenlySizedChunks( TableId tableId, Object min, Object max, long approximateRowCnt, int chunkSize, int dynamicChunkSize) { LOG.info( "Use evenly-sized chunk optimization fo...
@Test public void testSplitEvenlySizedChunksOverflow() { MySqlChunkSplitter splitter = new MySqlChunkSplitter(null, null); List<ChunkRange> res = splitter.splitEvenlySizedChunks( new TableId("catalog", "db", "tab"), Integer.MAX_VALUE - ...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_otherTypes_bigDecimalNotSupported() { BigDecimal expected = BigDecimal.valueOf(2.0); float[] actual = array(1.0f, 2.0f, 3.0f); expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected); assertFailureKeys( "value of", "exp...
@Override public MetricRegistry metricRegistry() { return this.metricRegistry; }
@Test @Order(1) void testMetricsEnabled() { KubernetesMetricsInterceptor metricsInterceptor = new KubernetesMetricsInterceptor(); List<Interceptor> interceptors = Collections.singletonList(metricsInterceptor); try (KubernetesClient client = KubernetesClientFactory.buildKubernetesClient( ...
public static boolean isValidDateFormatToStringDate( String dateFormat, String dateString ) { String detectedDateFormat = detectDateFormat( dateString ); if ( ( dateFormat != null ) && ( dateFormat.equals( detectedDateFormat ) ) ) { return true; } return false; }
@Test public void testIsValidDateFormatToStringDate() { assertTrue( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE_FORMAT_US, SAMPLE_DATE_STRING_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDate( null, SAMPLE_DATE_STRING_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDat...
@Override public int relaunchContainer(ContainerStartContext ctx) throws IOException, ConfigurationException { return handleLaunchForLaunchType(ctx, ApplicationConstants.ContainerLaunchType.RELAUNCH); }
@Test public void testRelaunchContainer() throws Exception { Container container = mock(Container.class); LinuxContainerExecutor lce = mock(LinuxContainerExecutor.class); ContainerStartContext.Builder builder = new ContainerStartContext.Builder(); builder.setContainer(container).setUser("foo")...
public static org.apache.avro.Schema toAvroSchema( Schema beamSchema, @Nullable String name, @Nullable String namespace) { final String schemaName = Strings.isNullOrEmpty(name) ? "topLevelRecord" : name; final String schemaNamespace = namespace == null ? "" : namespace; String childNamespace = ...
@Test public void testAvroSchemaFromBeamSchemaCanBeParsed() { org.apache.avro.Schema convertedSchema = AvroUtils.toAvroSchema(getBeamSchema()); org.apache.avro.Schema validatedSchema = new org.apache.avro.Schema.Parser().parse(convertedSchema.toString()); assertEquals(convertedSchema, validatedSch...
static JavaType constructType(Type type) { try { return constructTypeInner(type); } catch (Exception e) { throw new InvalidDataTableTypeException(type, e); } }
@Test void upper_bound_of_wild_card_list_type_replaces_wild_card_type() { JavaType javaType = TypeFactory.constructType(LIST_OF_WILD_CARD_NUMBER); TypeFactory.ListType listType = (TypeFactory.ListType) javaType; JavaType elementType = listType.getElementType(); assertThat(elementType...
@Override public void setLoginTimeout(final int seconds) throws SQLException { dataSource.setLoginTimeout(seconds); }
@Test void assertSetLoginTimeoutFailure() throws SQLException { doThrow(new SQLException("")).when(dataSource).setLoginTimeout(LOGIN_TIMEOUT); assertThrows(SQLException.class, () -> new PipelineDataSourceWrapper(dataSource, TypedSPILoader.getService(DatabaseType.class, "FIXTURE")).setLoginTimeout(LO...
@Override public ClassLoader getDefaultClassLoader() { return DEFAULT_CLASS_LOADER; }
@Test public void resources_notFound() { runWithClassloader(provider -> { try { var resources = provider.getDefaultClassLoader().getResources("a.b.c"); assertThat(Collections.list(resources)).isEmpty(); } catch (IOException e) { throw new UncheckedIOException(e); } })...
public static <T> ProcessorMetaSupplier metaSupplier( @Nonnull String directoryName, @Nonnull FunctionEx<? super T, ? extends String> toStringFn, @Nonnull String charset, @Nullable String datePattern, long maxFileSize, boolean exactlyOnce ) { ...
@Test public void test_rollByDate() { int numItems = 10; DAG dag = new DAG(); Vertex src = dag.newVertex("src", () -> new SlowSourceP(semaphore, numItems)).localParallelism(1); @SuppressWarnings("Convert2MethodRef") Vertex sink = dag.newVertex("sink", WriteFileP.metaSupplier(...
public ShardingTable getShardingTable(final String logicTableName) { return findShardingTable(logicTableName).orElseThrow(() -> new ShardingTableRuleNotFoundException(Collections.singleton(logicTableName))); }
@Test void assertGetTableRuleWithShardingTable() { ShardingTable actual = createMaximumShardingRule().getShardingTable("Logic_Table"); assertThat(actual.getLogicTable(), is("LOGIC_TABLE")); }
public void setBottomPadding(int bottomPadding) { mBottomPadding = bottomPadding; for (int childIndex = 0; childIndex < getChildCount(); childIndex++) { if (getChildAt(childIndex) instanceof MainChild v) { v.setBottomOffset(bottomPadding); } } }
@Test public void testSettingPadding() { AnyKeyboardView mock = Mockito.mock(AnyKeyboardView.class); mUnderTest.addView(mock); Mockito.verify(mock).setBottomOffset(0); View mockRegular = Mockito.mock(View.class); mUnderTest.addView(mockRegular); mUnderTest.setBottomPadding(10); Mockito.v...
public <T> List<T> apply(T[] a) { return apply(Arrays.asList(a)); }
@Test public void minOnlyRange() { Range r = new Range(4,Integer.MAX_VALUE); assertEquals("[e, f]", toS(r.apply(array))); assertEquals("[e, f]", toS(r.apply(list))); assertEquals("[e, f]", toS(r.apply(set))); }
public ServiceBuilder<U> addMethod(MethodConfig method) { if (this.methods == null) { this.methods = new ArrayList<>(); } this.methods.add(method); return getThis(); }
@Test void addMethod() { MethodConfig method = new MethodConfig(); ServiceBuilder builder = new ServiceBuilder(); builder.addMethod(method); Assertions.assertTrue(builder.build().getMethods().contains(method)); Assertions.assertEquals(1, builder.build().getMethods().size()); ...
public final long toLong(byte[] b) { return toLong(b, 0); }
@Test public void testToLong() { byte[] bytes = bitUtil.fromLong(Long.MAX_VALUE); assertEquals(Long.MAX_VALUE, bitUtil.toLong(bytes)); bytes = bitUtil.fromLong(Long.MAX_VALUE / 7); assertEquals(Long.MAX_VALUE / 7, bitUtil.toLong(bytes)); }
public boolean tryAdd(final Agent agent) { Objects.requireNonNull(agent, "agent cannot be null"); if (Status.ACTIVE != status) { throw new IllegalStateException("add called when not active"); } return addAgent.compareAndSet(null, agent); }
@Test void shouldDetectConcurrentAdd() { final Agent mockAgentOne = mock(Agent.class); final Agent mockAgentTwo = mock(Agent.class); final DynamicCompositeAgent compositeAgent = new DynamicCompositeAgent(ROLE_NAME, mockAgentOne, mockAgentTwo); final AgentInvoker invoker = new Ag...
public static String safeAppendDirectory( String dir, String file ) { boolean dirHasSeparator = ( ( dir.lastIndexOf( FILE_SEPARATOR ) ) == dir.length() - 1 ); boolean fileHasSeparator = ( file.indexOf( FILE_SEPARATOR ) == 0 ); if ( ( dirHasSeparator && !fileHasSeparator ) || ( !dirHasSeparator && fileHasSep...
@Test public void testSafeAppendDirectory() { final String expected = "dir" + Const.FILE_SEPARATOR + "file"; assertEquals( expected, Const.safeAppendDirectory( "dir", "file" ) ); assertEquals( expected, Const.safeAppendDirectory( "dir" + Const.FILE_SEPARATOR, "file" ) ); assertEquals( expected, Const....
public boolean isGreaterThanOrEqual(Version than) { return this.version.isGreaterThanOrEqual(than); }
@Test public void verify_methods() { var version = Version.create(9, 5); SonarQubeVersion underTest = new SonarQubeVersion(version); assertThat(underTest).extracting(SonarQubeVersion::toString, SonarQubeVersion::get) .containsExactly("9.5", version); var otherVersion = Version.create(8, 5); ...
public TargetState initialTargetState() { if (initialState != null) { return initialState.toTargetState(); } else { return null; } }
@Test public void testToTargetState() { assertEquals(TargetState.STARTED, CreateConnectorRequest.InitialState.RUNNING.toTargetState()); assertEquals(TargetState.PAUSED, CreateConnectorRequest.InitialState.PAUSED.toTargetState()); assertEquals(TargetState.STOPPED, CreateConnectorRequest.Initi...
@Override public int remainingCapacity() { return Integer.MAX_VALUE; }
@Test public void remainingCapacity() { assertEquals(Integer.MAX_VALUE, queue.remainingCapacity()); }
public static Ip6Prefix valueOf(byte[] address, int prefixLength) { return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfEmptyString() { Ip6Prefix ipPrefix; String fromString; fromString = ""; ipPrefix = Ip6Prefix.valueOf(fromString); }
public Comparator<?> getValueComparator(int column) { return valueComparators[column]; }
@Test public void getDefaultComparatorForObjectClass() { ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("object", Object.class)); assertThat(sorter.getValueComparator(0), is(nullValue())); }
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { // If the request servlet path is in the whitelist, // skip Kerberos authentication and return anonymous token. final String path = r...
@Test public void testRequestToWhitelist() throws Exception { final String token = new Base64(0).encodeToString(new byte[]{0, 1, 2}); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito...
@Override public IcebergEnumeratorState snapshotState(long checkpointId) { return new IcebergEnumeratorState( enumeratorPosition.get(), assigner.state(), enumerationHistory.snapshot()); }
@Test public void testThrottlingDiscovery() throws Exception { // create 10 splits List<IcebergSourceSplit> splits = SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 10, 1); TestingSplitEnumeratorContext<IcebergSourceSplit> enumeratorContext = new TestingSplitEnumeratorC...
public static Pair<Optional<Method>, Optional<TypedExpression>> resolveMethodWithEmptyCollectionArguments( final MethodCallExpr methodExpression, final MvelCompilerContext mvelCompilerContext, final Optional<TypedExpression> scope, List<TypedExpression> arguments, ...
@Test public void resolveMethodWithEmptyCollectionArgumentsCoerceMap() { final MethodCallExpr methodExpression = new MethodCallExpr("setItems", new MapCreationLiteralExpression(null, NodeList.nodeList())); final List<TypedExpression> arguments = new ArrayList<>(); arguments.add(new ListExprT...