focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset( RequestContext context, OffsetCommitRequestData request ) throws ApiException { Group group = validateOffsetCommit(context, request); // In the old consumer group protocol, the offset commits maintai...
@Test public void testConsumerGroupOffsetCommitWithUnknownMemberId() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); // Create an empty group. context.groupMetadataManager.getOrMaybeCreatePersistedConsumerGroup( "foo", ...
@Override public Optional<AuthenticatedDevice> authenticate(BasicCredentials basicCredentials) { boolean succeeded = false; String failureReason = null; try { final UUID accountUuid; final byte deviceId; { final Pair<String, Byte> identifierAndDeviceId = getIdentifierAndDeviceId...
@Test void testAuthenticateAccountNotFound() { assertThat(accountAuthenticator.authenticate(new BasicCredentials(UUID.randomUUID().toString(), "password"))) .isEmpty(); }
public static <T> Read<T> read(Class<T> classType) { return new AutoValue_CosmosIO_Read.Builder<T>().setClassType(classType).build(); }
@Test public void testEstimatedSizeBytes() throws Exception { Read<Family> read = CosmosIO.read(Family.class) .withContainer(CONTAINER) .withDatabase(DATABASE) .withCoder(SerializableCoder.of(Family.class)); BoundedCosmosBDSource<Family> initialSource = new Bounded...
public static BigInteger decodeQuantity(String value) { if (isLongValue(value)) { return BigInteger.valueOf(Long.parseLong(value)); } if (!isValidHexQuantity(value)) { throw new MessageDecodingException("Value must be in format 0x[0-9a-fA-F]+"); } try { ...
@Test public void testQuantityDecodeMissingPrefix() { assertThrows(MessageDecodingException.class, () -> Numeric.decodeQuantity("ff")); }
public boolean accept(DefaultIssue issue, Component component) { if (component.getType() != FILE || (exclusionPatterns.isEmpty() && inclusionPatterns.isEmpty())) { return true; } if (isExclude(issue, component)) { return false; } return isInclude(issue, component); }
@Test public void ignore_some_rule_and_component() { IssueFilter underTest = newIssueFilter(newSettings(asList("xoo:x1", "**/xoo/File1*"), Collections.emptyList())); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isTrue(); assertThat(u...
public void setIdentityContext(IdentityContext identityContext) { this.identityContext = identityContext; }
@Test void testSetIdentityContext() { IdentityContext identityContext = new IdentityContext(); assertNull(authContext.getIdentityContext()); authContext.setIdentityContext(identityContext); assertSame(identityContext, authContext.getIdentityContext()); }
@Override public boolean hasIndexFor(String column, IndexType<?, ?, ?> type) { File indexFile = getFileFor(column, type); return indexFile.exists(); }
@Test public void nativeTextIndexIsRecognized() throws IOException { // See https://github.com/apache/pinot/issues/11529 try (FilePerIndexDirectory fpi = new FilePerIndexDirectory(TEMP_DIR, _segmentMetadata, ReadMode.mmap); NativeTextIndexCreator fooCreator = new NativeTextIndexCreator("foo", TE...
@Override public KeyValueIterator<Windowed<K>, V> fetch(final K key) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType); for (final ReadOnlySessionStore<K, V> store : stores) { tr...
@Test public void shouldFetchResultsFromUnderlyingSessionStore() { underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(0, 0)), 1L); underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(10, 10)), 2L); final List<KeyValue<Windowed<String>, Long>> results = toList(sess...
@Override public BlockBuilder writeBytes(Slice source, int sourceIndex, int length) { checkValidSliceRange(sourceIndex, length); if (!initialized) { initializeCapacity(); } sliceOutput.writeBytes(source, sourceIndex, length); currentEntrySize += length; ...
@Test public void testWriteBytes() { int entries = 100; String inputChars = "abcdefghijklmnopqrstuvwwxyz01234566789!@#$%^"; VariableWidthBlockBuilder blockBuilder = new VariableWidthBlockBuilder(null, entries, entries); List<String> values = new ArrayList<>(); Random rand...
static MetricRegistry createMetricRegistry() { MetricRegistry registry = new MetricRegistry(); final Slf4jReporter reporter = Slf4jReporter.forRegistry(registry) .outputTo(LOG) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) ...
@Test public void testCreateMetricRegistry() { MetricRegistry registry = MetricsComponent.createMetricRegistry(); assertThat(registry, is(notNullValue())); }
@Override public int drainTo(Collection<? super E> c, int maxElements) { // initially take all permits to stop consumers from modifying queues // while draining. will restore any excess when done draining. final int permits = semaphore.drainPermits(); final int numElements = Math.min(maxElements, per...
@SuppressWarnings("deprecation") @Test public void testDrainTo() { Configuration conf = new Configuration(); conf.setInt("ns." + FairCallQueue.IPC_CALLQUEUE_PRIORITY_LEVELS_KEY, 2); FairCallQueue<Schedulable> fcq2 = new FairCallQueue<Schedulable>(2, 10, "ns", conf); // Start with 3 in fcq, to be dr...
public static int read( final UnsafeBuffer termBuffer, final int termOffset, final FragmentHandler handler, final int fragmentsLimit, final Header header, final ErrorHandler errorHandler, final long currentPosition, final Position subscriberPosition) {...
@Test void shouldReadLastMessage() { final int msgLength = 1; final int frameLength = HEADER_LENGTH + msgLength; final int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT); final int frameOffset = TERM_BUFFER_CAPACITY - alignedFrameLength; final long startingPosit...
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { metadata.set(Metadata.CONTENT_TYPE, TMX_CONTENT_TYPE.toString()); final XHTMLContentHandler xhtml = new XHTMLCont...
@Test public void testTMX() throws Exception { try (InputStream input = getResourceAsStream("/test-documents/testTMX.tmx")) { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); new TMXParser().parse(input, handler, metadata, new ParseCo...
@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 disallowsQuantileOverOne() { snapshot.getValue(1.5); }
public static void mkdir( final HybridFile parentFile, @NonNull final HybridFile file, final Context context, final boolean rootMode, @NonNull final ErrorCallBack errorCallBack) { new AsyncTask<Void, Void, Void>() { private DataUtils dataUtils = DataUtils.getInstance(); ...
@Test public void testMkdirNewFolderSameNameAsCurrentFolder() throws InterruptedException { File newFolder = new File(storageRoot, "test"); HybridFile newFolderHF = new HybridFile(OpenMode.FILE, newFolder.getAbsolutePath()); CountDownLatch waiter1 = new CountDownLatch(1); Operations.mkdir( ne...
public boolean setLocations(DefaultIssue issue, @Nullable Object locations) { if (!locationsEqualsIgnoreHashes(locations, issue.getLocations())) { issue.setLocations(locations); issue.setChanged(true); issue.setLocationsChanged(true); return true; } return false; }
@Test void change_locations_if_different_flow_count() { DbIssues.Locations locations = DbIssues.Locations.newBuilder() .addFlow(DbIssues.Flow.newBuilder() .addLocation(DbIssues.Location.newBuilder()) .build()) .build(); issue.setLocations(locations); DbIssues.Locations.Builder ...
public CountDownLatch getCountDownLatch() { return countDownLatch; }
@Test void testPhase() throws InterruptedException { // CREATE client.pods().inNamespace("ns1") .create(new PodBuilder().withNewMetadata().withName("pod1").endMetadata().withNewStatus() .endStatus().build()); await().until(isPodAvailable("pod1")); // READ PodList podList = clie...
@Override @Cacheable(cacheNames = RedisKeyConstants.OAUTH_CLIENT, key = "#clientId", unless = "#result == null") public OAuth2ClientDO getOAuth2ClientFromCache(String clientId) { return oauth2ClientMapper.selectByClientId(clientId); }
@Test public void testGetOAuth2ClientFromCache() { // mock 数据 OAuth2ClientDO clientDO = randomPojo(OAuth2ClientDO.class); oauth2ClientMapper.insert(clientDO); // 准备参数 String clientId = clientDO.getClientId(); // 调用,并断言 OAuth2ClientDO dbClientDO = oauth2Client...
@Override public void write(final MySQLPacketPayload payload, final Object value) { payload.getByteBuf().writeDoubleLE(Double.parseDouble(value.toString())); }
@Test void assertWrite() { new MySQLDoubleBinaryProtocolValue().write(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8), 1.0D); verify(byteBuf).writeDoubleLE(1.0D); }
abstract public long[] getBlockListAsLongs();
@Test public void testUc() { BlockListAsLongs blocks = checkReport( new ReplicaBeingWritten(b1, null, null, null)); assertArrayEquals( new long[] { 0, 1, -1, -1, -1, 1, 11, 111, ReplicaState.RBW.getValue() }, blocks.getBlockListAsLongs()); }
@Override public int partition(RowData row, int numPartitions) { // reuse the sortKey and rowDataWrapper sortKey.wrap(rowDataWrapper.wrap(row)); return SketchUtil.partition(sortKey, numPartitions, rangeBounds, comparator); }
@Test public void testRangePartitioningWithRangeBounds() { SketchRangePartitioner partitioner = new SketchRangePartitioner(TestFixtures.SCHEMA, SORT_ORDER, RANGE_BOUNDS); GenericRowData row = GenericRowData.of(StringData.fromString("data"), 0L, StringData.fromString("2023-06-20")); for (lo...
@Override public long sizeOf(T element) { LOG.warn( "Trying to estimate size using {}, this operation will always return 0", this.getClass().getSimpleName()); return 0; }
@Test public void alwaysReturns0AsEstimatedThroughput() { final NullSizeEstimator<byte[]> estimator = new NullSizeEstimator<>(); assertEquals(estimator.sizeOf(new byte[40]), 0D, DELTA); assertEquals(estimator.sizeOf(new byte[20]), 0D, DELTA); assertEquals(estimator.sizeOf(new byte[10]), 0D, DELTA); ...
@Override protected InputStream readInputStreamParam(String key) { Part part = readPart(key); return (part == null) ? null : part.getInputStream(); }
@Test public void returns_null_when_invalid_part() throws Exception { when(source.getContentType()).thenReturn("multipart/form-data"); InputStream file = mock(InputStream.class); Part part = mock(Part.class); when(part.getSize()).thenReturn(0L); when(part.getInputStream()).thenReturn(file); do...
@Operation(summary = "list", description = "List hosts") @GetMapping public ResponseEntity<List<HostVO>> list(@PathVariable Long clusterId) { return ResponseEntity.success(hostService.list(clusterId)); }
@Test void listReturnsEmptyForInvalidClusterId() { Long clusterId = 999L; when(hostService.list(clusterId)).thenReturn(List.of()); ResponseEntity<List<HostVO>> response = hostController.list(clusterId); assertTrue(response.isSuccess()); assertTrue(response.getData().isEmpty...
@Override public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream, ChannelPromise promise) { return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise); }
@Test public void headersWriteForUnknownStreamShouldCreateStream() throws Exception { writeAllFlowControlledFrames(); final int streamId = 6; ChannelPromise promise = newPromise(); encoder.writeHeaders(ctx, streamId, EmptyHttp2Headers.INSTANCE, 0, false, promise); verify(writ...
@Override protected Triple<List<HoodieClusteringGroup>, Integer, List<FileSlice>> buildSplitClusteringGroups( ConsistentBucketIdentifier identifier, List<FileSlice> fileSlices, int splitSlot) { return super.buildSplitClusteringGroups(identifier, fileSlices, splitSlot); }
@Test public void testBuildSplitClusteringGroup() throws IOException { setup(); int maxFileSize = 5120; Properties props = new Properties(); props.setProperty(KeyGeneratorOptions.RECORDKEY_FIELD_NAME.key(), "uuid"); HoodieWriteConfig config = HoodieWriteConfig.newBuilder().withPath(basePath) ...
@Nonnull @Override public ProgressState call() { progTracker.reset(); stateMachineStep(); return progTracker.toProgressState(); }
@Test public void when_item_then_offeredToSsWriter() { // When init(singletonList(entry("k", "v"))); assertEquals(MADE_PROGRESS, sst.call()); // Then assertEquals(entry(serialize("k"), serialize("v")), mockSsWriter.poll()); assertNull(mockSsWriter.poll()); }
public static ThreadFactory groupedThreads(String groupName, String pattern) { return groupedThreads(groupName, pattern, log); }
@Test public void groupedThreads() { ThreadFactory f = Tools.groupedThreads("foo/bar-me", "foo-%d"); Thread t = f.newThread(() -> TestTools.print("yo")); assertTrue("wrong pattern", t.getName().startsWith("foo-bar-me-foo-")); assertTrue("wrong group", "foo/bar-me".equals(t.getThreadG...
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) { if (statsEnabled) { stats.log(deviceStateServiceMsg); } stateService.onQueueMsg(deviceStateServiceMsg, callback); }
@Test public void givenProcessingFailure_whenForwardingDisconnectMsgToStateService_thenOnFailureCallbackIsCalled() { // GIVEN var disconnectMsg = TransportProtos.DeviceDisconnectProto.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantId...
@Override public FilteredMessage apply(Message msg) { try (var ignored = executionTime.time()) { return doApply(msg); } }
@Test void applyWithNoFilterAndTwoDestinations(MessageFactory messageFactory) { final var filter = createFilter(Map.of(), Set.of("indexer", "other")); final var message = messageFactory.createMessage("msg", "src", Tools.nowUTC()); message.addStream(defaultStream); final var filtered...
public void endsWith(@Nullable String string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that ends with", string); } else if (!actual.endsWith(string)) { failWithActual("expected to end with", string); } }
@Test public void stringEndsWithFail() { expectFailureWhenTestingThat("abc").endsWith("ab"); assertFailureValue("expected to end with", "ab"); }
@Override public List<Object> apply(ConsumerRecord<K, V> record) { List<Object> vals = func.apply(record); if (vals == null) { return null; } KafkaTuple ret = new KafkaTuple(); ret.addAll(vals); return ret.routedTo(stream); }
@Test public void testNullTranslation() { SimpleRecordTranslator<String, String> trans = new SimpleRecordTranslator<>((r) -> null, new Fields("key")); assertNull(trans.apply(null)); }
public boolean record(final Throwable observation) { final long timestampMs; DistinctObservation distinctObservation; timestampMs = clock.time(); synchronized (this) { distinctObservation = find(distinctObservations, observation); if (null == distinc...
@Test void shouldRecordFirstObservationOnly() { final long timestampOne = 7; final long timestampTwo = 8; final int offset = 0; final RuntimeException error = new RuntimeException("Test Error"); when(clock.time()).thenReturn(timestampOne).thenReturn(timestampTwo); ...
public static void retry(String action, RunnableThrowsIOException f, RetryPolicy policy) throws IOException { IOException e = null; while (policy.attempt()) { try { f.run(); return; } catch (IOException ioe) { e = ioe; LOG.debug("Failed to {} (attempt {}): {}", ...
@Test public void failure() throws IOException { AtomicInteger count = new AtomicInteger(0); try { RetryUtils.retry("failure test", () -> { count.incrementAndGet(); throw new IOException(Integer.toString(count.get())); }, new CountingRetry(10)); fail("Expected an exception to...
public void finish() throws IOException { if (finished) { return; } flush(); // Finish the stream with the terminatorValue. VarInt.encode(terminatorValue, os); if (!BUFFER_POOL.offer(buffer)) { // The pool is full, we can't store the buffer. We just drop the buffer. } finishe...
@Test public void testBehaviorWhenBufferPoolFull() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (BUFFER_POOL.remainingCapacity() > 0) { BUFFER_POOL.offer(ByteBuffer.allocate(256)); } BufferedElementCountingOutputStream os = createAndWriteValues(toBytes("abcd...
public Collection<ServerPluginInfo> loadPlugins() { Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>(); for (ServerPluginInfo bundled : getBundledPluginsMetadata()) { failIfContains(bundledPluginsByKey, bundled, plugin -> MessageException.of(format("Found two versions of the...
@Test public void test_plugin_requirements_at_startup() throws Exception { copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); copyTestPluginTo("test-require-plugin", fs.getInstalledExternalPluginsDir()); assertThat(underTest.loadPlugins()).extracting(PluginInfo::getKey).containsOn...
public synchronized NumaResourceAllocation allocateNumaNodes( Container container) throws ResourceHandlerException { NumaResourceAllocation allocation = allocate(container.getContainerId(), container.getResource()); if (allocation != null) { try { // Update state store. conte...
@Test public void testAllocateNumaNodeWhenNoNumaMemResourcesAvailable() throws Exception { NumaResourceAllocation nodeInfo = numaResourceAllocator .allocateNumaNodes(getContainer( ContainerId.fromString("container_1481156246874_0001_01_000001"), Resource.newInstance(2048000, ...
@Override public <T extends MigrationStep> MigrationStepRegistry add(long migrationNumber, String description, Class<T> stepClass) { validate(migrationNumber); requireNonNull(description, "description can't be null"); checkArgument(!description.isEmpty(), "description can't be empty"); requireNonNull(...
@Test public void add_fails_with_IAE_if_migrationNumber_is_less_than_0() { assertThatThrownBy(() -> { underTest.add(-Math.abs(new Random().nextLong() + 1), "sdsd", MigrationStep.class); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Migration number must be >= 0"); }
public void setConsumerThread(Thread consumerThread) { this.consumerThread = checkNotNull(consumerThread, "consumerThread can't be null"); }
@Test(expected = NullPointerException.class) @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") public void setOwningThread_whenNull() { MPSCQueue queue = new MPSCQueue(new BusySpinIdleStrategy()); queue.setConsumerThread(null); }
public static IntRef ofInt(int value) { return new IntRef(value); }
@Test public void testIntRef() { PrimitiveRef.IntRef ref = PrimitiveRef.ofInt(3); assertEquals(3, ref.value++); assertEquals(4, ref.value); assertEquals(5, ++ref.value); assertEquals(5, ref.value); }
public static boolean isQuorumCandidate(final ClusterMember[] clusterMembers, final ClusterMember candidate) { int possibleVotes = 0; for (final ClusterMember member : clusterMembers) { if (NULL_POSITION == member.logPosition || compareLog(candidate, member) < 0) { ...
@Test void isQuorumCandidateReturnTrueWhenQuorumIsReached() { final ClusterMember candidate = newMember(2, 10, 800); final ClusterMember[] members = new ClusterMember[] { newMember(10, 2, 100), newMember(20, 18, 6), newMember(30, 10, 800), ...
public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart, final CharSequence substring, final int start, final int length) { if (cs instanceof String && substring instanceof String) { return ((String) cs).regionMatches(ignoreCase, thisStart...
@Test void testRegionMatchesNotEqualsCaseInsensitive() { assertFalse(StringUtils.regionMatches("abc", true, 0, "xCab", 1, 3)); }
@Udf(description = "Adds a duration to a date") public Date dateAdd( @UdfParameter(description = "A unit of time, for example DAY") final TimeUnit unit, @UdfParameter(description = "An integer number of intervals to add") final Integer interval, @UdfParameter(description = "A DATE value.") final Dat...
@Test public void shouldAddToDate() { assertThat(udf.dateAdd(TimeUnit.DAYS, 9, new Date(86400000)), is(new Date(864000000))); assertThat(udf.dateAdd(TimeUnit.DAYS, -1, new Date(86400000)), is(new Date(0))); assertThat(udf.dateAdd(TimeUnit.SECONDS, 5, new Date(86400000)), is(new Date(86400000))); }
@Override public void checkApiEndpoint(GithubAppConfiguration githubAppConfiguration) { if (StringUtils.isBlank(githubAppConfiguration.getApiEndpoint())) { throw new IllegalArgumentException("Missing URL"); } URI apiEndpoint; try { apiEndpoint = URI.create(githubAppConfiguration.getApiEnd...
@Test @UseDataProvider("invalidApiEndpoints") public void checkApiEndpoint_Invalid(String url, String expectedMessage) { GithubAppConfiguration configuration = new GithubAppConfiguration(1L, "", url); assertThatThrownBy(() -> underTest.checkApiEndpoint(configuration)) .isInstanceOf(IllegalArgumentExc...
@Override public String getName() { return "HTTP Alarm Callback [Deprecated]"; }
@Test public void getNameReturnsNameOfHTTPAlarmCallback() throws Exception { assertThat(alarmCallback.getName()).isEqualTo("HTTP Alarm Callback [Deprecated]"); }
public static <T, IdT> Deduplicate.WithRepresentativeValues<T, IdT> withRepresentativeValueFn( SerializableFunction<T, IdT> representativeValueFn) { return new Deduplicate.WithRepresentativeValues<T, IdT>( DEFAULT_TIME_DOMAIN, DEFAULT_DURATION, representativeValueFn, null, null); }
@Test @Category({NeedsRunner.class, UsesTestStreamWithProcessingTime.class}) public void testRepresentativeValuesWithCoder() { Instant base = new Instant(0); TestStream<KV<Long, String>> values = TestStream.create(KvCoder.of(VarLongCoder.of(), StringUtf8Coder.of())) .advanceWatermarkTo(b...
public static boolean isAllowedStatement(final SQLStatement sqlStatement) { return ALLOWED_SQL_STATEMENTS.contains(sqlStatement.getClass()); }
@Test void assertIsStatementAllowed() { Collection<SQLStatement> sqlStatements = Arrays.asList( new MySQLAlterTableStatement(), new MySQLAlterUserStatement(), new MySQLAnalyzeTableStatement(), new MySQLCacheIndexStatement(), new MySQLCallStatement(), new MySQLChangeMasterStat...
@Override public Properties groupMetadataTopicConfigs() { Properties properties = new Properties(); properties.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); properties.put(TopicConfig.COMPRESSION_TYPE_CONFIG, BrokerCompressionType.PRODUCER.name); propert...
@Test public void testGroupMetadataTopicConfigs() { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, new Grou...
public static KStreamHolder<GenericKey> build( final KStreamHolder<?> stream, final StreamSelectKeyV1 selectKey, final RuntimeBuildContext buildContext ) { final LogicalSchema sourceSchema = stream.getSchema(); final CompiledExpression expression = buildExpressionEvaluator( selectKe...
@Test public void shouldReturnCorrectSerdeFactory() { // When: final KStreamHolder<GenericKey> result = selectKey.build(planBuilder, planInfo); // Then: result.getExecutionKeyFactory().buildKeySerde( FormatInfo.of(FormatFactory.JSON.name()), PhysicalSchema.from(SOURCE_SCHEMA, SerdeFea...
public Map<String, String> build() { Map<String, String> builder = new HashMap<>(); configureFileSystem(builder); configureNetwork(builder); configureCluster(builder); configureSecurity(builder); configureOthers(builder); LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]", ...
@Test public void set_initial_master_nodes_settings_if_cluster_is_enabled() throws Exception { Props props = minProps(CLUSTER_ENABLED); props.set(CLUSTER_ES_HOSTS.getKey(), "1.2.3.4:9000,1.2.3.5:8080"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), System2.INSTANCE).build...
public static StackTraceElement[] extract(Throwable t, String fqnOfInvokingClass, final int maxDepth, List<String> frameworkPackageList) { if (t == null) { return null; } StackTraceElement[] steArray = t.getStackT...
@Test public void testDeferredProcessing() { StackTraceElement[] cda = CallerData.extract(new Throwable(), "com.inexistent.foo", 10, null); assertNotNull(cda); assertEquals(0, cda.length); }
public static RSAPublicKey parseRSAPublicKey(String pem) throws ServletException { String fullPem = PEM_HEADER + pem + PEM_FOOTER; PublicKey key = null; try { CertificateFactory fact = CertificateFactory.getInstance("X.509"); ByteArrayInputStream is = new ByteArrayInputStream( fullPem....
@Test public void testValidPEM() throws Exception { String pem = "MIICOjCCAaOgAwIBAgIJANXi/oWxvJNzMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAlVTMQ0w" + "CwYDVQQIEwRUZXN0MQ0wCwYDVQQHEwRUZXN0MQ8wDQYDVQQKEwZIYWRvb3AxDTALBgNVBAsTBFRl" + "c3QxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xNTAxMDIyMTE5MjRaFw0xNjAxMDIyMTE5Mj...
@Override public ResourceStatistics getStatistics(String location, Job job) throws IOException { if (LOG.isDebugEnabled()) { String jobToString = String.format("job[id=%s, name=%s]", job.getJobID(), job.getJobName()); LOG.debug("LoadMetadata.getStatistics({}, {})", location, jobToString); } /*...
@Test public void testPredicatePushdown() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(ParquetLoader.ENABLE_PREDICATE_FILTER_PUSHDOWN, true); PigServer pigServer = new PigServer(ExecType.LOCAL, conf); pigServer.setValidateEachStatement(true); String out = "target/...
public boolean contains(int id) { checkIdInRange(id); return positions[id] != NOT_PRESENT; }
@Test void testContains() { create(4); push(1, 0.1f); push(2, 0.7f); push(0, 0.5f); assertFalse(contains(3)); assertTrue(contains(1)); assertEquals(1, poll()); assertFalse(contains(1)); }
public Object getSingleValue() { if (!isSingleValue()) { throw new IllegalStateException("Range does not have just a single value"); } return low.getValue(); }
@Test public void testGetSingleValue() { assertEquals(Range.equal(BIGINT, 0L).getSingleValue(), 0L); assertThrows(IllegalStateException.class, () -> Range.lessThan(BIGINT, 0L).getSingleValue()); }
public static ReadRows readRows() { return new AutoValue_JdbcIO_ReadRows.Builder() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .setStatementPreparator(ignored -> {}) .build(); }
@Test public void testReadRowsWithoutStatementPreparator() { SerializableFunction<Void, DataSource> dataSourceProvider = ignored -> DATA_SOURCE; String name = TestRow.getNameForSeed(1); PCollection<Row> rows = pipeline.apply( JdbcIO.readRows() .withDataSourceProviderFn(...
@Override public KVTable fetchBrokerRuntimeStats( final String brokerAddr) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException { return this.defaultMQAdminExtImpl.fetchBrokerRuntimeStats(brokerAddr); }
@Test public void testFetchBrokerRuntimeStats() throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException { KVTable brokerStats = defaultMQAdminExt.fetchBrokerRuntimeStats("127.0.0.1:10911"); assertThat(brokerStats.getTable().get...
private void registerPoolListeners() { memoryPools.forEach(memoryPool -> memoryPool.addListener(memoryPoolListener)); }
@Test public void testTaskThresholdRevokingSchedulerImmediate() throws Exception { SqlTask sqlTask1 = newSqlTask(new QueryId("query"), memoryPool); TestOperatorContext operatorContext11 = createTestingOperatorContexts(sqlTask1, "operator11"); TestOperatorContext operatorConte...
@Override public Long del(byte[]... keys) { if (isQueueing() || isPipelined()) { for (byte[] key: keys) { write(key, LongCodec.INSTANCE, RedisCommands.DEL, key); } return null; } CommandBatchService es = new CommandBatchService(executorSe...
@Test public void testDelPipeline() { byte[] k = "key".getBytes(); byte[] v = "val".getBytes(); connection.set(k, v); connection.openPipeline(); connection.get(k); connection.del(k); List<Object> results = connection.closePipeline(); byte[] val = (byt...
@Override public String getMethod() { return PATH; }
@Test public void testDeleteMyCommandsWithEmptyScope() { DeleteMyCommands deleteMyCommands = DeleteMyCommands.builder().build(); assertEquals("deleteMyCommands", deleteMyCommands.getMethod()); assertDoesNotThrow(deleteMyCommands::validate); }
@Deprecated public void awaitRunning(final Runnable runnable) { LOG.debug("Waiting for server to enter RUNNING state"); Uninterruptibles.awaitUninterruptibly(runningLatch); LOG.debug("Server entered RUNNING state"); try { LOG.debug("Executing awaitRunning callback"); ...
@Test public void testAwaitRunning() throws Exception { final Runnable runnable = mock(Runnable.class); final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch stopLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override publ...
public static String getGroupFromGrpcClient(AlluxioConfiguration conf) { try { User user = AuthenticatedClientUser.get(conf); if (user == null) { return ""; } return CommonUtils.getPrimaryGroupName(user.getName(), conf); } catch (IOException e) { return ""; } }
@Test public void getGroupFromGrpcClient() throws Exception { // When security is not enabled, user and group are not set mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL); assertEquals("", SecurityUtils.getGroupFromGrpcClient(mConfiguration)); mConfiguration.set(PropertyK...
@Description("converts the string to lower case") @ScalarFunction("lower") @LiteralParameters("x") @SqlType("char(x)") public static Slice charLower(@SqlType("char(x)") Slice slice) { return lower(slice); }
@Test public void testCharLower() { assertFunction("LOWER(CAST('' AS CHAR(10)))", createCharType(10), padRight("", 10)); assertFunction("LOWER(CAST('Hello World' AS CHAR(11)))", createCharType(11), padRight("hello world", 11)); assertFunction("LOWER(CAST('WHAT!!' AS CHAR(6)))", createCha...
public SmppCommand createSmppCommand(SMPPSession session, Exchange exchange) { SmppCommandType commandType = SmppCommandType.fromExchange(exchange); return commandType.createCommand(session, configuration); }
@Test public void createSmppDataSmCommand() { SMPPSession session = new SMPPSession(); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm"); SmppCommand command = binding.createSmppCommand(session, exchange);...
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokeRoundingDown() { FunctionTestUtil.assertResult(roundDownFunction.invoke(BigDecimal.valueOf(10.24)), BigDecimal.valueOf(10)); FunctionTestUtil.assertResult(roundDownFunction.invoke(BigDecimal.valueOf(10.24), BigDecimal.ONE), BigDecimal.valueOf(10...
@Override public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException { NAMING_LOGGER.info("[GRPC-SUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters); redoService.cacheSubscriberForRedo(serviceName, groupName, clusters); ...
@Test void testSubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); when(this.rpcClient.request(any())).thenReturn(res); ...
@Override public boolean syncData(DistroData data, String targetServer) { if (isNoExistTarget(targetServer)) { return true; } DistroDataRequest request = new DistroDataRequest(data, data.getType()); Member member = memberManager.find(targetServer); if (checkTarget...
@Test void testSyncDataWithCallbackForMemberUnhealthy() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); transportAgent.syncData(new DistroData(), member.getAddress(), distroCallback...
public static <T> void concat(T[] sourceFirst, T[] sourceSecond, T[] dest) { System.arraycopy(sourceFirst, 0, dest, 0, sourceFirst.length); System.arraycopy(sourceSecond, 0, dest, sourceFirst.length, sourceSecond.length); }
@Test(expected = NullPointerException.class) public void concat_whenSecondNull() { Integer[] first = new Integer[]{1, 2, 3}; Integer[] second = null; Integer[] concatenated = new Integer[4]; ArrayUtils.concat(first, second, concatenated); fail(); }
public void joinChannel(String name) { joinChannel(configuration.findChannel(name)); }
@Test public void doJoinChannelTestNoKey() { endpoint.joinChannel("#chan1"); verify(connection).doJoin("#chan1"); }
@Override public void cleanup() { for ( ServerSocket serverSocket : serverSockets ) { try { socketRepository.releaseSocket( serverSocket.getLocalPort() ); logDetailed( BaseMessages.getString( PKG, "BaseStep.Log.ReleasedServerSocketOnPort", serverSocket.getLocalPort() ) ); } ...
@Test public void testCleanup() throws IOException { BaseStep baseStep = new BaseStep( mockHelper.stepMeta, mockHelper.stepDataInterface, 0, mockHelper.transMeta, mockHelper.trans ); ServerSocket serverSocketMock = mock( ServerSocket.class ); doReturn( 0 ).when( serverSocketMock ).getLocalPort(); ...
@Override public void init(final InternalProcessorContext<Void, Void> context) { super.init(context); this.context = context; try { keySerializer = prepareKeySerializer(keySerializer, context, this.name()); } catch (ConfigException | StreamsException e) { thro...
@Test public void shouldThrowStreamsExceptionOnUndefinedValueSerde() { utilsMock.when(() -> WrappingNullableUtils.prepareValueSerializer(any(), any(), any())) .thenThrow(new ConfigException("Please set StreamsConfig#DEFAULT_VALUE_SERDE_CLASS_CONFIG")); final Throwable exception = assert...
@Override public void checkCanSelectFromColumns(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName, Set<Subfield> columnOrSubfieldNames) { Set<String> deniedColumns = new HashSet<>(); for (String column : columnOrSubf...
@Test public void testColumnLevelAccess() { ConnectorAccessControl accessControl = createRangerAccessControl("default-table-column-access.json", "user_groups.json"); // 'analyst' group have read access {group - analyst, user - joe} accessControl.checkCanSelectFromColumns(TRANSACTION_HAND...
@Override public V get() throws InterruptedException, ExecutionException { return peel().get(); }
@Test(expected = ExecutionException.class) public void get_executionExc() throws Exception { ScheduledFuture<Object> outer = createScheduledFutureMock(); ScheduledFuture<Object> inner = createScheduledFutureMock(); when(outer.get()).thenThrow(new ExecutionException(new NullPointerException()...
public static String getPrintSize(long size) { DecimalFormat df = new DecimalFormat("#.00"); if (size < KB_SIZE) { return size + "B"; } else if (size < MB_SIZE) { return df.format((double) size / KB_SIZE) + "KB"; } else if (size < GB_SIZE) { return df....
@Test public void assertGetPrintSize() { Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(220), "220B")); Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(2200), "2.15KB")); Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(2200000), "2.10MB")); Assert.isTru...
@Override public void onRestRequest(RestRequest req, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) { disruptRequest(req, requestContext, wireAttrs, nextFilter); }
@Test public void testRestTimeoutDisrupt() throws Exception { final RequestContext requestContext = new RequestContext(); requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.timeout()); final DisruptFilter filter = new DisruptFilter(_scheduler, _executor, REQUEST_TIMEOUT, _clock); fina...
@Override public double measure(MetricConfig config, long now) { purgeObsoleteSamples(config, now); return combine(this.samples, config, now); }
@Test @DisplayName("Sample should be purged if doesn't overlap the window") public void testSampleIsPurgedIfDoesntOverlap() { MetricConfig config = new MetricConfig().timeWindow(1, SECONDS).samples(2); // Monitored window: 2s. Complete a sample and wait 2.5s after. completeSample(config...
public static Optional<RestartConfig.RestartNode> getNextNode(RestartConfig config) { if (config == null) { return Optional.empty(); } List<RestartConfig.RestartNode> path = config.getRestartPath(); if (path != null && path.size() > 1) { return Optional.of(path.get(path.size() - 2)); } ...
@Test public void testGetNextNode() { RestartConfig config = RestartConfig.builder().addRestartNode("foo", 1, "bar").build(); Assert.assertEquals(Optional.empty(), RunRequest.getNextNode(config)); config = config.toBuilder().addRestartNode("bar", 1, "bar").build(); Assert.assertEquals( Optiona...
@VisibleForTesting Pair<String, File> encryptSegmentIfNeeded(File tempDecryptedFile, File tempEncryptedFile, boolean isUploadedSegmentEncrypted, String crypterUsedInUploadedSegment, String crypterClassNameInTableConfig, String segmentName, String tableNameWithType) { boolean segmentNeedsEncryption = ...
@Test public void testEncryptSegmentIfNeededCrypterInTableConfig() { // arrange boolean uploadedSegmentIsEncrypted = false; String crypterClassNameInTableConfig = "NoOpPinotCrypter"; String crypterClassNameUsedInUploadedSegment = null; // act Pair<String, File> encryptionInfo = _resource ...
public void feed(Royalty r) { r.getFed(); }
@Test void testFeed() { final var royalty = mock(Royalty.class); final var servant = new Servant("test"); servant.feed(royalty); verify(royalty).getFed(); verifyNoMoreInteractions(royalty); }
@Override public List<Map<String, String>> taskConfigs(int maxTasks) { if (knownConsumerGroups == null) { // If knownConsumerGroup is null, it means the initial loading has not finished. // An exception should be thrown to trigger the retry behavior in the framework. log....
@Test public void testReplicationEnabled() { // enable the replication MirrorCheckpointConfig config = new MirrorCheckpointConfig(makeProps("enabled", "true")); Set<String> knownConsumerGroups = new HashSet<>(); knownConsumerGroups.add(CONSUMER_GROUP); // MirrorCheckpointCon...
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { if(new DefaultPathPredicate(containerService.getContainer(file)).test(containerService.getContainer(renamed))...
@Test(expected = NotfoundException.class) public void testMoveNotFound() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path test = new Path(container, UUID.randomUUID(...
static String appendDefaultPort(String address, int defaultPort) { if (StringUtils.isNotEmpty(address) && defaultPort > 0) { int i = address.indexOf(':'); if (i < 0) { return address + ":" + defaultPort; } else if (Integer.parseInt(address.substring(i + 1)) ==...
@Test void testDefaultPort() { Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10:0", 2181)); Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10", 2181)); }
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { //Try to parse TSD file try (RereadableInputStream ris = new RereadableInputStream(stream, 2048, true)) { ...
@Test public void testTSDFileData() throws Exception { try (InputStream inputXml = getResourceAsStream("/test-documents/MANIFEST.XML.TSD"); InputStream inputTxt1 = getResourceAsStream("/test-documents/Test1.txt.tsd"); InputStream inputTxt2 = getResourceAsStream("/test-documen...
@Override public synchronized List<HeliumPackage> getAll() throws IOException { List<HeliumPackage> result = new LinkedList<>(); File file = new File(uri()); File [] files = file.listFiles(); if (files == null) { return result; } for (File f : files) { if (f.getName().startsWith(...
@Test void testGetAllPackage() throws IOException { // given File r1Path = new File(tmpDir, "r1"); HeliumLocalRegistry r1 = new HeliumLocalRegistry("r1", r1Path.getAbsolutePath()); assertEquals(0, r1.getAll().size()); // when Gson gson = new Gson(); HeliumPackage pkg1 = newHeliumPackage(H...
@Override public Iterable<Device> getDevices() { return manager.getVirtualDevices( this.networkId).stream().collect(Collectors.toSet()); }
@Test public void testGetDevices() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); VirtualDevice device1 = manager.createVirtualDevice(virtualNetwork.id(), DID1); VirtualDe...
@Override public AuthorizationPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { Capabilities capabilities = capabilities(descriptor.id()); PluggableInstanceSettings authConfigSettings = authConfigSettings(descriptor.id()); PluggableInstanceSettings roleSettings = roleSettings(descri...
@Test public void shouldBuildPluginInfoWithPluginDescriptor() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfoBuilder(extension).pluginInfoFor(descriptor); assertThat(pluginInfo.getDescrip...
public List<SearchResult> getSearchResults(String query) throws IOException { Elements results = fetchSearchResults(query); List<SearchResult> resultList = new ArrayList<>(); for (Element result : results) { Element title = result.getElementsByClass("links_main").first().getElements...
@Test void testGetSearchResultsLimitTo5() throws IOException { searchWebAction = new SearchWebAction() { @Override Elements fetchSearchResults(String query) { Elements mockResults = new Elements(); for (int i = 1; i <= 6; i++) { moc...
@Override public Command<?> buildCommand() { Common.setDeployMode(getDeployMode()); if (checkConfig) { return new SeaTunnelConfValidateCommand(this); } if (encrypt) { return new ConfEncryptCommand(this); } if (decrypt) { return new ...
@Test public void testExecuteClientCommandArgsWithPluginName() throws FileNotFoundException, URISyntaxException { String configurePath = "/config/fake_to_inmemory.json"; String configFile = MultiTableSinkTest.getTestConfigFile(configurePath); ClientCommandArgs clientCommandArgs =...
public ScanResults run(ScanTarget scanTarget) throws ExecutionException, InterruptedException { return runAsync(scanTarget).get(); }
@Test public void run_whenSomeVulnDetectorFailed_returnsPartiallySucceededScanResult() throws ExecutionException, InterruptedException { Injector injector = Guice.createInjector( new FakeUtcClockModule(), new FakePluginExecutionModule(), new FakePortScannerBootstr...
@Override public int getMajorVersion() { return -1; }
@Test public void testGetMajorVersion() { if (driver.getMajorVersion() >= 0) { fail("getMajorVersion"); } }
@PostMapping("/listener") @Secured(action = ActionTypes.READ, signType = SignType.CONFIG) @ExtractorManager.Extractor(httpExtractor = ConfigListenerHttpParamExtractor.class) public void listener(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ...
@Test void testListener() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH + "/listener") .param("Listening-Configs", "test"); int actualValue = mockmvc.perform(builder).andReturn().getResponse().getStatus(); ...
@Udf public List<Long> generateSeriesLong( @UdfParameter(description = "The beginning of the series") final long start, @UdfParameter(description = "Marks the end of the series (inclusive)") final long end ) { return generateSeriesLong(start, end, end - start > 0 ? 1 : -1); }
@Test public void shouldComputeIntRangeWithOddStepLong() { final List<Long> range = rangeUdf.generateSeriesLong(0, 9, 3); assertThat(range, hasSize(4)); long index = 0; for (final long i : range) { assertThat(index, is(i)); index += 3; } }
public final void doesNotContainKey(@Nullable Object key) { check("keySet()").that(checkNotNull(actual).keySet()).doesNotContain(key); }
@Test public void failMapLacksKey() { ImmutableMap<String, String> actual = ImmutableMap.of("a", "A"); expectFailureWhenTestingThat(actual).doesNotContainKey("a"); assertFailureKeys("value of", "expected not to contain", "but was", "map was"); assertFailureValue("value of", "map.keySet()"); assert...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseWindows10WithIe11Test() { final String uaStr = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"; final UserAgent ua = UserAgentUtil.parse(uaStr); assertEquals("MSIE11", ua.getBrowser().toString()); assertEquals("11.0", ua.getVersion()); assertEquals("Trident", ua...
public void addSecretVersion(String secretId, String secretData) { checkArgument(!secretId.isEmpty(), "secretId can not be empty"); checkArgument(!secretData.isEmpty(), "secretData can not be empty"); checkIsUsable(); try { SecretName parent = SecretName.of(projectId, secretId); SecretPayloa...
@Test public void testAddSecretVersionWithInvalidNameShouldFail() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> testManager.addSecretVersion(SECRET_ID, "")); assertThat(exception).hasMessageThat().contains("secretData can not be empty"); }
public B id(String id) { this.id = id; return getThis(); }
@Test void id() { Builder builder = new Builder(); builder.id("id"); Assertions.assertEquals("id", builder.build().getId()); }
static int getVideoStreamIndex(@NonNull final String targetResolution, final MediaFormat targetFormat, @NonNull final List<VideoStream> videoStreams) { int fullMatchIndex = -1; int fullMatchNoRefreshIndex = -1; int resMatchOnl...
@Test public void getVideoDefaultStreamIndexCombinations() { final List<VideoStream> testList = List.of( generateVideoStream("mpeg_4-1080", MediaFormat.MPEG_4, "1080p", false), generateVideoStream("mpeg_4-720_60", MediaFormat.MPEG_4, "720p60", false), generat...
public boolean submitUnknownProcessingError(Message message, String details) { return submitProcessingErrorsInternal(message, ImmutableList.of(new Message.ProcessingError( ProcessingFailureCause.UNKNOWN, "Encountered an unrecognizable processing error", details)))...
@Test @DisplayName("Ensure Message#getId() is used as a fallback for Message#getMessageId()") public void submitProcessingErrorWithIdButnoMessageId() throws Exception { // given final Message msg = Mockito.mock(Message.class); when(msg.getId()).thenReturn("msg-uuid"); when(msg.pr...
public static String parseNamespace(NacosClientProperties properties) { String namespaceTmp = null; String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PA...
@Test void testParseNamespace() { String expect = "test"; Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.NAMESPACE, expect); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); Str...
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testMiscellaneousErroneousPatterns() { assertThat( getLiteral( int.class.getCanonicalName(), "1F" ) ).isNull(); assertThat( getLiteral( float.class.getCanonicalName(), "1D" ) ).isNull(); assertThat( getLiteral( int.class.getCanonicalName(), "_1" ) ).isNull(); assert...