focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public PMML_MODEL getPMMLModelType(){ return PMML_MODEL.TREE_MODEL; }
@Test void getPMMLModelType() { assertThat(evaluator.getPMMLModelType()).isEqualTo(PMML_MODEL.TREE_MODEL); }
@VisibleForTesting static Map<String, Object> serializableHeaders(Map<String, Object> headers) { Map<String, Object> returned = new HashMap<>(); if (headers != null) { for (Map.Entry<String, Object> h : headers.entrySet()) { Object value = h.getValue(); if (value instanceof List<?>) { ...
@Test public void testSerializableHeadersWithLongStringValues() { Map<String, Object> rawHeaders = new HashMap<>(); String key1 = "key1", key2 = "key2", value1 = "value1", value2 = "value2"; rawHeaders.put(key1, LongStringHelper.asLongString(value1)); rawHeaders.put(key2, LongStringHelper.asLongString...
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) { if (LOG.isTraceEnabled()) { LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}" + " Used Normalized Resources: {} Total Normalized Resources:...
@Test public void testCalculateMinWithTooLittleResourceInTotal() { Map<String, Double> allResourcesMap = new HashMap<>(); allResourcesMap.put(Constants.COMMON_CPU_RESOURCE_NAME, 2.0); allResourcesMap.put(gpuResourceName, 1.0); NormalizedResources resources = new NormalizedResources(n...
@Override protected void copy(List<HadoopResourceId> srcResourceIds, List<HadoopResourceId> destResourceIds) throws IOException { for (int i = 0; i < srcResourceIds.size(); ++i) { // this enforces src and dest file systems to match final org.apache.hadoop.fs.FileSystem fs = srcResource...
@Test public void testCopy() throws Exception { create("testFileA", "testDataA".getBytes(StandardCharsets.UTF_8)); create("testFileB", "testDataB".getBytes(StandardCharsets.UTF_8)); fileSystem.copy( ImmutableList.of(testPath("testFileA"), testPath("testFileB")), ImmutableList.of(testPath("...
public void performSortOperation(int option, List<File> pdf) { switch (option) { case DATE_INDEX: sortFilesByDateNewestToOldest(pdf); break; case NAME_INDEX: sortByNameAlphabetical(pdf); break; case SIZE_INCREASI...
@Test public void shouldReturnArraySortedAlphabetically() throws IOException { // given // (for some reason sorting mocks doesn't work) List<String> paths = getPaths(); mFiles = new ArrayList<>(paths.size()); for (String item : paths) { File f = new File(item); ...
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testStateParameterNoAnnotation() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("missing StateId annotation"); thrown.expectMessage("myProcessElement"); thrown.expectMessage("index 1"); thrown.expectMessage(not(mentionsTimers())); DoFnS...
String upload(File report) { LOG.debug("Upload report"); long startTime = System.currentTimeMillis(); Part filePart = new Part(MediaTypes.ZIP, report); PostRequest post = new PostRequest("api/ce/submit") .setMediaType(MediaTypes.PROTOBUF) .setParam("projectKey", moduleHierarchy.root().key())...
@Test public void upload_error_message() { HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}"); WsResponse response = mock(WsResponse.class); when(response.failIfNotSuccessful()).thenThrow(ex); when(wsClient.call(any(WsRequest.c...
public ForComputation forComputation(String computation) { return new ForComputation(computation); }
@Test public void testBadCoderEquality() throws Exception { WindmillStateCache.ForKeyAndFamily keyCache1 = cache.forComputation(COMPUTATION).forKey(COMPUTATION_KEY, 0L, 0L).forFamily(STATE_FAMILY); StateTag<TestState> tag = new TestStateTagWithBadEquality("tag1"); keyCache1.put(StateNamespaces.gl...
@Override public void handle(ContainersLauncherEvent event) { // TODO: ContainersLauncher launches containers one by one!! Container container = event.getContainer(); ContainerId containerId = container.getContainerId(); switch (event.getType()) { case LAUNCH_CONTAINER: Application app =...
@SuppressWarnings("unchecked") @Test public void testLaunchContainerEvent() throws IllegalArgumentException { Map<ContainerId, ContainerLaunch> dummyMap = spy.running; when(event.getType()) .thenReturn(ContainersLauncherEventType.LAUNCH_CONTAINER); assertEquals(0, dummyMap.size()); spy...
@Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { int initLength = toAppendTo.length(); super.format(number, toAppendTo, pos); return pad(toAppendTo, initLength); }
@Test void format() { PaddingDecimalFormat format = new PaddingDecimalFormat("0.0", 7); assertThat(format.format(1L)).isEqualTo(" 1.0"); assertThat(format.format(1000L)).isEqualTo(" 1000.0"); assertThat(format.format(10000000L)).isEqualTo("10000000.0"); }
public String cleanupDwgString(String dwgString) { String cleanString = dwgString; StringBuilder sb = new StringBuilder(); //Strip off start/stop underline/overstrike/strike throughs Matcher m = Pattern.compile(underlineStrikeThrough).matcher(cleanString); while (m.find()) { ...
@Test public void testStackedFractions() { String formatted = "abc \\S+0,8^+0,1; efg"; DWGReadFormatRemover dwgReadFormatter = new DWGReadFormatRemover(); String expected = "abc +0,8/+0,1 efg"; assertEquals(expected, dwgReadFormatter.cleanupDwgString(formatted)); }
Optional<String> getServiceProviderPrivateKey() { return configuration.get(SERVICE_PROVIDER_PRIVATE_KEY); }
@Test public void return_service_provider_private_key() { settings.setProperty("sonar.auth.saml.sp.privateKey.secured", "my_private_secret_private_key"); assertThat(underTest.getServiceProviderPrivateKey()).hasValue("my_private_secret_private_key"); }
@Override public String getHelpMessage() { return HELP; }
@Test public void shouldGetHelp() { assertThat(cmd.getHelpMessage(), is( "run script <path_to_sql_file>:" + System.lineSeparator() + "\tLoad and run the statements in the supplied file." + System.lineSeparator() + "\tNote: the file must be UTF-8 encoded.")); }
public Map<String, Diff> diffs() { if (diffs.containsKey(ASSIGNEE)) { Map<String, Diff> result = new LinkedHashMap<>(diffs); result.put(ASSIGNEE, decode(result.get(ASSIGNEE))); return result; } return diffs; }
@Test public void diffs_should_be_empty_by_default() { assertThat(diffs.diffs()).isEmpty(); }
public RestResponse<KsqlEntityList> postKsqlRequest( final String ksql, final Map<String, ?> requestProperties, final Optional<Long> previousCommandSeqNum ) { return post( KSQL_PATH, createKsqlRequest(ksql, requestProperties, previousCommandSeqNum), r -> deserialize(r.get...
@Test public void shouldUseTimeout() { // Given: ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST, ImmutableMap.of(), 300L); // When: executor.submit(() -> { try { ksqlTarget.postKsqlRequest("some ksql;", Collections.emptyMap(), Optional.e...
@Override public double read() { return gaugeSource.read(); }
@Test public void whenLongGaugeField() { SomeObject someObject = new SomeObject(); metricsRegistry.registerStaticMetrics(someObject, "foo"); DoubleGauge gauge = metricsRegistry.newDoubleGauge("foo.longField"); assertEquals(someObject.longField, gauge.read(), 0.1); }
@Override public ManifestIdentifier identify(Config config) { Path manifestFile = getFileFromProperty("android_merged_manifest"); Path resourcesDir = getFileFromProperty("android_merged_resources"); Path assetsDir = getFileFromProperty("android_merged_assets"); Path apkFile = getFileFromProperty("andr...
@Test public void identify_withResourceApk() { Properties properties = new Properties(); properties.put("android_merged_manifest", "gradle/AndroidManifest.xml"); properties.put("android_merged_resources", "gradle/res"); properties.put("android_merged_assets", "gradle/assets"); properties.put("andr...
public Application load(HeliumPackage packageInfo, ApplicationContext context) throws Exception { if (packageInfo.getType() != HeliumType.APPLICATION) { throw new ApplicationException( "Can't instantiate " + packageInfo.getType() + " package using ApplicationLoader"); } // check if al...
@Test void loadUnloadApplication() throws Exception { // given LocalResourcePool resourcePool = new LocalResourcePool("pool1"); DependencyResolver dep = new DependencyResolver(tmpDir.getAbsolutePath(), ZeppelinConfiguration.load()); ApplicationLoader appLoader = new ApplicationLoader(resourceP...
public SchemaMapping fromParquet(MessageType parquetSchema) { List<Type> fields = parquetSchema.getFields(); List<TypeMapping> mappings = fromParquet(fields); List<Field> arrowFields = fields(mappings); return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings); }
@Test public void testParquetFixedBinaryToArrow() { MessageType parquet = Types.buildMessage() .addField(Types.optional(FIXED_LEN_BYTE_ARRAY).length(12).named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Binary()))); Assert.assertEquals(expected, conve...
public void syncTableMeta(String dbName, String tableName, boolean forceDeleteData) throws DdlException { Database db = GlobalStateMgr.getCurrentState().getDb(dbName); if (db == null) { throw new DdlException(String.format("db %s does not exist.", dbName)); } Table table = d...
@Test @Ignore public void testSyncTableMeta() throws Exception { long dbId = 100; long tableId = 1000; List<Long> shards = new ArrayList<>(); new MockUp<GlobalStateMgr>() { @Mock public Database getDb(String dbName) { return new Database(d...
public boolean isIncluded(Path absolutePath, Path relativePath, InputFile.Type type) { PathPattern[] inclusionPatterns = InputFile.Type.MAIN == type ? mainInclusionsPattern : testInclusionsPattern; if (inclusionPatterns.length == 0) { return true; } for (PathPattern pattern : inclusionPatterns) ...
@Test public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestInclusions() { settings.setProperty(PROJECT_TESTS_INCLUSIONS_PROPERTY, "**/*Dao.java"); settings.setProperty(PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*Dto.java"); AbstractExclusionFilters filter = new AbstractExclusionFilters...
public static void run(Path source, Path target) throws IOException { final List<Path> existingPaths = collectExistingPaths(target); existingPaths.remove(target); // exclude the target, we don't want to remove it in following step deletePaths(existingPaths); copyFiles(source, target); ...
@Test void run() throws IOException { FullDirSync.run(source, target); List<Path> afterSyncState = new ArrayList<>(); Files.walkFileTree(target, new SimpleFileVisitor<>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throw...
public CompletableFuture<InetSocketAddress> resolveAndCheckTargetAddress(String hostAndPort) { int pos = hostAndPort.lastIndexOf(':'); String host = hostAndPort.substring(0, pos); int port = Integer.parseInt(hostAndPort.substring(pos + 1)); if (!isPortAllowed(port)) { return ...
@Test public void shouldAllowIPv6Address() throws Exception { BrokerProxyValidator brokerProxyValidator = new BrokerProxyValidator( createMockedAddressResolver("fd4d:801b:73fa:abcd:0000:0000:0000:0001"), "*" , "fd4d:801b:73fa:abcd::/64" , "6650...
@Override public int countChars(Note note) { String titleAndContent = note.getTitle() + "\n" + note.getContent(); return (int) Stream.of(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split("")) .map(String::trim) .filter(s -> !s.isEmpty()) .count(); }
@Test public void countChars() { Note note = getNote(1L, "one two", "three four five\nAnother line"); assertEquals(30, new DefaultWordCounter().countChars(note)); }
public void put(String key, String val) throws IllegalArgumentException { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } Map<String, String> oldMap = copyOnThreadLocal.get(); Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); if (wasLastOpReadOrNull(las...
@Test public void nearSimultaneousPutsShouldNotCauseConcurrentModificationException() throws InterruptedException { // For the weirdest reason, modifications to mdcAdapter must be done // before the definition anonymous ChildThread class below. Otherwise, the // map in the child thread, the one contained ...
@Override protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { NSDictionary serialized = NSDictionary.dictionaryWithContentsOfFile(file.getAbsolute()); if(null == serialized) { throw new LocalAccessDeniedException(String.format("Invalid b...
@Test public void testParse() throws AccessDeniedException { FlowBookmarkCollection c = new FlowBookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), new TestProtocol(Scheme.https)...
@Override public long getOffsetInQueueByTime(String topic, int queueId, long timestamp) { return this.getOffsetInQueueByTime(topic, queueId, timestamp, BoundaryType.LOWER); }
@Test public void testGetOffsetInQueueByTime() { final int totalCount = 10; int queueId = 0; String topic = "FooBar"; AppendMessageResult[] appendMessageResults = putMessages(totalCount, topic, queueId, true); //Thread.sleep(10); StoreTestUtil.waitCommitLogReput((Defa...
@Override public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(HttpConstants.AUTHORIZATION_HEADER); if (authorizati...
@Test(timeout = 60000) public void testRequestWithWrongCredentials() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final Base64 base64 = new Base64(0); String credentials = base64.encodeT...
@Override public void run() { try { // Step1. Get Current Time. Date now = new Date(); LOG.info("SubClusterCleaner at {}.", now); Map<SubClusterId, SubClusterInfo> subClusters = federationFacade.getSubClusters(true); for (Map.Entry<SubClusterId, SubClusterInfo> subCluster : subClus...
@Test public void testSubClustersWithOutHeartBeat() throws InterruptedException, TimeoutException, YarnException { // We set up such a unit test, We set the status of all subClusters to RUNNING, // and Manually set subCluster heartbeat expiration. // At this time, the size of the Active SubCluster ...
List<PluginConfiguration> getAuthConfigMetadata(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_GET_AUTH_CONFIG_METADATA, new DefaultPluginInteractionCallback<>() { @Override public List<PluginConfiguration> onSuccess(String responseBody, Map<String, String>...
@Test void shouldTalkToPlugin_To_GetPluginConfigurationMetadata() { String responseBody = "[{\"key\":\"username\",\"metadata\":{\"required\":true,\"secure\":false}},{\"key\":\"password\",\"metadata\":{\"required\":true,\"secure\":true}}]"; when(pluginManager.submitTo(eq(PLUGIN_ID), eq(AUTHORIZATION_...
@Deprecated public static SofaRequest buildSofaRequest(Class<?> clazz, String method, Class[] argTypes, Object[] args) { SofaRequest request = new SofaRequest(); request.setInterfaceName(clazz.getName()); request.setMethodName(method); request.setMethodArgs(args == null ? CodecUtils....
@Test public void buildSofaRequest1() throws Exception { Method method = Number.class.getMethod("intValue"); SofaRequest request = MessageBuilder.buildSofaRequest(Number.class, method, new Class[0], StringUtils.EMPTY_STRING_ARRAY); Assert.assertEquals(request.getInterfaceName(), ...
public static DateTime convertToDateTime(@Nonnull Object value) { if (value instanceof DateTime) { return (DateTime) value; } if (value instanceof Date) { return new DateTime(value, DateTimeZone.UTC); } else if (value instanceof ZonedDateTime) { final...
@Test void convertFromInstant() { final long currentTimeMillis = System.currentTimeMillis(); final Instant input = Instant.ofEpochMilli(currentTimeMillis); final DateTime output = DateTimeConverter.convertToDateTime(input); final DateTime expectedOutput = new DateTime(currentTimeMi...
public static <T extends PipelineOptions> T as(Class<T> klass) { return new Builder().as(klass); }
@Test public void testMissingMultipleSettersThrows() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( "missing property methods on [org.apache.beam.sdk.options." + "PipelineOptionsFactoryTest$MissingMultipleSetters]"); expectedException.expec...
@Override public void initializeState(StateInitializationContext context) throws Exception { if (isPartitionCommitTriggerEnabled()) { partitionCommitPredicate = PartitionCommitPredicate.create(conf, getUserCodeClassloader(), partitionKeys); } currentNewPartit...
@Test void testFailover() throws Exception { OperatorSubtaskState state; try (OneInputStreamOperatorTestHarness<RowData, PartitionCommitInfo> harness = create()) { harness.setup(); harness.initializeEmptyState(); harness.open(); harness.processElement(...
public static <T> Map<T, T> reverse(Map<T, T> map) { return edit(map, t -> new Entry<T, T>() { @Override public T getKey() { return t.getValue(); } @Override public T getValue() { return t.getKey(); } @Override public T setValue(T value) { throw new UnsupportedOperationException...
@Test public void reverseTest() { final Map<String, String> map = MapUtil.newHashMap(); map.put("a", "1"); map.put("b", "2"); map.put("c", "3"); map.put("d", "4"); final Map<String, String> map2 = MapUtil.reverse(map); assertEquals("a", map2.get("1")); assertEquals("b", map2.get("2")); assertEquals...
public void startCluster() throws ClusterEntrypointException { LOG.info("Starting {}.", getClass().getSimpleName()); try { FlinkSecurityManager.setFromConfiguration(configuration); PluginManager pluginManager = PluginUtils.createPluginManagerFromRootFolder(co...
@Test public void testWorkingDirectoryIsNotDeletedWhenStoppingClusterEntrypoint() throws Exception { final File workingDirBase = TEMPORARY_FOLDER.newFolder(); final ResourceID resourceId = new ResourceID("foobar"); configureWorkingDirectory(flinkConfig, workingDirBase, resourceId); ...
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { if (!joinKey.isForeignKey()) { ensureMatchingPartitionCounts(buildContext.getServiceContext().getTopicClient()); } final JoinerFactory joinerFactory = new JoinerFactory( buildContext, this, ...
@Test public void shouldPerformTableToTableLeftJoin() { // Given: setupTable(left, leftSchemaKTable); setupTable(right, rightSchemaKTable); final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, true, left, right, empty(),"KAFKA"); // When: joinNode.buildStream(planBuild...
@Override public Object[] toArray() { return new Object[0]; }
@Test public void testToArray1() throws Exception { Object[] array = es.toArray(new Integer[1]); assertEquals(1, array.length); assertEquals(null, array[0]); array = es.toArray(new Integer[0]); assertEquals(0, array.length); }
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_parse_filter_tag() { properties.put(Constants.FILTER_TAGS_PROPERTY_NAME, "@No and not @Never"); RuntimeOptions options = cucumberPropertiesParser.parse(properties).build(); List<String> tagExpressions = options.getTagExpressions().stream() .map(Object::toSt...
public HtmlEmail createEmail(T report) throws MalformedURLException, EmailException { HtmlEmail email = new HtmlEmail(); setEmailSettings(email); addReportContent(email, report); return email; }
@Test public void support_ssl() throws Exception { BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere")); when(emailSettings.getSecureConnection()).thenReturn("SSL"); when(emailSettings.getSmtpHost()).thenReturn("smtphost"); when(emailSettings.getSmtpPort()).thenReturn(466); when(email...
public static String safeSubstring(String target, int start, int end) { if (target == null) { return null; } int slen = target.length(); if (start < 0 || end <= 0 || end <= start || slen < start || slen < end) { return null; } return target.subst...
@Test public void testSafeSubstring() { assertNull(Tools.safeSubstring(null, 10, 20)); assertNull(Tools.safeSubstring("", 10, 20)); assertNull(Tools.safeSubstring("foo", -1, 2)); assertNull(Tools.safeSubstring("foo", 1, 0)); assertNull(Tools.safeSubstring("foo", 5, 2)); ...
static List<CircuitBreaker> getDefaultCircuitBreakers(String resourceName) { if (rules == null || rules.isEmpty()) { return null; } List<CircuitBreaker> circuitBreakers = DefaultCircuitBreakerRuleManager.circuitBreakers.get(resourceName); if (circuitBreakers == null && !rules...
@Test public void testGetDefaultCircuitBreakers() { String resourceName = RESOURCE_NAME + "I"; assertFalse(DegradeRuleManager.hasConfig(resourceName)); List<CircuitBreaker> defaultCircuitBreakers1 = DefaultCircuitBreakerRuleManager.getDefaultCircuitBreakers( resourceName); ...
public DubboShutdownHook(ApplicationModel applicationModel) { super("DubboShutdownHook"); this.applicationModel = applicationModel; Assert.notNull(this.applicationModel, "ApplicationModel is null"); ignoreListenShutdownHook = Boolean.parseBoolean( ConfigurationUtils.getPr...
@Test public void testDubboShutdownHook() { Assertions.assertNotNull(dubboShutdownHook); Assertions.assertLinesMatch(asList("DubboShutdownHook"), asList(dubboShutdownHook.getName())); Assertions.assertFalse(dubboShutdownHook.getRegistered()); }
public Optional<Node> localCorpusDispatchTarget() { if (localCorpusDispatchTarget == null) return Optional.empty(); // Only use direct dispatch if the local group has sufficient coverage Group localSearchGroup = groups.get(localCorpusDispatchTarget.group()); if ( ! localSearchGroup.hasS...
@Test void requireThatVipStatusDownWhenLocalIsDown() { try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "b")) { test.waitOneFullPingRound(); assertTrue(test.vipStatus.isInRotation()); assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent...
public static void setMetadata( Context context, NotificationCompat.Builder notification, int type) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { switch (type) { case TYPE_NORMAL: createNormalChannel(context); break; case TYPE_FTP: createFtpChannel...
@Test @Config(sdk = {KITKAT}) // max sdk is N public void testFtpNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_FTP_ID) .setContentTitle("FTP server test") .setContentText("FTP listening at 127.0.0.1:22") .setSmal...
public void consume(Inbox inbox) { ensureNotDone(); if (limit <= 0) { done.compareAndSet(null, new ResultLimitReachedException()); ensureNotDone(); } while (offset > 0 && inbox.poll() != null) { offset--; } for (JetSqlRow row; (row = ...
@Test public void when_nextItemWhileWaiting_then_hasNextReturns() throws Exception { initProducer(false); Future<?> future = spawn(() -> { assertThat(iterator.hasNext(1, DAYS)).isEqualTo(YES); assertThat((int) iterator.next().get(0)).isEqualTo(42); }); sleepMi...
@Override public byte[] serialize() { byte[] optionsData = null; if (this.options.hasOptions()) { optionsData = this.options.serialize(); } int optionsLength = 0; if (optionsData != null) { optionsLength = optionsData.length; } final ...
@Test public void testSerialize() { NeighborSolicitation ns = new NeighborSolicitation(); ns.setTargetAddress(TARGET_ADDRESS); ns.addOption(NeighborDiscoveryOptions.TYPE_TARGET_LL_ADDRESS, MAC_ADDRESS.toBytes()); assertArrayEquals(ns.serialize(), bytePacket); ...
public static long readVLong(ByteData arr, long position) { byte b = arr.get(position++); if(b == (byte) 0x80) throw new RuntimeException("Attempting to read null value as long"); long value = b & 0x7F; while ((b & 0x80) != 0) { b = arr.get(position++); ...
@Test(expected = EOFException.class) public void testReadVLongTruncatedInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_TRUNCATED); VarInt.readVLong(is); }
@Override public void removeAll() { map.removeAll(Predicates.alwaysTrue()); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveAllWithKeys() { adapter.removeAll(singleton(42)); }
@NonNull public ConnectionFileName getConnectionRootFileName( @NonNull VFSConnectionDetails details ) { String connectionName = details.getName(); if ( StringUtils.isEmpty( connectionName ) ) { throw new IllegalArgumentException( "Unnamed connection" ); } return new ConnectionFileName( connect...
@Test( expected = IllegalArgumentException.class ) public void testGetConnectionRootFileNameThrowsIllegalArgumentGivenConnectionHasNullName() { when( vfsConnectionDetails.getName() ).thenReturn( null ); vfsConnectionManagerHelper.getConnectionRootFileName( vfsConnectionDetails ); }
public static boolean isWide(@Nullable Type type) { if (type == null) return false; return Type.DOUBLE_TYPE.equals(type) || Type.LONG_TYPE.equals(type); }
@Test void testIsWide() { assertTrue(Types.isWide(Type.getType("D"))); assertTrue(Types.isWide(Type.getType("J"))); // assertFalse(Types.isWide(Type.getType("V"))); assertFalse(Types.isWide(Type.getType("Z"))); assertFalse(Types.isWide(Type.getType("B"))); assertFalse(Types.isWide(Type.getType("C"))); ...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void atLiteralDuration() { String inputExpression = "@\"P2Y2M\""; BaseNode bool = parse(inputExpression); assertThat(bool).isInstanceOf(AtLiteralNode.class); assertThat(bool.getResultType()).isEqualTo(BuiltInType.DURATION); assertLocation(inputExpression, bool); }
public static double estimateDistanceInFeet(Point p1, Point p2, long maxTimeDeltaInMillisec) { //using sythetic Points to estimate physcial distances is numerically unstable verifyTimeDeltaIsSmall(p1, p2, maxTimeDeltaInMillisec); Instant avgTime = Time.averageTime(p1.time(), p2.time()); ...
@Test public void testEstimateDistanceInFeet_tooFarApartInTime() { //1 knot -- due east Point testPoint = (new PointBuilder()) .time(Instant.EPOCH) .latLong(0.0, 0.0) .altitude(Distance.ofFeet(0.0)) .speedInKnots(1.0) .courseInDegrees(90.0...
public static String getPackageName(Class<?> clazz) { return getPackageName(clazz.getName()); }
@Test public void testGetPackageName() { String packageName = ClassUtils.getPackageName(AbstractMap.class); assertEquals("java.util", packageName); }
public static DynamicMessage messageFromGenericRecord( Descriptor descriptor, GenericRecord record, @Nullable String changeType, long changeSequenceNum) { return messageFromGenericRecord( descriptor, record, changeType, Long.toHexString(changeSequenceNum)); }
@Test public void testMessageFromGenericRecord() throws Exception { Descriptors.Descriptor descriptor = TableRowToStorageApiProto.getDescriptorFromTableSchema( AvroGenericRecordToStorageApiProto.protoTableSchemaFromAvroSchema(NESTED_SCHEMA), true, false); DynamicMes...
public CsvData read() throws IORuntimeException { return read(this.reader, false); }
@Test public void readDisableCommentTest() { final CsvReader reader = CsvUtil.getReader(CsvReadConfig.defaultConfig().disableComment()); final CsvData read = reader.read(ResourceUtil.getUtf8Reader("test.csv")); final CsvRow row = read.getRow(0); assertEquals("# 这是一行注释,读取时应忽略", row.get(0)); }
Map<Path, Set<Integer>> changedLines() { return tracker.changedLines(); }
@Test public void do_not_count_deleted_line() throws IOException { String example = "Index: sample1\n" + "===================================================================\n" + "--- a/sample1\n" + "+++ b/sample1\n" + "@@ -1 +0,0 @@\n" + "-deleted line\n"; printDiff(example); ...
public synchronized TableId createTable(String tableName, Schema schema) throws BigQueryResourceManagerException { return createTable(tableName, schema, System.currentTimeMillis() + 3600000); // 1h }
@Test public void testCreateTableShouldThrowErrorWhenTableNameIsNotValid() { assertThrows(IllegalArgumentException.class, () -> testManager.createTable("", schema)); }
@Override public double getValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { throw new IllegalArgumentException(quantile + " is not in [0..1]"); } if (values.length == 0) { return 0.0; } final double pos = qua...
@Test(expected = IllegalArgumentException.class) public void disallowsNotANumberQuantile() { snapshot.getValue(Double.NaN); }
public static byte[] copyOf(byte[] original) { return Arrays.copyOf(original, original.length); }
@Test public void copyOf() { byte[] input = new byte[] {1, 2, 3}; assertThat(Tools.copyOf(input), is(equalTo(input))); assertNotSame(input, Tools.copyOf(input)); }
@RequestMapping("/error") public ModelAndView handleError(HttpServletRequest request) { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); ModelAndView modelAndView = new ModelAndView(); if (status != null) { int statusCode = Integer.parseInt(status.toStr...
@Test void handleError_ReturnsModelAndViewWithStatusCode() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) .thenReturn(HttpStatus.INTERNAL_SERVER_ERROR.value()); ModelAndView modelAndView = new Fr...
@Override public UltraLogLog getInitialAggregatedValue(Object rawValue) { UltraLogLog initialValue; if (rawValue instanceof byte[]) { byte[] bytes = (byte[]) rawValue; initialValue = deserializeAggregatedValue(bytes); } else { initialValue = UltraLogLog.create(_p); addObjectToSketc...
@Test public void getInitialValueShouldSupportDifferentTypes() { DistinctCountULLValueAggregator agg = new DistinctCountULLValueAggregator(Collections.emptyList()); assertEquals(roundedEstimate(agg.getInitialAggregatedValue(12345)), 1.0); assertEquals(roundedEstimate(agg.getInitialAggregatedValue(12345L))...
@Override public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(HttpConstants.AUTHORIZATION_HEADER); if (authorizati...
@Test(timeout = 60000) public void testRequestWithIncompleteAuthorization() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) ...
public static KeyStore newStoreCopyContent(KeyStore originalKeyStore, char[] currentPassword, final char[] newPassword) throws GeneralSecurityException, IOException { if (newPassword == null) { throw new Il...
@Test void testMovingManyEntiresOfTheSameType() throws Exception { final char[] oldPassword = "oldPass".toCharArray(); final char[] newPassword = "newPass".toCharArray(); KeyStore originalKeyStore = KeyStore.getInstance(PKCS12); originalKeyStore.load(null, oldPassword); Cert...
@Override public Stream<FileSlice> getLatestMergedFileSlicesBeforeOrOn(String partitionPath, String maxInstantTime) { return execute(partitionPath, maxInstantTime, preferredView::getLatestMergedFileSlicesBeforeOrOn, (path, instantTime) -> getSecondaryView().getLatestMergedFileSlicesBeforeOrOn(path, instan...
@Test public void testGetLatestMergedFileSlicesBeforeOrOn() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; String maxInstantTime = "2020-01-01"; when(primary.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime)) ...
@UdafFactory(description = "Compute average of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint>") public static TableUdaf<Integer, Struct, Double> averageInt() { return getAverageImplementation( 0, STRUCT_INT, (sum, newValue) -> sum.getInt32(SUM) + ne...
@Test public void shouldAverageInts() { final TableUdaf<Integer, Struct, Double> udaf = AverageUdaf.averageInt(); Struct agg = udaf.initialize(); final int[] values = new int[] {1, 1, 1, 1, 1}; for (final int thisValue : values) { agg = udaf.aggregate(thisValue, agg); } final double avg ...
static String calculateBillingProjectId(Optional<String> configParentProjectId, Optional<Credentials> credentials) { if (configParentProjectId.isPresent()) { return configParentProjectId.get(); } // All other credentials types (User, AppEngine, GCE, CloudShell, etc.) take it fro...
@Test public void testCredentialsOnly() throws Exception { String projectId = BigQueryConnectorModule.calculateBillingProjectId(Optional.empty(), credentials()); assertThat(projectId).isEqualTo("presto-bq-credentials-test"); }
@Override public final Object unwrap() { return delegate; }
@Test void unwrap() { assertThat(wrapper.unwrap()) .isEqualTo(request); }
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public AppInfo get() { return getAppInfo(); }
@Test public void testAMSlash() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("mapreduce/") .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, ...
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_attachNonexistentFileWithPath_then_throwsException() { // Given String path = Paths.get("/i/do/not/exist").toString(); // Then expectedException.expect(JetException.class); expectedException.expectMessage("Not an existing, readable file: " + path); ...
private DefaultFuture(Channel channel, Request request, int timeout) { this.channel = channel; this.request = request; this.id = request.getId(); this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); // put into waiting map. ...
@Test @Disabled public void timeoutNotSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println( "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after ...
public void putStats(String route, String cause) { if (route == null) { route = "UNKNOWN_ROUTE"; } route = route.replace("/", "_"); ConcurrentHashMap<String, ErrorStatsData> statsMap = routeMap.get(route); if (statsMap == null) { statsMap = new ConcurrentH...
@Test void testPutStats() { ErrorStatsManager sm = new ErrorStatsManager(); assertNotNull(sm); sm.putStats("test", "cause"); assertNotNull(sm.routeMap.get("test")); ConcurrentHashMap<String, ErrorStatsData> map = sm.routeMap.get("test"); ErrorStatsData sd = map.get("c...
@Override public long getTtl() { return expiryMetadata.getTtl(); }
@Test public void test_getTtl() { assertEquals(Long.MAX_VALUE, view.getTtl()); }
@Bean public PluginDataHandler resilience4JHandler() { return new Resilience4JHandler(); }
@Test public void testResilience4JHandler() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(Resilience4JPluginConfiguration.class)) .withBean(Resilience4JPluginConfigurationTest.class) .withPropertyValues("debug=true") .run(context ->...
@Override public LanguageDetector loadModels() { // FUTURE when the "language-detector" project supports short profiles, check if // isShortText() returns true and switch to those. languages = DEFAULT_LANGUAGES; if (languageProbabilities != null) { detector = createDete...
@Test @Timeout(5000) public void testOptimaizeRegexBug() throws Exception { //confirm TIKA-2777 doesn't affect langdetect's Optimaize LanguageDetector detector = new OptimaizeLangDetector().setShortText(false).loadModels(); StringBuilder sb = new StringBuilder(); for (int i = 0; ...
@Description("removes whitespace from the beginning and end of a string") @ScalarFunction("trim") @LiteralParameters("x") @SqlType("char(x)") public static Slice charTrim(@SqlType("char(x)") Slice slice) { return trim(slice); }
@Test public void testCharTrim() { assertFunction("TRIM(CAST('' AS CHAR(20)))", createCharType(20), padRight("", 20)); assertFunction("TRIM(CAST(' hello ' AS CHAR(9)))", createCharType(9), padRight("hello", 9)); assertFunction("TRIM(CAST(' hello' AS CHAR(7)))", createCharType(7), padR...
@Subscribe public void publishClusterEvent(Object event) { if (event instanceof DeadEvent) { LOG.debug("Skipping DeadEvent on cluster event bus"); return; } final String className = AutoValueUtils.getCanonicalName(event.getClass()); final ClusterEvent cluster...
@Test public void localEventIsPostedToServerBusImmediately() { SimpleEvent event = new SimpleEvent("test"); clusterEventPeriodical.publishClusterEvent(event); verify(serverEventBus, times(1)).post(event); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) { Object span = request.getAttribute(SpanCustomizer.class.getName()); if (span instanceof SpanCustomizer) handlerParser.preHandle(request, o, (SpanCustomizer) span); return true; }
@Test void preHandle_parses() { when(request.getAttribute("brave.SpanCustomizer")).thenReturn(span); interceptor.preHandle(request, response, controller); verify(request).getAttribute("brave.SpanCustomizer"); verify(parser).preHandle(request, controller, span); verifyNoMoreInteractions(request, r...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetcherSessionEpochUpdate() throws Exception { buildFetcher(2); MetadataResponse initialMetadataResponse = RequestTestUtils.metadataUpdateWithIds(1, singletonMap(topicName, 1), topicIds); client.updateMetadata(initialMetadataResponse); assignFromUser(Collection...
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void timeWindowedCogroupedZeroArgCountWithTopologyConfigShouldPreserveTopologyStructure() { // override the default store into in-memory final StreamsBuilder builder = new StreamsBuilder(overrideDefaultStore(StreamsConfig.IN_MEMORY)); builder.stream("input-topic") .g...
static boolean fieldMatch(Object repoObj, Object filterObj) { return filterObj == null || repoObj.equals(filterObj); }
@Test public void testFieldMatchWithNullFilterObjShouldReturnTrue() { assertTrue(Utilities.fieldMatch("repoObject", null)); }
protected Invoker<T> select( LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (CollectionUtils.isEmpty(invokers)) { return null; } String methodName = invocation == null ? StringUti...
@Test void testSelectAgainAndCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add...
@Override public void suspend(Throwable cause) { context.goToFinished(context.getArchivedExecutionGraph(JobStatus.SUSPENDED, cause)); }
@Test void testSuspendTransitionsToFinished() { FlinkException expectedException = new FlinkException("This is a test exception"); TestingStateWithoutExecutionGraph state = new TestingStateWithoutExecutionGraph(ctx, LOG); ctx.setExpectFinished( archivedExecutionGraph -> { ...
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_claimsContext() { assertExtraClaimed(propagationFactory.decorate(context)); }
@Override public void submit(VplsOperation vplsOperation) { if (isLeader) { // Only leader can execute operation addVplsOperation(vplsOperation); } }
@Test public void testSubmitUpdateHostOperation() { vplsOperationManager.hostService = new EmptyHostService(); VplsData vplsData = VplsData.of(VPLS1); vplsData.addInterfaces(ImmutableSet.of(V100H1, V100H2)); VplsOperation vplsOperation = VplsOperation.of(vplsData, ...
public Bandwidth add(Bandwidth value) { if (value instanceof LongBandwidth) { return Bandwidth.bps(this.bps + ((LongBandwidth) value).bps); } return Bandwidth.bps(this.bps + value.bps()); }
@Test public void testAdd() { final long add = billion + one; Bandwidth expected = Bandwidth.kbps(add); assertThat(big.add(small), is(expected)); final double notLongAdd = 1001.0; Bandwidth notLongExpected = Bandwidth.kbps(notLongAdd); assertThat(notLongSmall.add(n...
public static List<String> getDefaultProtocols() throws NoSuchAlgorithmException, KeyManagementException { // TODO Might want to cache the result. It's unlikely to change at runtime. final SSLContext context = getUninitializedSSLContext(); context.init( null, null, null ); return Arr...
@Test public void testHasDefaultProtocols() throws Exception { // Setup fixture. // (not needed) // Execute system under test. final Collection<String> result = EncryptionArtifactFactory.getDefaultProtocols(); // Verify results. assertFalse( result.isEmpty() ); ...
@VisibleForTesting static void validateWorkerSettings(DataflowPipelineWorkerPoolOptions workerOptions) { DataflowPipelineOptions dataflowOptions = workerOptions.as(DataflowPipelineOptions.class); validateSdkContainerImageOptions(workerOptions); GcpOptions gcpOptions = workerOptions.as(GcpOptions.class);...
@Test public void testExperimentRegionAndWorkerZoneMutuallyExclusive() { DataflowPipelineWorkerPoolOptions options = PipelineOptionsFactory.as(DataflowPipelineWorkerPoolOptions.class); DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); ExperimentalOptions.addExper...
public static CompletionStage<List<MultipartFile>> read(HttpServerRequest r) { var contentType = r.headers().getFirst("content-type"); if (contentType == null) { throw HttpServerResponseException.of(400, "content-type header is required"); } var m = boundaryPattern.matcher(co...
@Test void insomniaMultipart() { var body = """ --X-INSOMNIA-BOUNDARY\r Content-Disposition: form-data; name="field1"\r Content-Type: text/plain\r \r value1\r --X-INSOMNIA-BOUNDARY\r Content-Disposition: form-data; name="fie...
public static void checkKeyParam(String dataId, String group) throws NacosException { if (StringUtils.isBlank(dataId) || !ParamUtils.isValid(dataId)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, DATAID_INVALID_MSG); } if (StringUtils.isBlank(group) || !ParamUtils.i...
@Test void testCheckKeyParam3() throws NacosException { String dataId = "b"; String group = "c"; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); try { group = "c"; ParamUtils.checkKeyParam(new ArrayList<String>(), group); ...
@Override public <T> List<SearchResult<T>> search(SearchRequest request, Class<T> typeFilter) { SearchSession<T> session = new SearchSession<>(request, Collections.singleton(typeFilter)); if (request.inParallel()) { ForkJoinPool commonPool = ForkJoinPool.commonPool(); getPro...
@Test public void testNodeLabel() { GraphGenerator generator = GraphGenerator.build().generateTinyGraph(); generator.getGraph().getNode(GraphGenerator.FIRST_NODE).setLabel("foo"); SearchRequest request = buildRequest("foo", generator); Collection<SearchResult<Node>> results = contr...
@Override public SchemaResult getValueSchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, false); }
@Test public void shouldThrowFromGetValueSchemaOnOtherRestExceptions() throws Exception { // Given: when(srClient.getLatestSchemaMetadata(any())) .thenThrow(new RestClientException("failure", 1, 1)); // When: final Exception e = assertThrows( KsqlException.class, () -> supplie...
public static String getSanitizedPackageName(String modelName) { return modelName.replaceAll("[^A-Za-z0-9.]", "").toLowerCase(); }
@Test void getSanitizedPackageName() { packageNameMap.forEach((originalName, expectedName) -> assertThat(KiePMMLModelUtils.getSanitizedPackageName(originalName)).isEqualTo(expectedName)); }
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void kTableNamedMaterializedFilterShouldPreserveTopologyStructure() { final StreamsBuilder builder = new StreamsBuilder(); final KTable<Object, Object> table = builder.table("input-topic"); table.filter((key, value) -> false, Materialized.as("store-name")); final Topolog...
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long size = request.getContentLengthLong(); if (size > maxSize || isChunked(request)) { // Size it's either unknown or too large ...
@Test public void testDoFilterInvokeChainDoFilter() throws ServletException, IOException { MaxRequestSizeFilter maxRequestSizeFilter = new MaxRequestSizeFilter(MAX_SIZE); FilterChain spyFilterChain = Mockito.spy(FilterChain.class); ServletRequest spyHttpServletRequest = Mockito.spy(ServletRe...
private int usage(String[] args) { err( "Usage : [load | create] <classname>"); err( " [locate | print] <resourcename>]"); err("The return codes are:"); explainResult(SUCCESS, "The operation was successful"); explainResult(E_GENERIC, "Something ...
@Test public void testUsage() throws Throwable { run(FindClass.E_USAGE, "org.apache.hadoop.util.TestFindClass"); }
@VisibleForTesting void setKeyACLs(Configuration conf) { Map<String, HashMap<KeyOpType, AccessControlList>> tempKeyAcls = new HashMap<String, HashMap<KeyOpType,AccessControlList>>(); Map<String, String> allKeyACLS = conf.getValByRegex(KMSConfiguration.KEY_ACL_PREFIX_REGEX); for (Map.Entry<...
@Test public void testKeyAclReload() { Configuration conf = new Configuration(false); conf.set(DEFAULT_KEY_ACL_PREFIX + "READ", "read1"); conf.set(DEFAULT_KEY_ACL_PREFIX + "MANAGEMENT", ""); conf.set(DEFAULT_KEY_ACL_PREFIX + "GENERATE_EEK", "*"); conf.set(DEFAULT_KEY_ACL_PREFIX + "DECRYPT_EEK", "d...
public EndpointResponse getServerMetadata() { return EndpointResponse.ok(serverMetadata); }
@Test public void shouldReturnServerMetadata() { // When: final EndpointResponse response = serverMetadataResource.getServerMetadata(); // Then: assertThat(response.getStatus(), equalTo(200)); assertThat(response.getEntity(), instanceOf(ServerMetadata.class)); final ServerMetadata serverMetad...
public static byte[] serialize(final Object obj) throws IOException { return SERIALIZER_REF.get().serialize(obj); }
@Test public void testClassFullyQualifiedNameSerialization() throws IOException { DeleteRecord deleteRecord = DeleteRecord.create(new HoodieKey("key", "partition")); List<Pair<DeleteRecord, Long>> deleteRecordList = new ArrayList<>(); deleteRecordList.add(Pair.of(deleteRecord, -1L)); HoodieDeleteBlock...
public static void checkMock(Class<?> interfaceClass, AbstractInterfaceConfig config) { String mock = config.getMock(); if (ConfigUtils.isEmpty(mock)) { return; } String normalizedMock = MockInvoker.normalizeMock(mock); if (normalizedMock.startsWith(RETURN_PREFIX)) {...
@Test void checkMock3() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock(GreetingMock2.class.getName()); ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig); ...