focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public final List<? extends FileBasedSource<T>> split( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { // This implementation of method split is provided to simplify subclasses. Here we // split a FileBasedSource based on a file pattern to FileBasedSources based on ful...
@Test public void testSplittingFailsOnEmptyFileExpansion() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); String missingFilePath = tempFolder.newFolder().getAbsolutePath() + "/missing.txt"; TestFileBasedSource source = new TestFileBasedSource(missingFilePath, Long.MAX_VALUE,...
public static CopyFilter getCopyFilter(Configuration conf) { String filtersClassName = conf .get(DistCpConstants.CONF_LABEL_FILTERS_CLASS); if (filtersClassName != null) { try { Class<? extends CopyFilter> filtersClass = conf .getClassByName(filtersClassName) ...
@Test public void testGetCopyFilterNonExistingClass() throws Exception { final String filterName = "org.apache.hadoop.tools.RegexpInConfigurationWrongFilter"; Configuration configuration = new Configuration(false); configuration.set(DistCpConstants.CONF_LABEL_FILTERS_CLASS, filterName); in...
@Override public void executeUpdate(final RegisterStorageUnitStatement sqlStatement, final ContextManager contextManager) { checkDataSource(sqlStatement, contextManager); Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.get...
@Test void assertExecuteUpdateSuccess() { assertDoesNotThrow(() -> executor.executeUpdate(createRegisterStorageUnitStatement(), mock(ContextManager.class, RETURNS_DEEP_STUBS))); }
@Override public String query(final String key) { try ( Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(repositorySQL.getSelectByKeySQL())) { preparedStatement.setString(1, key); try...
@Test void assertGetFailure() throws SQLException { when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByKeySQL())).thenReturn(mockPreparedStatement); when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet); when(mockResultSet.next()).thenReturn(false); Stri...
@Override protected void readInternal(ObjectDataInput in) throws IOException { throw new UnsupportedOperationException(getClass().getName() + " is only used locally!"); }
@Test(expected = UnsupportedOperationException.class) public void testReadInternal() throws Exception { operation.readInternal(null); }
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowMaterializedViewFromUnknownDatabase() throws DdlException, AnalysisException { ShowMaterializedViewsStmt stmt = new ShowMaterializedViewsStmt("emptyDb", (String) null); expectedEx.expect(SemanticException.class); expectedEx.expectMessage("Unknown database 'emptyDb'...
@VisibleForTesting @SuppressWarnings("WeakerAccess") LookupResult parseResponse(@Nullable ResponseBody body) { if (body != null) { try { final JsonNode json = OBJECT_MAPPER.readTree(body.string()); return LookupResult.withoutTTL() .sin...
@Test public void parseResponse() throws Exception { final URL url = Resources.getResource(getClass(), "otx-IPv4-response.json"); final ResponseBody body = ResponseBody.create(null, Resources.toByteArray(url)); final LookupResult result = otxDataAdapter.parseResponse(body); assertTh...
public <T extends Notification> T getFromQueue() { int batchSize = 1; List<NotificationQueueDto> notificationDtos = dbClient.notificationQueueDao().selectOldest(batchSize); if (notificationDtos.isEmpty()) { return null; } dbClient.notificationQueueDao().delete(notificationDtos); return co...
@Test public void shouldGetFromQueueAndDelete() { Notification notification = new Notification("test"); NotificationQueueDto dto = NotificationQueueDto.toNotificationQueueDto(notification); List<NotificationQueueDto> dtos = Arrays.asList(dto); when(notificationQueueDao.selectOldest(1)).thenReturn(dtos...
public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException, InvalidKeySpecException { final String algo = getAlgorithmForOid(getOidFromPkcs8Encoded(encoded)); final KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded); final KeyFactory kf = KeyFactory.getInstance(algo); final Pr...
@Test public void recoverKeyPair_Rsa() throws Exception { KeyPair kp = PubkeyUtils.recoverKeyPair(RSA_KEY_PKCS8); RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic(); assertEquals(RSA_KEY_N, pubKey.getModulus()); assertEquals(RSA_KEY_E, pubKey.getPublicExponent()); }
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 testIdempotentUnknownProducerHandlingWhenRetentionLimitReached() throws Exception { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(pr...
@Override public org.apache.parquet.hadoop.api.ReadSupport.ReadContext init( Configuration configuration, Map<String, String> keyValueMetaData, MessageType fileSchema) { return init(new HadoopParquetConfiguration(configuration), keyValueMetaData, fileSchema); }
@Test public void testInitWithPartialSchema() { GroupReadSupport s = new GroupReadSupport(); Configuration configuration = new Configuration(); Map<String, String> keyValueMetaData = new HashMap<String, String>(); MessageType fileSchema = MessageTypeParser.parseMessageType(fullSchemaStr); MessageT...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testSiblings() { Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true)); OpenAPI openAPI = reader.read(SiblingsResource.class); String yaml = "openapi: 3.1.0\n" + "paths:\n" + " /test:\n" + ...
@Override public void declareResourceRequirements(ResourceRequirements resourceRequirements) { synchronized (lock) { checkNotClosed(); if (isConnected()) { currentResourceRequirements = resourceRequirements; triggerResourceRequirementsSubmission( ...
@Test void testDeclareResourceRequirementsSendsRequirementsIfConnected() { final DeclareResourceRequirementServiceConnectionManager declareResourceRequirementServiceConnectionManager = createResourceManagerConnectionManager(); final CompletableFuture<Resource...
@Override public Duration convert(String source) { try { if (ISO8601.matcher(source).matches()) { return Duration.parse(source); } Matcher matcher = SIMPLE.matcher(source); Assert.state(matcher.matches(), "'" + source + "' is not a valid durati...
@Test public void convertWhenSimpleSecondsShouldReturnDuration() { assertThat(convert("10s")).isEqualTo(Duration.ofSeconds(10)); assertThat(convert("10S")).isEqualTo(Duration.ofSeconds(10)); assertThat(convert("+10s")).isEqualTo(Duration.ofSeconds(10)); assertThat(convert("-10s")).is...
@Override public void encode(final ChannelHandlerContext context, final DatabasePacket message, final ByteBuf out) { MySQLPacketPayload payload = new MySQLPacketPayload(prepareMessageHeader(out).markWriterIndex(), context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()); try { ...
@Test void assertEncode() { when(byteBuf.writeInt(anyInt())).thenReturn(byteBuf); when(byteBuf.markWriterIndex()).thenReturn(byteBuf); when(byteBuf.readableBytes()).thenReturn(8); MySQLPacket actualMessage = mock(MySQLPacket.class); context.channel().attr(MySQLConstants.SEQUE...
public Optional<Result> execute( List<RowMetaAndData> rows ) throws KettleException { if ( rows.isEmpty() || stopped ) { return Optional.empty(); } Trans subtrans = this.createSubtrans(); running.add( subtrans ); parentTrans.addActiveSubTransformation( subTransName, subtrans ); // Pass p...
@Test public void testRunningZeroRowsIsEmptyOptional() throws Exception { SubtransExecutor subtransExecutor = new SubtransExecutor( "subtransname", null, null, false, null, "", 0 ); Optional<Result> execute = subtransExecutor.execute( Collections.emptyList() ); assertFalse( execute.isPresent() ); }
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) { SourceConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!ex...
@Test public void testMergeDifferentUserConfig() { SourceConfig sourceConfig = createSourceConfig(); Map<String, String> myConfig = new HashMap<>(); myConfig.put("MyKey", "MyValue"); SourceConfig newSourceConfig = createUpdatedSourceConfig("configs", myConfig); SourceConfig m...
public static SnapshotRef fromJson(String json) { Preconditions.checkArgument( json != null && !json.isEmpty(), "Cannot parse snapshot ref from invalid JSON: %s", json); return JsonUtil.parse(json, SnapshotRefParser::fromJson); }
@Test public void testFailParsingWhenMissingRequiredFields() { String refMissingType = "{\"snapshot-id\":1}"; assertThatThrownBy(() -> SnapshotRefParser.fromJson(refMissingType)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Cannot parse missing string"); String r...
static PrimitiveIterator.OfInt filterTranslate(int arrayLength, IntPredicate filter, IntUnaryOperator translator) { return new IndexIterator(0, arrayLength, filter, translator); }
@Test public void testFilterTranslate() { assertEquals(IndexIterator.filterTranslate(20, value -> value < 5, Math::negateExact), 0, -1, -2, -3, -4); }
private TemporaryClassLoaderContext(Thread thread, ClassLoader originalContextClassLoader) { this.thread = thread; this.originalContextClassLoader = originalContextClassLoader; }
@Test void testTemporaryClassLoaderContext() { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); final ChildFirstClassLoader temporaryClassLoader = new ChildFirstClassLoader( new URL[0], contextClassLoader, new String[0], ...
public boolean isForce() { return args.length >= 4 && parseForceParameter(args[3]); }
@Test void assertGetForce() { assertFalse(new BootstrapArguments(new String[]{"3306", "test_conf", "127.0.0.1"}).isForce()); assertFalse(new BootstrapArguments(new String[]{"3306", "test_conf", "127.0.0.1", "false"}).isForce()); assertTrue(new BootstrapArguments(new String[]{"3306", "test_co...
@Override public AdminUserDO getUser(Long id) { return userMapper.selectById(id); }
@Test public void testGetUser() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); // 准备参数 Long userId = dbUser.getId(); // 调用 AdminUserDO user = userService.getUser(userId); // 断言 assertPojoEquals(dbUser, user);...
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.1"); // 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 testImportWhitelistedSites() throws IOException { WhitelistedSite site1 = new WhitelistedSite(); site1.setId(1L); site1.setClientId("foo"); WhitelistedSite site2 = new WhitelistedSite(); site2.setId(2L); site2.setClientId("bar"); WhitelistedSite site3 = new WhitelistedSite(); site3....
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testMultipleSchemaParameters() { DoFnSignature sig = DoFnSignatures.getSignature( new DoFn<String, String>() { @ProcessElement public void process( @Element Row row1, @Timestamp Instant ts, @Ele...
public static boolean isIPv6MixedAddress(final String input) { int splitIndex = input.lastIndexOf(':'); if (splitIndex == -1) { return false; } //the last part is a ipv4 address boolean ipv4PartValid = isIPv4Address(input.substring(splitIndex + 1)); ...
@Test void isIPv6MixedAddress() { assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18")); assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18")); assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA")); }
@Override @CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理 public void updateSmsTemplate(SmsTemplateSaveReqVO updateReqVO) { // 校验存在 validateSmsTemplateExists(updateReqVO.getId()); // 校验短信渠道 SmsChann...
@Test public void testUpdateSmsTemplate_notExists() { // 准备参数 SmsTemplateSaveReqVO reqVO = randomPojo(SmsTemplateSaveReqVO.class); // 调用, 并断言异常 assertServiceException(() -> smsTemplateService.updateSmsTemplate(reqVO), SMS_TEMPLATE_NOT_EXISTS); }
static void printEntries(PrintWriter writer, String intro, OptionalInt screenWidth, List<String> entries) { if (entries.isEmpty()) { return; } if (!intro.isEmpty()) { writer.println(int...
@Test public void testPrintEntries() throws Exception { try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { try (PrintWriter writer = new PrintWriter(new OutputStreamWriter( stream, StandardCharsets.UTF_8))) { LsCommandHandler.printEntries(write...
public void process() throws Exception { if (_segmentMetadata.getTotalDocs() == 0) { LOGGER.info("Skip preprocessing empty segment: {}", _segmentMetadata.getName()); return; } // Segment processing has to be done with a local directory. File indexDir = new File(_indexDirURI); // ...
@Test public void testV3CleanupH3AndTextIndices() throws Exception { constructV3Segment(); SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(_indexDir); assertEquals(segmentMetadata.getVersion(), SegmentVersion.v3); // V3 use single file for all column indices. File segmentDirec...
static Map<Integer, COSObjectable> getNumberTreeAsMap(PDNumberTreeNode tree) throws IOException { if (tree == null) { return new LinkedHashMap<>(); } Map<Integer, COSObjectable> numbers = tree.getNumbers(); if (numbers == null) { nu...
@Test void testParentTree() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3999-GeneralForbearance.pdf"))) { PDStructureTreeRoot structureTreeRoot = doc.getDocumentCatalog().getStructureTreeRoot(); PDNumberTreeNod...
public List<Flow> convertFlows(String componentName, @Nullable DbIssues.Locations issueLocations) { if (issueLocations == null) { return Collections.emptyList(); } return issueLocations.getFlowList().stream() .map(sourceFlow -> toFlow(componentName, sourceFlow)) .collect(Collectors.toColle...
@Test public void convertFlows_withNullDbLocations_returnsEmptyList() { assertThat(flowGenerator.convertFlows(COMPONENT_NAME, null)).isEmpty(); }
BackgroundJobRunner getBackgroundJobRunner(Job job) { assertJobExists(job.getJobDetails()); return backgroundJobRunners.stream() .filter(jobRunner -> jobRunner.supports(job)) .findFirst() .orElseThrow(() -> problematicConfigurationException("Could not find...
@Test void getBackgroundJobRunnerForJobThatCannotBeRun() { final Job job = anEnqueuedJob() .<TestServiceThatCannotBeRun>withJobDetails(ts -> ts.doWork()) .build(); assertThatThrownBy(() -> backgroundJobServer.getBackgroundJobRunner(job)) .isInstanceOf(...
public static void validatePath(String path) throws InvalidPathException { boolean invalid = (path == null || path.isEmpty()); if (!OSUtils.isWindows()) { invalid = (invalid || !path.startsWith(AlluxioURI.SEPARATOR)); } if (invalid) { throw new InvalidPathException(ExceptionMessage.PATH_INV...
@Test public void validatePath() throws InvalidPathException { // check valid paths PathUtils.validatePath("/foo/bar"); PathUtils.validatePath("/foo/bar/"); PathUtils.validatePath("/foo/./bar/"); PathUtils.validatePath("/foo/././bar/"); PathUtils.validatePath("/foo/../bar"); PathUtils.vali...
@Override protected void runTask() { LOGGER.trace("Looking for scheduled jobs... "); Instant scheduledBefore = now().plus(backgroundJobServerConfiguration().getPollInterval()); processManyJobs(previousResults -> getJobsToSchedule(scheduledBefore, previousResults), Job::enqueu...
@Test void testTask() { final Job scheduledJob = aScheduledJob().build(); when(storageProvider.getScheduledJobs(any(), any(AmountRequest.class))).thenReturn(singletonList(scheduledJob), emptyJobList()); runTask(task); verify(storageProvider).save(jobsToSaveArgumentCaptor.capture()...
@Udf public <T> boolean contains( @UdfParameter final List<T> array, @UdfParameter final T val ) { return array != null && array.contains(val); }
@Test public void shouldNotFindValuesInNullListElements() { assertTrue(udf.contains(Collections.singletonList(null), null)); assertFalse(udf.contains(Collections.singletonList(null), "null")); assertFalse(udf.contains(Collections.singletonList(null), true)); assertFalse(udf.contains(Collections.single...
public final TraceContext decorate(TraceContext context) { long traceId = context.traceId(), spanId = context.spanId(); E claimed = null; int existingIndex = -1, extraLength = context.extra().size(); for (int i = 0; i < extraLength; i++) { Object next = context.extra().get(i); if (next inst...
@Test void decorate_forksWhenFieldsAlreadyClaimed() { TraceContext other = TraceContext.newBuilder().traceId(98L).spanId(99L).build(); BasicMapExtra claimed = factory.decorate(other).findExtra(BasicMapExtra.class); List<TraceContext> contexts = asList( context.toBuilder().addExtra(claimed).build(),...
@Override public byte[] decrypt(byte[] bytes, KeyType keyType) { // 在非使用BC库情况下,blockSize使用默认的算法 if (this.decryptBlockSize < 0 && null == GlobalBouncyCastleProvider.INSTANCE.getProvider()) { // 加密数据长度 <= 模长-11 this.decryptBlockSize = ((RSAKey) getKeyByType(keyType)).getModulus().bitLength() / 8; } return ...
@Test public void rsaDecodeTest() { final String PRIVATE_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIL7pbQ+5KKGYRhw7jE31hmA" // + "f8Q60ybd+xZuRmuO5kOFBRqXGxKTQ9TfQI+aMW+0lw/kibKzaD/EKV91107xE384qOy6IcuBfaR5lv39OcoqNZ"// + "5l+Dah5ABGnVkBP9fKOFhPgghBknTRo0/rZFGI6Q1UHXb+4atP++LNFlDymJcPAgMBAAECgY...
public static Map<String, Integer> retrieveTags(Note note) { HashMap<String, Integer> tagsMap = new HashMap<>(); String[] words = (note.getTitle() + " " + note.getContent()).replaceAll("\n", " ").trim() .split(" "); for (String word : words) { String parsedHashtag = UrlCompleter.parseHashtag(w...
@Test public void retrievesTagsFromNote() { Map<String, Integer> tags = TagsHelper.retrieveTags(note); assertEquals(4, tags.size()); assertTrue(tags.containsKey(TAG1.getText()) && tags.containsKey(TAG2.getText()) && tags.containsKey(TAG3.getText()) && tags.containsKey(TAG4.getText())); assertF...
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext ctx) { log.fine(() -> String.format("retryRequest(exception='%s', executionCount='%d', ctx='%s'", exception.getClass().getName(), executionCount, ctx)); HttpClientContext...
@Test void retries_for_listed_exceptions_until_max_retries_exceeded() { int maxRetries = 2; DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder .withFixedDelay(Duration.ofSeconds(2), maxRetries) .retryForExceptions(List.of(SSLExcep...
public ColumnName getName() { return name; }
@Test public void shouldReturnName() { // Given: final TableElement element = new TableElement(NAME, new Type(SqlTypes.STRING), NO_COLUMN_CONSTRAINTS); // Then: assertThat(element.getName(), is(NAME)); }
public static String getCheckJobIdsRootPath(final String jobId) { return String.join("/", getJobRootPath(jobId), "check", "job_ids"); }
@Test void assertGetCheckJobIdsPath() { assertThat(PipelineMetaDataNode.getCheckJobIdsRootPath(jobId), is(jobCheckRootPath + "/job_ids")); }
public static MemberLookup createLookUp(ServerMemberManager memberManager) throws NacosException { if (!EnvUtil.getStandaloneMode()) { String lookupType = EnvUtil.getProperty(LOOKUP_MODE_TYPE); LookupType type = chooseLookup(lookupType); LOOK_UP = find(type); curr...
@Test void createLookUpStandaloneMemberLookup() throws NacosException { EnvUtil.setIsStandalone(true); memberLookup = LookupFactory.createLookUp(memberManager); assertEquals(StandaloneMemberLookup.class, memberLookup.getClass()); }
@Override public HttpResponseOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final DelayedHttpEntityCallable<Node> command = new DelayedHttpEntityCallable<Node>(file) { @Override public Node call(f...
@Test public void testReadWrite() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path room = new DeepboxDirector...
public void addEntity(Entity entity) { entities.add(entity); }
@Test void testAddEntity() { var entity = new Skeleton(1); world.addEntity(entity); assertEquals(entity, world.entities.get(0)); }
protected FixedTemplate(Object object, FixedDataSchema schema) throws TemplateOutputCastException { Class<?> objectClass = object.getClass(); if (objectClass == String.class) { String data = (String) object; if (data.length() != schema.getSize()) { throw new TemplateOutputCastExce...
@Test public void testFixedTemplate() { String goodObjects[] = { "12345", "ABCDF" }; ByteString goodByteStrings[] = { ByteString.copyAvroString("qwert", false) }; Object badObjects[] = { "", "1", "12", "123", "1234", "1234\u0100", "123456", 1, 2.0f, 3.0,...
@Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns...
@Test void shouldCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("other.domain.com")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); ...
public static String toJson(MetadataUpdate metadataUpdate) { return toJson(metadataUpdate, false); }
@Test public void testSetSnapshotRefBranchToJsonAllFields() { long snapshotId = 1L; SnapshotRefType type = SnapshotRefType.BRANCH; String refName = "hank"; Integer minSnapshotsToKeep = 2; Long maxSnapshotAgeMs = 3L; Long maxRefAgeMs = 4L; String expected = "{\"action\":\"set-snapsh...
@Override public String convertToDatabaseColumn(Map<String, String> attribute) { return GSON.toJson(attribute); }
@Test void convertToDatabaseColumn_null() { assertEquals("null", this.converter.convertToDatabaseColumn(null)); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TopicIdPartition that = (TopicIdPartition) o; return topicId.equals(that.topicId) && topic...
@Test public void testEquals() { assertEquals(topicIdPartition0, topicIdPartition1); assertEquals(topicIdPartition1, topicIdPartition0); assertEquals(topicIdPartitionWithNullTopic0, topicIdPartitionWithNullTopic1); assertNotEquals(topicIdPartition0, topicIdPartition2); asser...
static Future<Secret> getValidatedSecret(SecretOperator secretOperator, String namespace, String name, String... items) { return secretOperator.getAsync(namespace, name) .compose(secret -> validatedSecret(namespace, name, secret, items)); }
@Test void testGetValidateSecret() { String namespace = "ns"; String secretName = "my-secret"; Secret secret = new SecretBuilder() .withNewMetadata() .withName(secretName) .withNamespace(namespace) .endMetadata() ...
public boolean isRunning() { return isRunning.get(); }
@Test public void testServerStartOnCreation() { assertTrue(application.isRunning()); }
@Override public List<Type> getColumnTypes() { return columnTypes; }
@Test public void testGetColumnTypes() { RecordSet recordSet = new JdbcRecordSet(jdbcClient, session, split, ImmutableList.of( new JdbcColumnHandle("test", "text", JDBC_VARCHAR, VARCHAR, true, Optional.empty()), new JdbcColumnHandle("test", "text_short", JDBC_VARCHAR, cre...
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@Test public void testPartitionedHours() throws Exception { createPartitionedTable(spark, tableName, "hours(ts)"); SparkScanBuilder builder = scanBuilder(); HoursFunction.TimestampToHoursFunction function = new HoursFunction.TimestampToHoursFunction(); UserDefinedScalarFunc udf = toUDF(function, exp...
public static AnnotateImagesFromBytesWithContext annotateImagesFromBytesWithContext( List<Feature> features, long batchSize, int desiredRequestParallelism) { return new AnnotateImagesFromBytesWithContext(features, batchSize, desiredRequestParallelism); }
@Test public void shouldConvertKVOfBytesToRequest() { CloudVision.AnnotateImagesFromBytesWithContext annotateImagesFromBytesWithContext = CloudVision.annotateImagesFromBytesWithContext(features, 1, 1); AnnotateImageRequest request = annotateImagesFromBytesWithContext.mapToRequest(KV.of(TEST_BY...
protected Object getValidJMSHeaderValue(String headerName, Object headerValue) { if (headerValue instanceof String) { return headerValue; } else if (headerValue instanceof BigInteger) { return headerValue.toString(); } else if (headerValue instanceof BigDecimal) { ...
@Test public void testGetValidJmsHeaderValueWithIso8601DateShouldSucceed() { when(mockJmsConfiguration.isFormatDateHeadersToIso8601()).thenReturn(true); Object value = jmsBindingUnderTest.getValidJMSHeaderValue("foo", Date.from(instant)); assertEquals("2018-02-26T19:12:18Z", value); }
@Override public void onSwipeLeft(boolean twoFingers) {}
@Test public void testOnSwipeLeft() { mUnderTest.onSwipeLeft(true); Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction); }
public static Upstream selector(final List<Upstream> upstreamList, final String algorithm, final String ip) { LoadBalancer loadBalance = ExtensionLoader.getExtensionLoader(LoadBalancer.class).getJoin(algorithm); return loadBalance.select(upstreamList, ip); }
@Test public void loadBalanceUtilsOrderedWeightTest() { List<Upstream> upstreamList = Stream.of(10, 20, 70) .map(weight -> Upstream.builder() .url("upstream-" + weight) .weight(weight) ...
@Override protected Monitor createMonitor(URL url) { URLBuilder urlBuilder = URLBuilder.from(url); urlBuilder.setProtocol(url.getParameter(PROTOCOL_KEY, DUBBO_PROTOCOL)); if (StringUtils.isEmpty(url.getPath())) { urlBuilder.setPath(MonitorService.class.getName()); } ...
@Test void testCreateMonitor() { URL urlWithoutPath = URL.valueOf("http://10.10.10.11"); Monitor monitor = dubboMonitorFactory.createMonitor(urlWithoutPath); assertThat(monitor, not(nullValue())); URL urlWithFilterKey = URL.valueOf("http://10.10.10.11/").addParameter(REFERENCE_FILTE...
public static String format(String source, Object... parameters) { String current = source; for (Object parameter : parameters) { if (!current.contains("{}")) { return current; } current = current.replaceFirst("\\{\\}", String.valueOf(parameter)); ...
@Test public void testFormatExtraBracket() { String fmt = "Some string {} 2 {}"; assertEquals("Some string 1 2 {}", format(fmt, 1)); }
public String determineRootDir(String location) { int prefixEnd = location.indexOf(':') + 1; int rootDirEnd = location.length(); while (rootDirEnd > prefixEnd && isPattern(location.substring(prefixEnd, rootDirEnd))) { rootDirEnd = location.lastIndexOf('/', rootDirEnd - 2) + 1; ...
@Test public void testDetermineRoot() { AntPathMatcher matcher = new AntPathMatcher(); assertEquals("org/apache/camel", matcher.determineRootDir("org/apache/camel")); assertEquals("org/apache/camel/", matcher.determineRootDir("org/apache/camel/")); assertEquals("org/apache/camel/", m...
public Group getGroup(JID jid) throws GroupNotFoundException { JID groupJID = GroupJID.fromJID(jid); return (groupJID instanceof GroupJID) ? getGroup(((GroupJID)groupJID).getGroupName()) : null; }
@Test public void aForceLookupHitWillIgnoreTheExistingCache() throws Exception { groupCache.put(GROUP_NAME, CacheableOptional.of(cachedGroup)); doReturn(unCachedGroup).when(groupProvider).getGroup(GROUP_NAME); final Group returnedGroup = groupManager.getGroup(GROUP_NAME, true); ass...
@Override public Result apply(PathData item, int depth) throws IOException { if (expression != null) { return expression.apply(item, -1); } return Result.PASS; }
@Test public void apply() throws IOException { PathData item = mock(PathData.class); when(expr.apply(item, -1)).thenReturn(Result.PASS).thenReturn(Result.FAIL); assertEquals(Result.PASS, test.apply(item, -1)); assertEquals(Result.FAIL, test.apply(item, -1)); verify(expr, times(2)).apply(item, -1);...
@Bean("dispatcherHandler") public DispatcherHandler dispatcherHandler() { return new DispatcherHandler(); }
@Test public void testDispatcherHandler() { applicationContextRunner.run(context -> { DispatcherHandler handler = context.getBean("dispatcherHandler", DispatcherHandler.class); assertNotNull(handler); } ); }
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testExpire() throws InterruptedException { RLock lock = redisson.getLock("lock"); lock.lock(2, TimeUnit.SECONDS); final long startTime = System.currentTimeMillis(); Thread t = new Thread() { public void run() { RLock lock1 = redisson.get...
public static int getEditDistance( String source, String target, boolean caseSensitive, int changeCost, int openGapCost, int continueGapCost) { if (!caseSensitive) { source = Ascii.toLowerCase(source); target = Ascii.toLowerCase(target); } int sourceLength =...
@Test public void needlemanWunschEditDistance_matchesLevenschtein_withHugeGapCost() { String identifier = "fooBar"; String otherIdentifier = "bazQux"; double levenschtein = LevenshteinEditDistance.getEditDistance(identifier, otherIdentifier); double needlemanWunsch = NeedlemanWunschEditDistan...
public static void isGreaterThanOrEqualTo(int value, int minimumValue) { isGreaterThanOrEqualTo( value, minimumValue, String.format("value [%s] is less than minimum value [%s]", value, minimumValue)); }
@Test public void testIsGreaterThanOrEqualTo1() { Precondition.isGreaterThanOrEqualTo(1, 1); }
public ConfigCenterBuilder appendParameter(String key, String value) { this.parameters = appendParameter(this.parameters, key, value); return getThis(); }
@Test void appendParameter() { ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey...
@Override public TaskType taskType() { return taskType; }
@Test public void shouldReportTaskType() { ProcessorStateManager stateMgr = getStateManager(Task.TaskType.STANDBY); assertEquals(Task.TaskType.STANDBY, stateMgr.taskType()); stateMgr = getStateManager(Task.TaskType.ACTIVE); assertEquals(Task.TaskType.ACTIVE, stateMgr.taskType()); ...
@Override public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) { ParamCheckResponse paramCheckResponse = new ParamCheckResponse(); if (paramInfos == null) { paramCheckResponse.setSuccess(true); return paramCheckResponse; } for (ParamInfo pa...
@Test void testCheckParamInfoForMetadata() { ParamInfo paramInfo = new ParamInfo(); ArrayList<ParamInfo> paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); Map<String, String> metadata = new HashMap<>(); paramInfo.setMetadata(metadata); // Max length m...
public Set<String> makeReady(final Map<String, InternalTopicConfig> topics) { // we will do the validation / topic-creation in a loop, until we have confirmed all topics // have existed with the expected number of partitions, or some create topic returns fatal errors. log.debug("Starting to vali...
@Test public void shouldExhaustRetriesOnTimeoutExceptionForMakeReady() { mockAdminClient.timeoutNextRequest(5); final InternalTopicManager topicManager = new InternalTopicManager( new AutoAdvanceMockTime(time), mockAdminClient, new StreamsConfig(confi...
@Override public void processElement(StreamRecord<RowData> element) throws Exception { RowData inputRow = element.getValue(); long timestamp; if (windowAssigner.isEventTime()) { if (inputRow.isNullAt(rowtimeIndex)) { // null timestamp would be dropped ...
@Test public void testTumblingWindows() throws Exception { final TumblingWindowAssigner assigner = TumblingWindowAssigner.of(Duration.ofSeconds(3)); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(assigner, shiftTimeZone); testHarness.setup...
@Override @SuppressWarnings("unchecked") public CalendarEventModel apply(Map<String, Object> event, TransformerContext context) { if (!"singleInstance" .equals(event.get("type"))) { // support single instances for now;recurring events later return null; } String calendarId = context.getPro...
@SuppressWarnings("unchecked") @Test public void testTransform() throws IOException { context.setProperty(CALENDAR_ID, "123"); Map<String, Object> rawEvent = mapper.readValue(SAMPLE_CALENDAR_EVENT, Map.class); CalendarEventModel event = transformer.apply(rawEvent, context); assertEquals("123", eve...
public ParseResult parse(File file) throws IOException, SchemaParseException { return parse(file, null); }
@Test void testParseStream() throws IOException { Schema schema = new SchemaParser().parse(new ByteArrayInputStream(SCHEMA_JSON.getBytes(StandardCharsets.UTF_16))) .mainSchema(); assertEquals(SCHEMA_REAL, schema); }
@Override public String normalise(String text) { if (Objects.isNull(text) || text.isEmpty()) { throw new IllegalArgumentException("Text cannot be null or empty"); } return text.trim() .toLowerCase() .replaceAll("\\p{Punct}", "") .replaceAll("\\s+", " "); }
@Description("Normalise, when text is null, then throw IllegalArgumentException") @Test void normalise_WhenTextIsNull_ThenThrowIllegalArgumentException() { // When & Then assertThrows(IllegalArgumentException.class, () -> textNormaliser.normalise(null)); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) throws IOException { try { oAuthCsrfVerifier.verifyState(request, response, samlIdentityProvider, "CSRFToken"); } catch (AuthenticationException exception) { AuthenticationError.handleError(request,...
@Test public void do_filter_admin() throws IOException { HttpServletRequest servletRequest = spy(HttpServletRequest.class); HttpServletResponse servletResponse = mock(HttpServletResponse.class); StringWriter stringWriter = new StringWriter(); doReturn(new PrintWriter(stringWriter)).when(servletRespons...
@Override public void publishLeaderInformation(String componentId, LeaderInformation leaderInformation) { Preconditions.checkState(running.get()); if (!leaderLatch.hasLeadership()) { return; } final String connectionInformationPath = ZooKeeperUtils.gener...
@Test void testPublishEmptyLeaderInformation() throws Exception { new Context() { { runTest( () -> { leaderElectionListener.await(LeaderElectionEvent.IsLeaderEvent.class); final String componentId = ...
public static SupportedVersionRange fromMap(Map<String, Short> versionRangeMap) { return new SupportedVersionRange( BaseVersionRange.valueOrThrow(MIN_VERSION_KEY_LABEL, versionRangeMap), BaseVersionRange.valueOrThrow(MAX_VERSION_KEY_LABEL, versionRangeMap)); }
@Test public void testFromMapFailure() { // min_version can't be < 0. Map<String, Short> invalidWithBadMinVersion = mkMap(mkEntry("min_version", (short) -1), mkEntry("max_version", (short) 0)); assertThrows( IllegalArgumentException.class, () -> SupportedV...
public static boolean startsWithScheme( String vfsFileName ) { FileSystemManager fsManager = getInstance().getFileSystemManager(); boolean found = false; String[] schemes = fsManager.getSchemes(); for (int i = 0; i < schemes.length; i++) { if ( vfsFileName.startsWith( schemes[i] + ":" ) ) { ...
@Test public void testStartsWithScheme() { String fileName = "zip:file:///SavedLinkedres.zip!Calculate median and percentiles using the group by steps.ktr"; assertTrue( KettleVFS.startsWithScheme( fileName ) ); fileName = "SavedLinkedres.zip!Calculate median and percentiles using the group by steps.ktr";...
public SSLContext createContext(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, CertificateException { SSLContext sslContext = getProvider() != null ? SSLContext.getInstance(getProtocol(), getProvi...
@Test public void testCreateContext() throws Exception { factoryBean.setKeyManagerFactory(keyManagerFactory); factoryBean.setKeyStore(keyStore); factoryBean.setTrustManagerFactory(trustManagerFactory); factoryBean.setTrustStore(trustStore); factoryBean.setSecureRandom(secureR...
@Override public double calcNormalizedEdgeDistance(double ry, double rx, double ay, double ax, double by, double bx) { return calcNormalizedEdgeDistance3D( ry, rx, 0, ay, ax, 0, by, ...
@Test public void testCalcNormalizedEdgeDistance() { DistanceCalcEuclidean distanceCalc = new DistanceCalcEuclidean(); double distance = distanceCalc.calcNormalizedEdgeDistance(0, 10, 0, 0, 10, 10); assertEquals(50, distance, 0); }
public static UnixMountInfo parseMountInfo(String line) { // Example mount lines: // ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb) // map -hosts on /net (autofs, nosuid, automounted, nobrowse) UnixMountInfo.Builder builder = new UnixMountInfo.Builder(); // First get and remove the mount t...
@Test public void parseRamfsMountInfoWithType() throws Exception { // Linux mount info. UnixMountInfo info = ShellUtils.parseMountInfo("ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb)"); assertEquals(Optional.of("ramfs"), info.getDeviceSpec()); assertEquals(Optional.of("/mnt/ramdisk"),...
public static <T> T checkFoundWithOptional(java.util.Optional<T> value, String message, Object... messageArguments) { if (!value.isPresent()) { throw new NotFoundException(format(message, messageArguments)); } return value.get(); }
@Test public void checkFoundWithOptional_throws_NotFoundException_if_empty_and_formats_message() { String message = "foo %s"; assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFoundWithOptional(Optional.empty(), message, "bar")) .withMessage("foo bar"); }
public static boolean hasRestartMethods(Class<? extends ConfigInstance> configClass) { try { configClass.getDeclaredMethod("containsFieldsFlaggedWithRestart"); configClass.getDeclaredMethod("getChangesRequiringRestart", configClass); return true; } catch (NoSuchMethod...
@Test void requireThatRestartMethodsAreDetectedProperly() { assertFalse(ReflectionUtil.hasRestartMethods(NonRestartConfig.class)); assertTrue(ReflectionUtil.hasRestartMethods(RestartConfig.class)); }
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("position") BigDecimal position, @ParameterName("newItem") Object newItem) { if (list == null) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", CANNO...
@Test void invokeReplaceByNegativePositionWithNotNull() { List list = getList(); List expected = new ArrayList<>(list); expected.set(2, "test"); FunctionTestUtil.assertResult(listReplaceFunction.invoke(list, BigDecimal.valueOf(-1), "test"), expected); }
public void setUsers(List<?> users) { userPasswords.clear(); userGroups.clear(); for (Iterator<?> it = users.iterator(); it.hasNext();) { AuthenticationUser user = (AuthenticationUser)it.next(); userPasswords.put(user.getUsername(), user.getPassword()); Set<Pr...
@Test public void testSetUsers() { AuthenticationUser alice = new AuthenticationUser("alice", "password", "group1"); AuthenticationUser bob = new AuthenticationUser("bob", "security", "group2"); SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(); authe...
@Override public Publisher<Exchange> from(String uri) { final String name = publishedUriToStream.computeIfAbsent(uri, camelUri -> { try { String uuid = context.getUuidGenerator().generateUuid(); RouteBuilder.addRoutes(context, rb -> rb.from(camelUri).to("reactive...
@Test public void testFrom() throws Exception { context.start(); Publisher<Exchange> timer = crs.from("timer:reactive?period=250&repeatCount=3&includeMetadata=true"); AtomicInteger value = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(3); Flux.from(timer) ...
@Override public Num calculate(BarSeries series, Position position) { if (position.isClosed()) { final int exitIndex = position.getExit().getIndex(); final int entryIndex = position.getEntry().getIndex(); return series.numOf(exitIndex - entryIndex + 1); } ...
@Test public void calculateWithNoPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); AnalysisCriterion numberOfBars = getCriterion(); assertNumEquals(0, numberOfBars.calculate(series, new BaseTradingRecord())); }
public void lock(long lockedByPipelineId) { this.lockedByPipelineId = lockedByPipelineId; locked = true; }
@Test void shouldBeEqualToAnotherPipelineStateIfBothDoNotHaveLockedBy() { PipelineState pipelineState1 = new PipelineState("p"); PipelineState pipelineState2 = new PipelineState("p"); pipelineState1.lock(1); pipelineState2.lock(1); assertThat(pipelineState2).isEqualTo(pipelin...
public IntersectOperator(OpChainExecutionContext opChainExecutionContext, List<MultiStageOperator> inputOperators, DataSchema dataSchema) { super(opChainExecutionContext, inputOperators, dataSchema); }
@Test public void testIntersectOperator() { DataSchema schema = new DataSchema(new String[]{"int_col", "string_col"}, new DataSchema.ColumnDataType[]{ DataSchema.ColumnDataType.INT, DataSchema.ColumnDataType.STRING }); Mockito.when(_leftOperator.nextBlock()) .thenReturn(OperatorTestUtil.bl...
public boolean fileIsInAllowedPath(Path path) { if (allowedPaths.isEmpty()) { return true; } final Path realFilePath = resolveRealPath(path); if (realFilePath == null) { return false; } for (Path allowedPath : allowedPaths) { final Pat...
@Test public void inAllowedPath() throws IOException { final Path permittedPath = permittedTempDir.getRoot().toPath(); final Path filePath = permittedTempDir.newFile(FILE).toPath(); pathChecker = new AllowedAuxiliaryPathChecker(new TreeSet<>(Collections.singleton(permittedPath))); as...
public int generateWorkerId(final Properties props) { Preconditions.checkArgument(workerIdGenerator.get() != null, "Worker id generator is not initialized."); int result = workerIdGenerator.get().generate(props); instance.setWorkerId(result); return result; }
@Test void assertGenerateWorkerId() { ComputeNodeInstanceContext context = new ComputeNodeInstanceContext( new ComputeNodeInstance(mock(InstanceMetaData.class)), mock(WorkerIdGenerator.class), modeConfig, lockContext, eventBusContext); assertThat(context.generateWorkerId(new Properti...
@Override public void writeTo(ByteBuf byteBuf) throws LispWriterException { WRITER.writeTo(byteBuf, this); }
@Test public void testSerialization() throws LispReaderException, LispWriterException, LispParseError, DeserializationException { ByteBuf byteBuf = Unpooled.buffer(); MapReferralWriter writer = new MapReferralWriter(); writer.writeTo(byteBuf, referral1); MapReferralRead...
@Override @SuppressWarnings("unchecked") public Neighbor<double[], E>[] search(double[] q, int k) { if (k < 1) { throw new IllegalArgumentException("Invalid k: " + k); } Set<Integer> candidates = getCandidates(q); k = Math.min(k, candidates.size()); HeapSele...
@Test public void testKnn() { System.out.println("knn"); int[] recall = new int[testx.length]; for (int i = 0; i < testx.length; i++) { int k = 7; Neighbor[] n1 = lsh.search(testx[i], k); Neighbor[] n2 = naive.search(testx[i], k); for (Neighbo...
@Override public void close() throws IOException { if (mUfsInStream.isPresent()) { mUfsInStream.get().close(); mUfsInStream = Optional.empty(); } }
@Test public void readWithNullUfsStream() { assertThrows(NullPointerException.class, () -> new UfsFileInStream(null, 0L).close()); }
static Set<PipelineOptionSpec> getOptionSpecs( Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) { Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods); ImmutableSe...
@Test public void testShouldSerialize() { Set<PipelineOptionSpec> properties = PipelineOptionsReflector.getOptionSpecs(JsonIgnoreOptions.class, true); assertThat(properties, hasItem(allOf(hasName("notIgnored"), shouldSerialize()))); assertThat(properties, hasItem(allOf(hasName("ignored"), not(sho...
static <T> Optional<T> lookupByNameAndType(CamelContext camelContext, String name, Class<T> type) { return Optional.ofNullable(ObjectHelper.isEmpty(name) ? null : name) .map(n -> EndpointHelper.isReferenceParameter(n) ? EndpointHelper.resolveReferenceParameter(camelContex...
@Test void testLookupByNameAndTypeWithReferenceParameter() { String name = "#referenceParameter"; when(camelContext.getRegistry()).thenReturn(mockRegistry); Optional<Object> object = DynamicRouterRecipientListHelper.lookupByNameAndType(camelContext, name, Object.class); Assertions.as...
@Override public List<Operation> parse(String statement) { CalciteParser parser = calciteParserSupplier.get(); FlinkPlannerImpl planner = validatorSupplier.get(); Optional<Operation> command = EXTENDED_PARSER.parse(statement); if (command.isPresent()) { return Collection...
@Test void testParseLegalStatements() { for (TestSpec spec : TEST_SPECS) { if (spec.expectedSummary != null) { Operation op = parser.parse(spec.statement).get(0); assertThat(op.asSummaryString()).isEqualTo(spec.expectedSummary); } if (spec...
@Override public ConfigDef config() { return CONFIG_DEF; }
@Test public void testPatternRequiredInConfig() { Map<String, String> props = new HashMap<>(); ConfigException e = assertThrows(ConfigException.class, () -> config(props)); assertTrue(e.getMessage().contains("Missing required configuration \"pattern\"")); }
@Override public void renameTable(ObjectPath tablePath, String newTableName, boolean ignoreIfNotExists) throws TableNotExistException, TableAlreadyExistException, CatalogException { checkNotNull(tablePath, "Table path cannot be null"); checkArgument( !isNullOrWhitespaceOnly(newTableName), "New t...
@Test public void testRenameTable() throws Exception { Map<String, String> originOptions = new HashMap<>(); originOptions.put(FactoryUtil.CONNECTOR.key(), "hudi"); CatalogTable originTable = new CatalogTableImpl(schema, partitions, originOptions, "hudi table"); hoodieCatalog.createTable(tableP...
static Serde<List<?>> createSerde(final PersistenceSchema schema) { final List<SimpleColumn> columns = schema.columns(); if (columns.isEmpty()) { // No columns: return new KsqlVoidSerde<>(); } if (columns.size() != 1) { throw new KsqlException("The '" + FormatFactory.KAFKA.name() ...
@Test public void shouldThrowIfMap() { // Given: final PersistenceSchema schema = schemaWithFieldOfType( SqlTypes.map(SqlTypes.STRING, SqlTypes.STRING )); // When: final Exception e = assertThrows( KsqlException.class, () -> KafkaSerdeFactory.createSerde(schema) );...
@Override void decode(ByteBufAllocator alloc, ByteBuf headerBlock, SpdyHeadersFrame frame) throws Exception { ObjectUtil.checkNotNull(headerBlock, "headerBlock"); ObjectUtil.checkNotNull(frame, "frame"); if (cumulation == null) { decodeHeaderBlock(headerBlock, frame); ...
@Test public void testMultipleValuesEndsWithNull() throws Exception { ByteBuf headerBlock = Unpooled.buffer(28); headerBlock.writeInt(1); headerBlock.writeInt(4); headerBlock.writeBytes(nameBytes); headerBlock.writeInt(12); headerBlock.writeBytes(valueBytes); ...