focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@ScalarFunction(nullableParameters = true) public static byte[] toHLL(@Nullable Object input) { return toHLL(input, CommonConstants.Helix.DEFAULT_HYPERLOGLOG_LOG2M); }
@Test public void hllCreation() { for (Object i : _inputs) { Assert.assertEquals(hllEstimate(SketchFunctions.toHLL(i)), 1); Assert.assertEquals(hllEstimate(SketchFunctions.toHLL(i, 8)), 1); } Assert.assertEquals(hllEstimate(SketchFunctions.toHLL(null)), 0); Assert.assertEquals(hllEstimate(...
public void requireAtLeast(final int requiredMajor, final int requiredMinor) { final Version required = new Version(requiredMajor, requiredMinor); if (this.compareTo(required) < 0) { throw new UnsupportedOperationException( "This operation requires API version at least "...
@Test public void shouldObserveApiLimitsOnMajorVersions() { assertThrows(UnsupportedOperationException.class, () -> V35_0.requireAtLeast(36, 0)); }
public Class getResClass(String service, String methodName) { String key = service + "#" + methodName; Class reqClass = responseClassCache.get(key); if (reqClass == null) { // 读取接口里的方法参数和返回值 String interfaceClass = ConfigUniqueNameGenerator.getInterfaceName(service); ...
@Test public void getResClass() { Class res = protobufHelper.getResClass( "com.alipay.sofa.rpc.codec.protobuf.ProtoService", "echoStr"); Assert.assertTrue(res == EchoStrRes.class); }
public Tuple2<Long, Long> cancel() throws Exception { List<Tuple2<Future<? extends StateObject>, String>> pairs = new ArrayList<>(); pairs.add(new Tuple2<>(getKeyedStateManagedFuture(), "managed keyed")); pairs.add(new Tuple2<>(getKeyedStateRawFuture(), "managed operator")); pairs.add(ne...
@Test void testCancelAndCleanup() throws Exception { OperatorSnapshotFutures operatorSnapshotResult = new OperatorSnapshotFutures(); operatorSnapshotResult.cancel(); KeyedStateHandle keyedManagedStateHandle = mock(KeyedStateHandle.class); SnapshotResult<KeyedStateHandle> keyedState...
public static boolean isValidUrl(final String url) { try { String encodedURL = URLEncoder.encode(url, Charset.defaultCharset().name()); return url.equals(encodedURL); } catch (UnsupportedEncodingException e) { return false; } }
@Test public void should_know_valid_url_character() { assertThat(URLs.isValidUrl("base"), is(true)); assertThat(URLs.isValidUrl("base path"), is(false)); }
void subscribeNewCommentNotification(Post post) { var subscriber = new Subscription.Subscriber(); subscriber.setName(post.getSpec().getOwner()); var interestReason = new Subscription.InterestReason(); interestReason.setReasonType(NotificationReasonConst.NEW_COMMENT_ON_POST); int...
@Test void subscribeNewCommentNotificationTest() { Post post = TestPost.postV1(); postReconciler.subscribeNewCommentNotification(post); verify(notificationCenter).subscribe( assertArg(subscriber -> assertThat(subscriber.getName()) .isEqualTo(post.getSpec().getOw...
public static UMethodInvocation create( List<? extends UExpression> typeArguments, UExpression methodSelect, List<UExpression> arguments) { return new AutoValue_UMethodInvocation( ImmutableList.copyOf(typeArguments), methodSelect, ImmutableList.copyOf(arguments)); }
@Test public void match() { UExpression fooIdent = mock(UExpression.class); when(fooIdent.unify(ident("foo"), isA(Unifier.class))).thenReturn(Choice.of(unifier)); ULiteral oneLit = ULiteral.intLit(1); ULiteral barLit = ULiteral.stringLit("bar"); UMethodInvocation invocation = UMethodInvoca...
public static DistCpOptions parse(String[] args) throws IllegalArgumentException { CommandLineParser parser = new CustomParser(); CommandLine command; try { command = parser.parse(cliOptions, args, true); } catch (ParseException e) { throw new IllegalArgumentException("Unable to pars...
@Test public void testInvalidArgs() { try { OptionsParser.parse(new String[] { "-m", "-f", "hdfs://localhost:8020/source"}); Assert.fail("Missing map value"); } catch (IllegalArgumentException ignore) {} }
@Override public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey, @Nullable String projectName) { String key = Optional.ofNullable(projectKey).orElse(generateUniqueProjectKey()); boolean isManaged ...
@Test void createProjectAndBindToDevOpsPlatformFromScanner_whenVisibilitySynchronizationDisabled_successfullyCreatesProjectAndMakesProjectPrivate() { // given mockGeneratedProjectKey(); ComponentCreationData componentCreationData = mockProjectCreation("generated_orga2/repo1"); ProjectAlmSettingDao pr...
public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
@Test public void testCompare2() { ByteBuf expected = wrappedBuffer(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); ByteBuf actual = wrappedBuffer(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}); assertTrue(ByteBufUtil.compare(expected, actual) > 0); ...
@Override public String toString() { StringBuilder b = new StringBuilder(); if (StringUtils.isNotBlank(protocol)) { b.append(protocol); b.append("://"); } if (StringUtils.isNotBlank(host)) { b.append(host); } if (!isPortDefault() &&...
@Test public void testInvalidURL() { s = "http://www.example.com/\"path\""; t = "http://www.example.com/%22path%22"; assertEquals(t, new HttpURL(s).toString()); }
public static Map<String, String> computeAliases(PluginScanResult scanResult) { Map<String, Set<String>> aliasCollisions = new HashMap<>(); scanResult.forEach(pluginDesc -> { aliasCollisions.computeIfAbsent(simpleName(pluginDesc), ignored -> new HashSet<>()).add(pluginDesc.className()); ...
@Test public void testCollidingPrunedAlias() { SortedSet<PluginDesc<Converter>> converters = new TreeSet<>(); converters.add(new PluginDesc<>(CollidingConverter.class, null, PluginType.CONVERTER, CollidingConverter.class.getClassLoader())); SortedSet<PluginDesc<HeaderConverter>> headerConver...
@Override public void stopAndCleanupCluster(String clusterId) { this.internalClient .apps() .deployments() .withName(KubernetesUtils.getDeploymentName(clusterId)) .cascading(true) .delete(); }
@Test void testStopAndCleanupCluster() throws Exception { this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification); final KubernetesPod kubernetesPod = buildKubernetesPod(TASKMANAGER_POD_NAME); this.flinkKubeClient.createTaskManagerPod(kubernetesPod).get(); ...
@Override protected int command() { if (!validateConfigFilePresent()) { return 1; } final MigrationConfig config; try { config = MigrationConfig.load(getConfigFile()); } catch (KsqlException | MigrationException e) { LOGGER.error(e.getMessage()); return 1; } retur...
@Test public void shouldThrowErrorOnParsingFailure() throws Exception { // Given: command = PARSER.parse("-n"); createMigrationFile(1, NAME, migrationsDir, "SHOW TABLES;"); when(versionQueryResult.get()).thenReturn(ImmutableList.of()); // When: final int result = command.command(config, (cfg,...
@Override @SuppressWarnings("DuplicatedCode") public Integer cleanJobLog(Integer exceedDay, Integer deleteLimit) { int count = 0; LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay); // 循环删除,直到没有满足条件的数据 for (int i = 0; i < Short.MAX_VALUE; i++) { int d...
@Test public void testCleanJobLog() { // mock 数据 JobLogDO log01 = randomPojo(JobLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3)))) .setExecuteIndex(1); jobLogMapper.insert(log01); JobLogDO log02 = randomPojo(JobLogDO.class, o -> o.setCreateTime(addTime(D...
public int wipeWritePermOfBroker(final String namesrvAddr, String brokerName, final long timeoutMillis) throws RemotingCommandException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQClientException { WipeWritePermOfBrokerRequestHeader ...
@Test public void assertWipeWritePermOfBroker() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); WipeWritePermOfBrokerResponseHeader responseHeader = mock(WipeWritePermOfBrokerResponseHeader.class); when(responseHeader.getWipeTopicCount()).thenReturn(1); ...
@VisibleForTesting List<MessageSummary> getMessageBacklog(EventNotificationContext ctx, SlackEventNotificationConfig config) { List<MessageSummary> backlog = notificationCallbackService.getBacklogForEvent(ctx); if (config.backlogSize() > 0 && backlog != null) { return backlog.stream().li...
@Test public void testBacklogMessageLimitWhenBacklogSizeIsZero() { SlackEventNotificationConfig slackConfig = SlackEventNotificationConfig.builder() .backlogSize(0) .build(); //global setting is at N and the message override is 0 then the backlog size = 50 Li...
@VisibleForTesting Path getWarArtifact() { Build build = project.getBuild(); String warName = build.getFinalName(); Plugin warPlugin = project.getPlugin("org.apache.maven.plugins:maven-war-plugin"); if (warPlugin != null) { for (PluginExecution execution : warPlugin.getExecutions()) { i...
@Test public void testGetWarArtifact() { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); assertThat(mavenProjectProperties.getWarArtifact()) .isEqualTo(Paths.get("/foo/bar/helloworld-1.war")); }
public static Write write() { return new AutoValue_PulsarIO_Write.Builder().build(); }
@Test public void testWriteFromTopic() { try { PulsarIO.Write writer = PulsarIO.write().withClientUrl(pulsarContainer.getPulsarBrokerUrl()).withTopic(TOPIC); int numberOfMessages = 100; List<byte[]> messages = new ArrayList<>(); for (int i = 0; i < numberOfMessages; i++) { ...
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) throws SQLException { int length = payload.readInt1(); payload.readInt1(); payload.readInt4(); switch (length) { case 0: return new Timestamp(0L); case 8: ...
@Test void assertReadWithEightBytes() throws SQLException { when(payload.readInt1()).thenReturn(8, 0, 10, 59, 0); Calendar actual = Calendar.getInstance(); actual.setTimeInMillis(((Timestamp) new MySQLTimeBinaryProtocolValue().read(payload, false)).getTime()); assertThat(actual.get(C...
@Override public int getEventType() { return eventType; }
@Test public void testGetEventType() { assertEquals(23, localCacheWideEventData.getEventType()); }
public static String getLocalHostAddress() { if (useFqdn) { return localAddr.getCanonicalHostName(); } return InetAddresses.toAddrString(localAddr); }
@Test public void enableFQDNTest() throws UnknownHostException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { ...
@Override public ClusterInfo clusterGetClusterInfo() { RFuture<Map<String, String>> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO); Map<String, String> entries = syncFuture(f); Properties props = new Properties(); for (Entry<String, Str...
@Test public void testClusterGetClusterInfo() { ClusterInfo info = connection.clusterGetClusterInfo(); assertThat(info.getSlotsFail()).isEqualTo(0); assertThat(info.getSlotsOk()).isEqualTo(MasterSlaveConnectionManager.MAX_SLOT); assertThat(info.getSlotsAssigned()).isEqualTo(MasterSla...
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: ret...
@Test public void testConvertTypeCaseInt() { TypeInfo typeInfo = TypeInfoFactory.INT; Type result = EntityConvertUtils.convertType(typeInfo); assertEquals(Type.INT, result); }
public StringableMap(String s) { super(); if (s == null || s.isEmpty()) { return; } String[] parts = s.split(":", 2); // read that many chars int numElements = Integer.parseInt(parts[0]); s = parts[1]; for (int i = 0; i < numElements; i++) { // Get the key String. parts...
@Test public void stringableMap() throws Exception { // Empty map case StringableMap m = new StringableMap(new HashMap<String, String>()); String s = m.toString(); Assert.assertEquals("0:", s); m = new StringableMap(s); Assert.assertEquals(0, m.size()); Map<S...
public URI getHttpPublishUri() { if (httpPublishUri == null) { final URI defaultHttpUri = getDefaultHttpUri(); LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri); return defaultHttpUri; } else { final InetAddress inetAddress = to...
@Test public void testHttpPublishUriWithCustomPort() throws RepositoryException, ValidationException { jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_publish_uri", "http://example.com:12900/"))).addConfigurationBean(configuration).process(); assertThat(configuration.getHttpPub...
@Override public BigDecimal getBigDecimal(final int columnIndex) throws SQLException { return (BigDecimal) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, BigDecimal.class), BigDecimal.class); }
@Test void assertGetBigDecimalAndScaleWithColumnLabel() throws SQLException { when(mergeResultSet.getValue(1, BigDecimal.class)).thenReturn(new BigDecimal("1")); assertThat(shardingSphereResultSet.getBigDecimal("label", 10), is(new BigDecimal("1"))); }
@GwtIncompatible("java.util.regex.Pattern") public void containsMatch(@Nullable Pattern regex) { checkNotNull(regex); if (actual == null) { failWithActual("expected a string that contains a match for", regex); } else if (!regex.matcher(actual).find()) { failWithActual("expected to contain a ma...
@Test public void stringContainsMatchStringFailNull() { expectFailureWhenTestingThat(null).containsMatch(".*b.*"); assertFailureValue("expected a string that contains a match for", ".*b.*"); }
@Override public String toString() { return MoreObjects.toStringHelper(ByteKeyRange.class) .add("startKey", startKey) .add("endKey", endKey) .toString(); }
@Test public void testToString() { assertEquals("ByteKeyRange{startKey=[], endKey=[0a]}", UP_TO_10.toString()); }
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 testPDFBoxRepeatableSubcommand() throws Exception { PDFBox.main(new String[] { "export:text", "-i", testfile1, "-console", // "export:text", "-i", testfile2, "-console" }); String result = out.toString("UTF-8"); assertTrue(result.contains("PDF1")); ass...
public IMetaStoreClient get(final HiveConf hiveConf) throws MetaException, IOException, LoginException { final HiveClientCacheKey cacheKey = HiveClientCacheKey.fromHiveConf(hiveConf, getThreadId()); ICacheableMetaStoreClient cacheableHiveMetaStoreClient = null; // the hmsc is not shared across threads. So ...
@Test public void testCacheExpiry() throws IOException, MetaException, LoginException, InterruptedException { HiveClientCache cache = new HiveClientCache(1); HiveClientCache.ICacheableMetaStoreClient client = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf); assertNotNull(client); Thre...
@Beta @Nonnull public ClientConfig setTpcConfig(@Nonnull ClientTpcConfig tpcConfig) { this.tpcConfig = isNotNull(tpcConfig, "tpcConfig"); return this; }
@Test public void testTpcConfig() { ClientConfig config = new ClientConfig(); ClientTpcConfig tpcConfig = new ClientTpcConfig(); assertFalse(tpcConfig.isEnabled()); tpcConfig.setEnabled(true); tpcConfig.setConnectionCount(10); config.setTpcConfig(tpcConfig); ...
@Override public boolean next() throws SQLException { if (skipAll) { return false; } if (!paginationContext.getActualRowCount().isPresent()) { return getMergedResult().next(); } return ++rowNumber <= paginationContext.getActualRowCount().get() && getMe...
@Test void assertNextForSkipAll() throws SQLException { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); MySQLSelectStatement selectStatement = new MySQLSelectStatement(); selectStatement.setProjections(new ProjectionsSegment(0, 0)); selectSta...
@Override public ListenableFuture<?> execute(StartTransaction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Session session = stateMachine.getSession(); if (!session.isClientTransac...
@Test public void testStartTransactionTooManyAccessModes() { Session session = sessionBuilder() .setClientTransactionSupport() .build(); TransactionManager transactionManager = createTestTransactionManager(); QueryStateMachine stateMachine = createQuerySta...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { KeyAuthRuleHandle keyAuthRuleHandle = KeyAuthPluginDataHandler.CACHED_HANDLE.get() .obtainHandle(C...
@Test public void testNotConfigured() { ruleData.setHandle("{}"); keyAuthPluginDataHandler.handlerRule(ruleData); exchange = MockServerWebExchange.from(MockServerHttpRequest .get("localhost") .build()); Mono<Void> mono = keyAuthPlugin.doExecute(exchang...
@Override public void accept(T t) { updateTimeHighWaterMark(t.time()); shortTermStorage.add(t); drainDueToLatestInput(t); //standard drain policy drainDueToTimeHighWaterMark(); //prevent blow-up when data goes backwards in time sizeHighWaterMark = Math.max(sizeHighWaterMa...
@Test public void testStalePointsAreNotAutoEvicted() { TimeOrderVerifyingConsumer downstreamConsumer = new TimeOrderVerifyingConsumer(); ApproximateTimeSorter<TimePojo> sorter = new ApproximateTimeSorter<>( Duration.ofSeconds(10), downstreamConsumer ); sort...
public CompletableFuture<Account> removeDevice(final Account account, final byte deviceId) { if (deviceId == Device.PRIMARY_ID) { throw new IllegalArgumentException("Cannot remove primary device"); } return accountLockManager.withLockAsync(List.of(account.getNumber()), () -> removeDevice(acco...
@Test void testRemovePrimaryDevice() { final Device primaryDevice = new Device(); primaryDevice.setId(Device.PRIMARY_ID); final Account account = AccountsHelper.generateTestAccount("+14152222222", List.of(primaryDevice)); when(keysManager.deleteSingleUsePreKeys(any(), anyByte())).thenReturn(Completa...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldFetchWithStartLowerBoundIfHighest() { // Given: final Range<Instant> startBounds = Range.closed( NOW.plusSeconds(5), NOW.plusSeconds(10) ); final Range<Instant> endBounds = Range.closed( NOW, NOW.plusSeconds(15).plus(WINDOW_SIZE) ); // ...
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors( ReconnaissanceReport reconnaissanceReport) { return tsunamiPlugins.entrySet().stream() .filter(entry -> isVulnDetector(entry.getKey())) .map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc...
@Test public void getVulnDetectors_whenServiceNameFilterHasNoMatchingService_returnsEmpty() { NetworkService httpsService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 443)) .setTransportProtocol(TransportProtocol.TCP) .s...
public void isNotNull() { standardIsNotEqualTo(null); }
@Test public void isNotNull() { Object o = new Object(); assertThat(o).isNotNull(); }
public static String get(String urlString, Charset customCharset) { return HttpRequest.get(urlString).charset(customCharset).execute().body(); }
@Test @Disabled public void oschinaTest() { // 请求列表页 String listContent = HttpUtil.get("https://www.oschina.net/action/ajax/get_more_news_list?newsType=&p=2"); // 使用正则获取所有标题 final List<String> titles = ReUtil.findAll("<span class=\"text-ellipsis\">(.*?)</span>", listContent, 1); for (final String title : ti...
public Plan validateReservationDeleteRequest( ReservationSystem reservationSystem, ReservationDeleteRequest request) throws YarnException { return validateReservation(reservationSystem, request.getReservationId(), AuditConstants.DELETE_RESERVATION_REQUEST); }
@Test public void testDeleteReservationDoesnotExist() { ReservationDeleteRequest request = new ReservationDeleteRequestPBImpl(); ReservationId rId = ReservationSystemTestUtil.getNewReservationId(); request.setReservationId(rId); when(rSystem.getQueueForReservation(rId)).thenReturn(null); Plan plan...
@Override public Collection<String> getEnhancedTableNames() { return logicalTableMapper; }
@Test void assertGetEnhancedTableMapper() { assertThat(new LinkedList<>(ruleAttribute.getEnhancedTableNames()), is(Collections.singletonList("foo_tbl"))); }
@VisibleForTesting public static long getDefaultFileLength() { return DEFAULT_FILE_LENGTH; }
@Test public void testCornerConditions() throws Exception { final String segmentName = "someSegment"; PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName); final long s1 = MmapMemoryManager.getDefaultFileLength() - 1; final long s2 = 1; final long s3 = 100...
@Override public void createOperateLog(OperateLogCreateReqDTO createReqDTO) { OperateLogDO log = BeanUtils.toBean(createReqDTO, OperateLogDO.class); operateLogMapper.insert(log); }
@Test public void testCreateOperateLog() { OperateLogCreateReqDTO reqVO = RandomUtils.randomPojo(OperateLogCreateReqDTO.class); // 调研 operateLogServiceImpl.createOperateLog(reqVO); // 断言 OperateLogDO operateLogDO = operateLogMapper.selectOne(null); assertPojoEquals(r...
public boolean isAllBindingTables(final Collection<String> logicTableNames) { if (logicTableNames.isEmpty()) { return false; } Optional<BindingTableRule> bindingTableRule = findBindingTableRule(logicTableNames); if (!bindingTableRule.isPresent()) { return false; ...
@Test void assertIsAllBindingTableWithJoinQueryWithoutJoinCondition() { SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS); when(sqlStatementContext.isContainsJoinQuery()).thenReturn(true); when(sqlStatementContext.getSqlStatement()).thenRetur...
void addEndpointHeaders(ComponentModel componentModel, UriEndpoint uriEndpoint, String scheme) { final Class<?> headersClass = uriEndpoint.headersClass(); if (headersClass == void.class) { getLog().debug(String.format("The endpoint %s has not defined any headers class", uriEndpoint.scheme())...
@Test void testHeadersNotProperlyDefinedAreIgnored() { mojo.addEndpointHeaders(model, SomeEndpointWithBadHeaders.class.getAnnotation(UriEndpoint.class), "some"); assertEquals(0, model.getEndpointHeaders().size()); }
@Override public Collection<String> getJdbcUrlPrefixes() { return Arrays.asList("jdbc:microsoft:sqlserver:", "jdbc:sqlserver:"); }
@Test void assertGetJdbcUrlPrefixes() { assertThat(TypedSPILoader.getService(DatabaseType.class, "SQLServer").getJdbcUrlPrefixes(), is(Arrays.asList("jdbc:microsoft:sqlserver:", "jdbc:sqlserver:"))); }
public long getCertificateExpirationDateEpoch() { var cert = cert(caCertSecret, CA_CRT); if (cert == null) { throw new RuntimeException(CA_CRT + " does not exist in the secret " + caCertSecret); } return cert.getNotAfter().getTime(); }
@Test @DisplayName("Should raise RuntimeException when certificate is not present") void shouldReturnZeroWhenCertificateNotPresent() { Exception exception = assertThrows(RuntimeException.class, () -> ca.getCertificateExpirationDateEpoch()); assertEquals("ca.crt does not exist in the secret null"...
public static Builder in(Table table) { return new Builder(table); }
@TestTemplate public void testInPartition() { table .newAppend() .appendFile(FILE_A) // bucket 0 .appendFile(FILE_B) // bucket 1 .appendFile(FILE_C) // bucket 2 .appendFile(FILE_D) // bucket 3 .commit(); Iterable<DataFile> files = FindFiles.in(table) ...
static ArgumentParser argParser() { ArgumentParser parser = ArgumentParsers .newArgumentParser("producer-performance") .defaultHelp(true) .description("This tool is used to verify the producer performance. To enable transactions, " + "you c...
@Test public void testMutuallyExclusiveGroup() { String[] args1 = new String[] { "--topic", "Hello-Kafka", "--num-records", "5", "--throughput", "100", "--record-size", "100", "--payload-monotonic", "--producer-props", "bootstrap.server...
@Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { return fromVersion == 0 ? upgradeToUseFetchToAndDataToFetch(oldConfiguration) : new TbPair<>(false, oldConfiguration); }
@Test public void givenOldConfig_whenUpgrade_thenShouldReturnTrueResultWithNewConfig() throws Exception { var defaultConfig = new TbGetEntityDataNodeConfiguration().defaultConfiguration(); var node = new TbGetCustomerAttributeNode(); String oldConfig = "{\"attrMapping\":{\"alarmThreshold\":\...
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception { LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation); MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con...
@Test public void shouldFailValidationIfPackageTypeMaterialForPipelineHasARefToNonExistantPackage() throws Exception { String packageId = "does-not-exist"; PackageMaterialConfig packageMaterialConfig = new PackageMaterialConfig(packageId); PackageRepository repository = com.thoughtworks.go.d...
@SuppressWarnings("MethodMayBeStatic") @Udf(description = "The 2 input points should be specified as (lat, lon) pairs, measured" + " in decimal degrees. An optional fifth parameter allows to specify either \"MI\" (miles)" + " or \"KM\" (kilometers) as the desired unit for the output measurement. Default i...
@Test public void shouldComputeDistanceSouthHemisphere() { assertEquals(11005.2330, (double) distanceUdf.geoDistance(-33.9323, 18.4197, -33.8666, 151.1), 0.5); assertEquals(11005.2330, (double) distanceUdf.geoDistance(-33.9323, 18.4197, -33.8666, 151.1, "KM"), 0.5); assertEquals(6838.7564,...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testChronicleAddFull() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHRONICLE_ADD_FULL, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_CHRONICLE, 1000); }
@Override public Annotation getAnnotation() { return this.annotation; }
@Test public void baseInfoTest() { final Annotation annotation = ClassForTest1.class.getAnnotation(AnnotationForTest.class); final Method attribute = ReflectUtil.getMethod(AnnotationForTest.class, "value"); final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attr...
public CreateTableBuilder withPkConstraintName(String pkConstraintName) { this.pkConstraintName = validateConstraintName(pkConstraintName); return this; }
@Test public void withPkConstraintName_does_not_fail_if_name_contains_numbers() { underTest.withPkConstraintName("a0123456789"); }
@Override public void executeUpdate(final AlterStorageUnitStatement sqlStatement, final ContextManager contextManager) { checkBefore(sqlStatement); Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.getStorageUnits()); ...
@Test void assertExecuteUpdateSuccess() { ResourceMetaData resourceMetaData = mock(ResourceMetaData.class, RETURNS_DEEP_STUBS); StorageUnit storageUnit = mock(StorageUnit.class, RETURNS_DEEP_STUBS); ConnectionProperties connectionProps = mockConnectionProperties("ds_0"); when(storage...
@Override protected Map<String, String> getHealthInformation() { if (!configuration.getBackgroundJobServer().isEnabled()) { healthStatus = HealthStatus.UP; return mapOf("backgroundJobServer", "disabled"); } else { if (backgroundJobServer.isRunning()) { ...
@Test void givenDisabledBackgroundJobServer_ThenHealthIsUp() { when(backgroundJobServerConfiguration.isEnabled()).thenReturn(false); jobRunrHealthIndicator.getHealthInformation(); assertThat(jobRunrHealthIndicator.getHealthStatus()).isEqualTo(HealthStatus.UP); }
@VisibleForTesting ZonedDateTime resolveAbsoluteDateTime(ZonedDateTime absoluteDateTime, Duration timeRange, ZonedDateTime now) { if (timeRange != null) { if (absoluteDateTime != null) { throw new IllegalArgumentException("Parameters 'startDate' and 'timeRange' are mutually exclu...
@Test void resolveAbsoluteDateTime() { final ZonedDateTime absoluteTimestamp = ZonedDateTime.of(2023, 2, 3, 4, 6,10, 0, ZoneId.systemDefault()); final Duration offset = Duration.ofSeconds(5L); final ZonedDateTime baseTimestamp = ZonedDateTime.of(2024, 2, 3, 5, 6,10, 0, ZoneId.systemDefault()...
public static List<alluxio.grpc.Metric> reportClientMetrics() { long start = System.currentTimeMillis(); List<alluxio.grpc.Metric> metricsList = reportMetrics(InstanceType.CLIENT); LOG.debug("Get the client metrics list contains {} metrics to report to leading master in {}ms", metricsList.size(), Sy...
@Test public void testReportClientMetrics() { String metricName = "Client.TestMetric"; Counter counter = MetricsSystem.counter(metricName); if (!MetricKey.isValid(metricName)) { MetricKey.register(new MetricKey.Builder(metricName) .setMetricType(MetricType.COUNTER).setIsClusterAggregated(t...
public Stream open(InputStream in) throws IOException { return this.delegate.open(in); }
@Test public void testParseMultipleJsons() throws Exception { final JsonParser parser = new JsonParser(); final String multipleJsons = "{\"col1\": 1}{\"col1\": 2}"; try (JsonParser.Stream stream = parser.open(toInputStream(multipleJsons))) { assertEquals("{\"col1\":1}", stream.ne...
public PasswordAlgorithm defaultPasswordAlgorithm() { return defaultPasswordAlgorithm; }
@Test public void testDefaultPasswordAlgorithm() throws Exception { final PasswordAlgorithm defaultPasswordAlgorithm = mock(PasswordAlgorithm.class); final PasswordAlgorithmFactory passwordAlgorithmFactory = new PasswordAlgorithmFactory(Collections.<String, PasswordAlgorithm>emptyMap(), ...
static CapsVersionAndHash generateVerificationString(DiscoverInfoView discoverInfo) { return generateVerificationString(discoverInfo, null); }
@Test public void testSimpleGenerationExample() throws XmppStringprepException { DiscoverInfo di = createSimpleSamplePacket(); CapsVersionAndHash versionAndHash = EntityCapsManager.generateVerificationString(di, StringUtils.SHA1); assertEquals("QgayPKawpkPSDYmwT/WM94uAlu0=", versionAndHash....
@Override public MetricsRepository load() { List<Metric> metrics = new ArrayList<>(); try { loadFromPaginatedWs(metrics); } catch (Exception e) { throw new IllegalStateException("Unable to load metrics", e); } return new MetricsRepository(metrics); }
@Test public void test() { MetricsRepository metricsRepository = metricsRepositoryLoader.load(); assertThat(metricsRepository.metrics()).hasSize(3); WsTestUtil.verifyCall(wsClient, WS_URL + "1"); WsTestUtil.verifyCall(wsClient, WS_URL + "2"); verifyNoMoreInteractions(wsClient); }
public String getId(String name) { // Use the id directly if it is unique and the length is less than max if (name.length() <= maxHashLength && usedIds.add(name)) { return name; } // Pick the last bytes of hashcode and use hex format final String hexString = Integer.toHexString(name.hashCode(...
@Test public void testGetId() { final HashIdGenerator idGenerator = new HashIdGenerator(); final Set<String> ids = ImmutableSet.of( idGenerator.getId(Count.perKey().getName()), idGenerator.getId(MapElements.into(null).getName()), idGenerator.getId(Count.globally().g...
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = ...
@Test void testMapToEnum() throws Exception { Map map = new HashMap(); map.put("name", "MONDAY"); Object o = PojoUtils.realize(map, Day.class); assertEquals(o, Day.MONDAY); }
@Subscribe @AllowConcurrentEvents public void handleIndexClosing(IndicesClosedEvent event) { for (String index : event.indices()) { if (!indexSetRegistry.isManagedIndex(index)) { LOG.debug("Not handling closed index <{}> because it's not managed by any index set.", index); ...
@Test @MongoDBFixtures("MongoIndexRangeServiceTest.json") public void testHandleIndexClosing() throws Exception { when(indexSetRegistry.isManagedIndex("graylog_1")).thenReturn(true); assertThat(indexRangeService.findAll()).hasSize(2); localEventBus.post(IndicesClosedEvent.create(Collec...
public String lookup(final String name, final String uriParamName, final boolean isReLookup) { final long beginNs = clock.nanoTime(); maxTimeTracker.update(beginNs); String resolvedName = null; try { resolvedName = delegateResolver.lookup(name, uriParamName, isReL...
@Test void lookupShouldMeasureExecutionTime() { final NameResolver delegateResolver = mock(NameResolver.class); when(delegateResolver.lookup(anyString(), anyString(), anyBoolean())) .thenAnswer(invocation -> { final String name = invocation.getArgument(0);...
public Schema toKsqlSchema(final Schema schema) { try { final Schema rowSchema = toKsqlFieldSchema(schema); if (rowSchema.type() != Schema.Type.STRUCT) { throw new KsqlException("KSQL stream/table schema must be structured"); } if (rowSchema.fields().isEmpty()) { throw new K...
@Test public void shouldTranslateStructInsideArray() { final Schema connectSchema = SchemaBuilder .struct() .field( "arrayField", SchemaBuilder.array( SchemaBuilder.struct() .field("innerIntField", Schema.OPTIONAL_INT32_SCHEMA) ...
@Nonnull @Override public Optional<? extends Padding> parse( @Nullable String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } if (str.toUpperCase().contains("OAEP")) { final JcaOAEPPaddingMapper jcaOA...
@Test void padding() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaPaddingMapper jcaPaddingMapper = new JcaPaddingMapper(); Optional<? extends INode> asset = jcaPaddingMapper.parse("PKCS1...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testRetryWhenProducerIdChanges() throws InterruptedException { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(producerId, Short.MAX_V...
public String join(final Stream<?> parts) { return join(parts.iterator()); }
@Test public void shouldHandleFourItems() { assertThat(joiner.join(ImmutableList.of(1, 2, 3, 4)), is("1, 2, 3 or 4")); }
public FlatFileStore(MessageStoreConfig storeConfig, MetadataStore metadataStore, MessageStoreExecutor executor) { this.storeConfig = storeConfig; this.metadataStore = metadataStore; this.executor = executor; this.flatFileFactory = new FlatFileFactory(metadataStore, storeConfig); ...
@Test public void flatFileStoreTest() { // Empty recover MessageStoreExecutor executor = new MessageStoreExecutor(); FlatFileStore fileStore = new FlatFileStore(storeConfig, metadataStore, executor); Assert.assertTrue(fileStore.load()); Assert.assertEquals(storeConfig, fileS...
public static String dnsEncode(String name) throws IOException { String[] parts = name.split("\\."); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (String part : parts) { byte[] bytes = toUtf8Bytes("_" + normalise(part)); if (bytes == null) { ...
@Test void testDnsEncode() throws IOException { String dnsEncoded = NameHash.dnsEncode("1.offchainexample.eth"); assertEquals("0x01310f6f6666636861696e6578616d706c650365746800", dnsEncoded); }
public AccessPrivilege getAccessPrivilege(InetAddress addr) { return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName()); }
@Test public void testExactAddressRO() { NfsExports matcher = new NfsExports(CacheSize, ExpirationPeriod, address1); Assert.assertEquals(AccessPrivilege.READ_ONLY, matcher.getAccessPrivilege(address1, hostname1)); Assert.assertEquals(AccessPrivilege.NONE, matcher.getAccessPrivilege(address...
public static RestSettingBuilder head() { return all(HttpMethod.HEAD); }
@Test public void should_head_with_all() throws Exception { server.resource("targets", head().response(header("ETag", "Moco")) ); running(server, () -> { HttpResponse httpResponse = helper.headForResponse(remoteUrl("/targets")); assertThat(httpRespons...
@Override @CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理 public void deleteSmsTemplate(Long id) { // 校验存在 validateSmsTemplateExists(id); // 更新 smsTemplateMapper.deleteById(id); }
@Test public void testDeleteSmsTemplate_success() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO(); smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbSmsTemplate.getId(); // 调用 smsTemplateService.deleteSmsTemplat...
public Object get(final String property) { return props.get(property); }
@Test public void shouldGetCurrentValue() { assertThat(propsWithMockParser.get("prop-1"), is("parsed-initial-val-1")); }
public boolean write(final int msgTypeId, final DirectBuffer srcBuffer, final int offset, final int length) { checkTypeId(msgTypeId); checkMsgLength(length); final AtomicBuffer buffer = this.buffer; final int recordLength = length + HEADER_LENGTH; final int recordIndex = cla...
@Test void shouldWriteToEmptyBuffer() { final int length = 8; final int recordLength = length + HEADER_LENGTH; final int alignedRecordLength = align(recordLength, ALIGNMENT); final long tail = 0L; final long head = 0L; when(buffer.getLongVolatile(HEAD_COUNTER_IND...
public boolean tryLock() { try { lockRandomAccessFile = new RandomAccessFile(lockFilePath.toFile(), "rw"); lockChannel = lockRandomAccessFile.getChannel(); lockFile = lockChannel.tryLock(0, 1024, false); return lockFile != null; } catch (IOException e) { throw new IllegalStateExce...
@Test public void errorTryLock() { lock = new DirectoryLock(Paths.get("non", "existing", "path")); assertThatThrownBy(() -> lock.tryLock()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Failed to create lock"); }
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowCreateHiveExternalTable() { new MockUp<MetadataMgr>() { @Mock public Database getDb(String catalogName, String dbName) { return new Database(); } @Mock public Table getTable(String catalogName, String dbNa...
@Override public String toString() { boolean traceHi = traceIdHigh != 0; char[] result = new char[traceHi ? 32 : 16]; int pos = 0; if (traceHi) { writeHexLong(result, pos, traceIdHigh); pos += 16; } writeHexLong(result, pos, traceId); return new String(result); }
@Test void testToString() { assertThat(base.toBuilder().traceIdHigh(222L).build().toString()) .isEqualTo("00000000000000de000000000000014d"); }
@Override public MutableAnalysisMetadataHolder setUuid(String s) { checkState(!uuid.isInitialized(), "Analysis uuid has already been set"); requireNonNull(s, "Analysis uuid can't be null"); this.uuid.setProperty(s); return this; }
@Test public void setUuid_throws_ISE_if_called_twice() { underTest.setUuid("org1"); assertThatThrownBy(() -> underTest.setUuid("org1")) .isInstanceOf(IllegalStateException.class) .hasMessage("Analysis uuid has already been set"); }
public static PTransform<PCollection<? extends KV<?, ?>>, PCollection<String>> kvs() { return kvs(","); }
@Test @Category(NeedsRunner.class) public void testToStringKV() { ArrayList<KV<String, Integer>> kvs = new ArrayList<>(); kvs.add(KV.of("one", 1)); kvs.add(KV.of("two", 2)); ArrayList<String> expected = new ArrayList<>(); expected.add("one,1"); expected.add("two,2"); PCollection<KV<Str...
static String getConfigValueAsString(ServiceConfiguration conf, String configProp) throws IllegalArgumentException { String value = getConfigValueAsStringImpl(conf, configProp); log.info("Configuration for [{}] is [{}]", configProp, value); return ...
@Test public void testGetConfigValueAsStringReturnsNullIfMissing() { Properties props = new Properties(); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); String actual = ConfigUtils.getConfigValueAsString(config, "prop1"); assertNull(act...
@Override public ProcessingLogger getLogger( final String name ) { return getLogger(name, Collections.emptyMap()); }
@Test public void shouldCreateLoggerWithoutPassingInTags() { // Given: final ProcessingLogger testLogger = factory.getLogger("foo.bar"); final Sensor sensor = metricCollectors.getMetrics().getSensor("foo.bar"); final Map<String, String> metricsTags = new HashMap<>(customMetricsTags); metricsTags.p...
@Override protected List<ParentRunner<?>> getChildren() { return children; }
@Test void finds_no_features_when_explicit_feature_path_has_no_features() throws InitializationError { Cucumber cucumber = new Cucumber(ExplicitFeaturePathWithNoFeatures.class); List<ParentRunner<?>> children = cucumber.getChildren(); assertThat(children, is(equalTo(emptyList()))); }
public static ResolvedSchema expandCompositeTypeToSchema(DataType dataType) { if (dataType instanceof FieldsDataType) { return expandCompositeType((FieldsDataType) dataType); } else if (dataType.getLogicalType() instanceof LegacyTypeInformationType && dataType.getLogicalType(...
@Test void testExpandRowType() { DataType dataType = ROW( FIELD("f0", INT()), FIELD("f1", STRING()), FIELD("f2", TIMESTAMP(5).bridgedTo(Timestamp.class)), FIELD("f3", TIMESTAMP(3))); Resol...
@Override public TimeSlot apply(TimeSlot timeSlot, SegmentInMinutes segmentInMinutes) { int segmentInMinutesDuration = segmentInMinutes.value(); Instant segmentStart = normalizeStart(timeSlot.from(), segmentInMinutesDuration); Instant segmentEnd = normalizeEnd(timeSlot.to(), segmentInMinute...
@Test void hasNoEffectWhenSlotAlreadyNormalized() { //given Instant start = Instant.parse("2023-09-09T00:00:00Z"); Instant end = Instant.parse("2023-09-09T01:00:00Z"); TimeSlot timeSlot = new TimeSlot(start, end); SegmentInMinutes oneHour = SegmentInMinutes.of(60, FIFTEEN_MIN...
@Override public <T> Task<T> synchronize(Task<T> task, long deadline) { return PlanLocal.get(getPlanLocalKey(), LockInternal.class) .flatMap(lockInternal -> { if (lockInternal != null) { // we already acquire the lock, add count only. lockInternal._lockCount++; ...
@Test public void testReleaseAfterException() throws InterruptedException { final long deadline = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(10, TimeUnit.SECONDS); final String path = "/testPath"; final String errMsg = "Boom! There is an exception! But, who cares..."; final ZKLoc...
public static RepositoryMetadataStore getInstance() { return repositoryMetadataStore; }
@Test public void shouldGetAllPluginIds() throws Exception { RepositoryMetadataStore metadataStore = RepositoryMetadataStore.getInstance(); metadataStore.addMetadataFor("plugin1", new PackageConfigurations()); metadataStore.addMetadataFor("plugin2", new PackageConfigurations()); meta...
@Override public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException { try { ctx.proceed(); } finally { TrackedByGauge trackedByGauge = _resourceInfo.getResourceMethod().getAnnotation(TrackedByGauge.class); if (trackedByGauge != null) { ...
@Test(expectedExceptions = IOException.class) public void testWriterInterceptorDecrementsGaugeWhenWriterThrowsException() throws Exception { Method methodOne = TrackedClass.class.getDeclaredMethod("trackedMethod"); when(_resourceInfo.getResourceMethod()).thenReturn(methodOne); doThrow(new IOExceptio...
@Override public void transferBufferOwnership(Object oldOwner, Object newOwner, Buffer buffer) { checkState(buffer.isBuffer(), "Only buffer supports transfer ownership."); decNumRequestedBuffer(oldOwner); incNumRequestedBuffer(newOwner); buffer.setRecycler(memorySegment -> recycleBuf...
@Test void testTransferBufferOwnership() throws IOException { TieredStorageMemoryManagerImpl memoryManager = createStorageMemoryManager( 1, Collections.singletonList(new TieredStorageMemorySpec(this, 0))); BufferBuilder bufferBuilder = memoryManager.requestBuf...
public Boolean fileExists( File dir, String path ) { try { FileProvider<File> fileProvider = providerService.get( dir.getProvider() ); return fileProvider.fileExists( dir, path, space ); } catch ( InvalidFileProviderException | FileException e ) { return false; } }
@Test public void testFileExists() { TestDirectory testDirectory = new TestDirectory(); testDirectory.setPath( "/directory1" ); Assert.assertTrue( fileController.fileExists( testDirectory, "/directory1/file1" ) ); Assert.assertFalse( fileController.fileExists( testDirectory, "/directory1/file5" ) ); ...
public Optional<Integer> declareManagedMemoryUseCaseAtOperatorScope( ManagedMemoryUseCase managedMemoryUseCase, int weight) { checkNotNull(managedMemoryUseCase); checkArgument( managedMemoryUseCase.scope == ManagedMemoryUseCase.Scope.OPERATOR, "Use case is not...
@Test void testDeclareManagedMemoryOperatorScopeUseCaseFailWrongScope() { assertThatThrownBy( () -> transformation.declareManagedMemoryUseCaseAtOperatorScope( ManagedMemoryUseCase.PYTHON, 123)) .i...
@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 testGenericsNotInSuperclass() { // use getMapReturnTypes() RichMapFunction<?, ?> function = new RichMapFunction<LongKeyValue<String>, LongKeyValue<String>>() { private static final long serialVersionUID =...
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"}) public static boolean isScalablePushQuery( final Statement statement, final KsqlExecutionContext ksqlEngine, final KsqlConfig ksqlConfig, final Map<String, Object> overrides ) { if (!isPushV2Enabled(ksqlConfig, ov...
@Test public void isScalablePushQuery_true_latestConfig() { try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) { // When: expectIsSPQ(ColumnName.of("foo"), columnExtractor); when(ksqlConfig.getKsqlStreamConfigProp(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)) ...
@Override public Optional<ResultDecorator<MaskRule>> newInstance(final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final MaskRule maskRule, final ConfigurationProperties props, final SQLStatementContext sqlStatementContext) { ...
@Test void assertNewInstanceWithOtherStatement() { MaskResultDecoratorEngine engine = (MaskResultDecoratorEngine) OrderedSPILoader.getServices(ResultProcessEngine.class, Collections.singleton(rule)).get(rule); assertFalse(engine.newInstance(mock(RuleMetaData.class), database, rule, mock(Configuratio...
@Override public ImagesAndRegistryClient call() throws IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { EventHandlers eventHandlers = buildContext...
@Test(expected = UnlistedPlatformInManifestListException.class) public void testCall_ManifestList_UnknownArchitecture() throws InvalidImageReferenceException, IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException...