focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { return uploadSegment(segmentFile, segmentName, _segmentUploadRequestTimeoutMs); }
@Test public void testUploadSuccess() throws URISyntaxException { Server2ControllerSegmentUploader uploader = new Server2ControllerSegmentUploader(_logger, _fileUploadDownloadClient, GOOD_CONTROLLER_VIP, "segmentName", 10000, mock(ServerMetrics.class), null, _llcSegmentName.getTableName(...
@Override public ClusterClientProvider<String> deploySessionCluster( ClusterSpecification clusterSpecification) throws ClusterDeploymentException { final ClusterClientProvider<String> clusterClientProvider = deployClusterInternal( KubernetesSessionClusterE...
@Test void testDeploySessionCluster() throws Exception { flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.SESSION.getName()); final ClusterClient<String> clusterClient = deploySessionCluster().getClusterClient(); checkClusterClient(clusterClient); checkUpdatedConf...
@Override public void start(EdgeExplorer explorer, int startNode) { IntArrayDeque stack = new IntArrayDeque(); GHBitSet explored = createBitSet(); stack.addLast(startNode); int current; while (stack.size() > 0) { current = stack.removeLast(); if (!exp...
@Test public void testDFS2() { DepthFirstSearch dfs = new DepthFirstSearch() { @Override protected GHBitSet createBitSet() { return new GHBitSetImpl(); } @Override public boolean goFurther(int v) { counter++; ...
@Override public void run(T configuration, Environment environment) throws Exception { final String name = name(); final String primaryName = name + PRIMARY; final String readerName = name + READER; final PooledDataSourceFactory primaryConfig = getDataSourceFactory(configuration); ...
@Test public void registersACustomNameOfHealthCheckAndDBPoolMetrics() throws Exception { final String name = "custom-hibernate"; final HibernateBundle<Configuration> customBundle = new HibernateBundle<Configuration>(entities, factory) { @Override public DataSourceFactory get...
@Override public HttpResponse handle(HttpRequest request) { final List<String> uris = circularArrayAccessLogKeeper.getUris(); return new HttpResponse(200) { @Override public void render(OutputStream outputStream) throws IOException { JsonGenerator generator ...
@Test void testEmpty() throws IOException { HttpResponse response = handler.handle(null); response.render(out); assertEquals("{\"entries\":[]}", out.toString()); }
private Mono<ServerResponse> listSinglePages(ServerRequest request) { var query = new SinglePagePublicQuery(request.exchange()); return singlePageFinder.list(query.getPage(), query.getSize(), query.toPredicate(), query.toComparator() ) ...
@Test void listSinglePages() { ListedSinglePageVo test = ListedSinglePageVo.builder() .metadata(metadata("test")) .spec(new SinglePage.SinglePageSpec()) .build(); ListResult<ListedSinglePageVo> pageResult = new ListResult<>(List.of(test)); when(singlePag...
@Override public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) { if (method == null) { return defaultName; } else if (method.getDeclaringClass().isAnnotationPresen...
@Test void nameForSetterMethodWorksWithNullField() { final MapperConfig<?> mapperConfig = mock(MapperConfig.class); final String name = strategy.nameForSetterMethod(mapperConfig, null, "defaultName"); assertThat(name).isEqualTo("defaultName"); }
public void setName(String name) throws IllegalStateException { if (name != null && name.equals(this.name)) { return; // idempotent naming } if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { this.name = name; } else { throw new IllegalStateExc...
@Test public void renameDefault() { context.setName(CoreConstants.DEFAULT_CONTEXT_NAME); context.setName("hello"); }
public Optional<DoFn.ProcessContinuation> run( PartitionRecord partitionRecord, ChangeStreamRecord record, RestrictionTracker<StreamProgress, StreamProgress> tracker, DoFn.OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, ...
@Test public void testChangeStreamMutationUser() { ByteStringRange partition = ByteStringRange.create("", ""); when(partitionRecord.getPartition()).thenReturn(partition); final Instant commitTimestamp = Instant.ofEpochMilli(1_000L); final Instant lowWatermark = Instant.ofEpochMilli(500L); ChangeSt...
@VisibleForTesting static Optional<Dependency> parseDependency(String line) { Matcher dependencyMatcher = SHADE_INCLUDE_MODULE_PATTERN.matcher(line); if (!dependencyMatcher.find()) { return Optional.empty(); } return Optional.of( Dependency.create( ...
@Test void testLineParsingVersion() { assertThat( ShadeParser.parseDependency( "Including external:dependency1:jar:1.0 in the shaded jar.")) .hasValueSatisfying( dependency -> assertThat(dependency.getVersion())....
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType; String colName = null...
@Test public void testAggregateSingleStatWhenNullValues() throws MetaException { List<String> partitions = Collections.singletonList("part1"); ColumnStatisticsData data1 = new ColStatsBuilder<>(Decimal.class).numNulls(1).numDVs(2).build(); List<ColStatsObjWithSourceInfo> statsList = Collections.s...
public static OptExpression bind(Pattern pattern, GroupExpression groupExpression) { Binder binder = new Binder(pattern, groupExpression); return binder.next(); }
@Test public void testBinderTop() { OptExpression expr = OptExpression.create(new MockOperator(OperatorType.LOGICAL_JOIN), new OptExpression(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN)), new OptExpression(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN))); Patte...
public EventJournalConfig setEnabled(boolean enabled) { this.enabled = enabled; return this; }
@Test(expected = UnsupportedOperationException.class) public void testReadOnlyClass_setEnabled_throwsException() { getReadOnlyConfig().setEnabled(false); }
@Override public boolean isPurgeable(String tableNameWithType, SegmentZKMetadata segmentZKMetadata) { long endTimeMs = segmentZKMetadata.getEndTimeMs(); // Check that the end time is between 1971 and 2071 if (!TimeUtils.timeValueInValidRange(endTimeMs)) { LOGGER.warn("Segment: {} of table: {} has i...
@Test public void testTimeRetention() { String tableNameWithType = "myTable_OFFLINE"; TimeRetentionStrategy retentionStrategy = new TimeRetentionStrategy(TimeUnit.DAYS, 30L); SegmentZKMetadata segmentZKMetadata = new SegmentZKMetadata("mySegment"); // Without setting time unit or end time, should no...
@Nonnull public static <T> Sink<T> noop() { return fromProcessor("noop", preferLocalParallelismOne(noopP())); }
@Test public void noop() { // Given populateList(srcList); // When Sink<Object> sink = Sinks.noop(); // Then p.readFrom(Sources.list(srcName)).writeTo(sink); execute(); // works without error }
@Override public String info(String name) { Object struct = db.get(name); if (isNull(struct)) throw new IllegalStateException(format("DB structure with name [%s] does not exist", name)); if (struct instanceof Set) return format("%s - Set - %d", name, ((Set) struct).size()); else if (struc...
@Test void cantGetInfoFromNonexistentDBStructureName() { Assertions.assertThrows(IllegalStateException.class, () -> db.info(TEST)); }
public static TriggerUuids toTriggerUuids(Workflow workflow) { TriggerUuids.TriggerUuidsBuilder builder = TriggerUuids.builder(); if (workflow.getTimeTriggers() != null && !workflow.getTimeTriggers().isEmpty()) { builder.timeTriggerUuid( IdHelper.createUuid(workflow.getTimeTriggers().toString())...
@Test public void testToTriggerUuids() { Workflow workflow = Workflow.builder() .id("test-wf-id") .timeTriggers(Collections.singletonList(new CronTimeTrigger())) .signalTriggers(Collections.singletonList(new SignalTrigger())) .build(); TriggerUuids trigg...
public static NetworkEndpoint forHostname(String hostname) { checkArgument( !InetAddresses.isInetAddress(hostname), "Expected hostname, got IP address '%s'", hostname); return NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.HOSTNAME) .setHostname(Hostname.newBuilder().setName...
@Test public void forHostname_withHostname_returnsHostnameNetworkEndpoint() { assertThat(NetworkEndpointUtils.forHostname("localhost")) .isEqualTo( NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.HOSTNAME) .setHostname(Hostname.newBuilder().setName("l...
@Override public int nrow() { return m; }
@Test public void testNrows() { System.out.println("nrow"); assertEquals(3, matrix.nrow()); }
public void sort(String id1, SortDir dir1, String id2, SortDir dir2) { Collections.sort(rows, new RowComparator(id1, dir1, id2, dir2)); }
@Test public void sortAlphaAscNumberDesc() { tm = unsortedDoubleTableModel(); verifyRowOrder("unsorted", tm, UNSORTED_IDS); tm.sort(ALPHA, SortDir.ASC, NUMBER, SortDir.DESC); verifyRowOrder("aand", tm, ROW_ORDER_AA_ND); }
public static <T> RemoteIterator<T> remoteIteratorFromSingleton( @Nullable T singleton) { return new SingletonIterator<>(singleton); }
@Test public void testSingletonStats() throws Throwable { IOStatsInstance singleton = new IOStatsInstance(); RemoteIterator<IOStatsInstance> it = remoteIteratorFromSingleton(singleton); extractStatistics(it); }
public long timeOfLastReset() { List<Status> statusList = sm.getCopyOfStatusList(); if (statusList == null) return -1; int len = statusList.size(); for (int i = len - 1; i >= 0; i--) { Status s = statusList.get(i); if (CoreConstants.RESET_MSG_PREFIX.e...
@Test public void withoutResetsStatusUtilShouldReturnNotFound() { context.getStatusManager().add(new InfoStatus("test", this)); assertEquals(-1, statusUtil.timeOfLastReset()); }
public ClientChannelInfo findChannel(final String group, final String clientId) { ConsumerGroupInfo consumerGroupInfo = this.consumerTable.get(group); if (consumerGroupInfo != null) { return consumerGroupInfo.findChannel(clientId); } return null; }
@Test public void findChannelTest() { register(); final ClientChannelInfo consumerManagerChannel = consumerManager.findChannel(GROUP, CLIENT_ID); Assertions.assertThat(consumerManagerChannel).isNotNull(); }
public void isAssignableTo(Class<?> clazz) { if (!clazz.isAssignableFrom(checkNotNull(actual))) { failWithActual("expected to be assignable to", clazz.getName()); } }
@Test public void testIsAssignableTo_differentTypes() { expectFailureWhenTestingThat(String.class).isAssignableTo(Exception.class); assertFailureValue("expected to be assignable to", "java.lang.Exception"); }
private synchronized boolean validateClientAcknowledgement(long h) { if (h < 0) { throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h); } if (h > MASK) { throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa...
@Test public void testValidateClientAcknowledgement_rollover_edgecase4() throws Exception { // Setup test fixture. final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1; final long h = 0; final long oldH = MAX; final Long lastUnackedX = 0L; // Execute ...
public Map<String, String> transform(Map<String, String> configs) { return transform(null, configs); }
@Test public void testReplaceVariableWithTTL() { // Execution Map<String, String> props = new HashMap<>(); props.put(MY_KEY, "${test:testPath:testKeyWithTTL}"); props.put(CONFIG_RELOAD_ACTION_CONFIG, CONFIG_RELOAD_ACTION_NONE); Map<String, String> result = configTransformer.t...
@Description("arc tangent of given fraction") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double atan2(@SqlType(StandardTypes.DOUBLE) double num1, @SqlType(StandardTypes.DOUBLE) double num2) { return Math.atan2(num1, num2); }
@Test public void testAtan2() { for (double doubleValue : DOUBLE_VALUES) { assertFunction("atan2(" + doubleValue + ", " + doubleValue + ")", DOUBLE, Math.atan2(doubleValue, doubleValue)); assertFunction("atan2(REAL '" + (float) doubleValue + "', REAL '" + (float) doubleValue + "'...
@Override public ChannelFuture writeData(final ChannelHandlerContext ctx, final int streamId, ByteBuf data, int padding, final boolean endOfStream, ChannelPromise promise) { promise = promise.unvoid(); final Http2Stream stream; try { stream = requireStream(streamId); ...
@Test public void dataWriteShouldCreateHalfClosedStream() throws Exception { writeAllFlowControlledFrames(); Http2Stream stream = createStream(STREAM_ID, false); ByteBuf data = dummyData(); ChannelPromise promise = newPromise(); encoder.writeData(ctx, STREAM_ID, data.retain(...
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testIsNull() { Evaluator evaluator = new Evaluator(STRUCT, isNull("z")); assertThat(evaluator.eval(TestHelpers.Row.of(1, 2, null))).as("null is null").isTrue(); assertThat(evaluator.eval(TestHelpers.Row.of(1, 2, 3))).as("3 is not null").isFalse(); Evaluator structEvaluator = new Eva...
static List<String> parseEtcResolverSearchDomains() throws IOException { return parseEtcResolverSearchDomains(new File(ETC_RESOLV_CONF_FILE)); }
@Test public void searchDomainsWithMultipleSearch(@TempDir Path tempDir) throws IOException { File f = buildFile(tempDir, "search linecorp.local\n" + "search squarecorp.local\n" + "nameserver 127.0.0.2\n"); List<String> domains = UnixResolverDnsS...
@Override public long get(long key1, long key2) { assert key1 != unassignedSentinel : "get() called with key1 == nullKey1 (" + unassignedSentinel + ')'; return super.get0(key1, key2); }
@Test(expected = AssertionError.class) @RequireAssertEnabled public void testGet_whenDisposed() { hsa.dispose(); hsa.get(1, 1); }
public static URL getCorrectHostnamePort(String hostPort) { return validateHostPortString(hostPort); }
@Test void testCorrectHostnamePort() throws Exception { final URL url = new URL("http", "foo.com", 8080, "/index.html"); assertThat(NetUtils.getCorrectHostnamePort("foo.com:8080/index.html")).isEqualTo(url); }
@Override public void receiveConfigInfo(String configInfo) { if (StringUtils.isEmpty(configInfo)) { return; } Properties properties = new Properties(); try { properties.load(new StringReader(configInfo)); innerReceive(properties); ...
@Test void testReceiveConfigInfo() { final Deque<Properties> q2 = new ArrayDeque<Properties>(); PropertiesListener a = new PropertiesListener() { @Override public void innerReceive(Properties properties) { q2.offer(properties); } }; ...
public void verifyState(HttpRequest request, HttpResponse response, OAuth2IdentityProvider provider) { verifyState(request, response, provider, DEFAULT_STATE_PARAMETER_NAME); }
@Test public void fail_with_AuthenticationException_when_cookie_is_missing() { when(request.getCookies()).thenReturn(new Cookie[]{}); assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) .hasMessage("Cookie 'OAUTHSTATE' is missing") .isInstanceOf(AuthenticationExce...
@Override public int getTotalNumberOfRecords(Configuration conf) throws HiveJdbcDatabaseAccessException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { initializeDatabaseConnection(conf); String tableName = getQualifiedTableName(conf); // Always use...
@Test public void testGetTotalNumberOfRecords_noRecords() throws HiveJdbcDatabaseAccessException { Configuration conf = buildConfiguration(); conf.set(JdbcStorageConfig.QUERY.getPropertyName(), "select * from test_strategy where strategy_id = '25'"); DatabaseAccessor accessor = DatabaseAccessorFactory.get...
@Override protected void onStateExpiry(UUID sessionId, TransportProtos.SessionInfoProto sessionInfo) { log.debug("Session with id: [{}] has expired due to last activity time.", sessionId); SessionMetaData expiredSession = sessions.remove(sessionId); if (expiredSession != null) { ...
@Test void givenSessionDoesNotExist_whenOnStateExpiryCalled_thenShouldNotPerformExpirationActions() { // GIVEN TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder() .setSessionIdMSB(SESSION_ID.getMostSignificantBits()) .setSessio...
@Override public boolean isPluginOfType(final String extension, String pluginId) { return goPluginOSGiFramework.hasReferenceFor(GoPlugin.class, pluginId, extension); }
@Test void shouldSayPluginIsOfGivenExtensionTypeWhenReferenceIsFound() { String pluginId = "plugin-id"; String extensionType = "sample-extension"; GoPluginIdentifier pluginIdentifier = new GoPluginIdentifier(extensionType, List.of("1.0")); final GoPlugin goPlugin = mock(GoPlugin.clas...
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DefaultUrlProvider(session.getHost()).toUrl(file); if(file.isFile()) { // Authenticated browser download using cookie-based Google account authentication in conjunction with ACL lis...
@Test public void testGet() { assertEquals("https://storage.cloud.google.com/c/f", new GoogleStorageUrlProvider(session).toUrl( new Path("/c/f", EnumSet.of(Path.Type.file))).find(DescriptiveUrl.Type.authenticated).getUrl()); }
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image) throws IOException { if (isGrayImage(image)) { return createFromGrayImage(image, document); } // We try to encode the image with predictor if (USE_PREDICTOR_ENCODER...
@Test void testCreateLosslessFromImageINT_ARGB() throws IOException { PDDocument document = new PDDocument(); BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png")); // create an ARGB image int w = image.getWidth(); int h = image.getHeight(); ...
public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException { checkMaybeCompatible(source, target); if (source.isOptional() && !target.isOptional()) { if (target.defaultValue() != null) { if (record != null) { ...
@Test public void testProjectMissingDefaultValuedStructField() { final Schema source = SchemaBuilder.struct().build(); final Schema target = SchemaBuilder.struct().field("id", SchemaBuilder.int64().defaultValue(42L).build()).build(); assertEquals(42L, (long) ((Struct) SchemaProjector.project...
public static String prettyJSON(String json) { return prettyJSON(json, TAB_SEPARATOR); }
@Test public void testRenderResultComplexArray() throws Exception { assertEquals("[\n" + TAB + "1,\n" + TAB + "{\n" + TAB + TAB + "\"A\": \"B\"\n" + TAB + "}\n]", prettyJSON("[1,{\"A\":\"B\"}]")); }
@Override public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) { ScannerReport.LineCoverage reportCoverage = getNextLineCoverageIfMatchLine(lineBuilder.getLine()); if (reportCoverage != null) { processCoverage(lineBuilder, reportCoverage); coverage = null; } return Optio...
@Test public void nothing_to_do_when_no_coverage_info() { CoverageLineReader computeCoverageLine = new CoverageLineReader(Collections.<ScannerReport.LineCoverage>emptyList().iterator()); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(comp...
public static Executor scopeToJob(JobID jobID, Executor executor) { checkArgument(!(executor instanceof MdcAwareExecutor)); return new MdcAwareExecutor<>(executor, asContextData(jobID)); }
@Test void testScopeExecutorService() throws Exception { assertJobIDLogged( jobID -> MdcUtils.scopeToJob(jobID, Executors.newDirectExecutorService()) .submit(LOGGING_RUNNABLE) .get()); }
public final long getJobFinishTime() { return jobFinishTime; }
@Test public final void testGetJobFinishTime() { Assert.assertNull(resourceSkyline); ReservationInterval riAdd = new ReservationInterval(0, 10); skylineList.addInterval(riAdd, resource1); riAdd = new ReservationInterval(10, 20); skylineList.addInterval(riAdd, resource1); resourceSkyline = ...
@VisibleForTesting SegmentSizeRecommendations estimate(long generatedSegmentSize, int desiredSegmentSize, int numRecordsOfGeneratedSegment, long numRecordsPerPush) { // calc num rows in desired segment double sizeRatio = (double) desiredSegmentSize / generatedSegmentSize; long numRowsInDesiredSegme...
@Test public void testEstimate() { /* * numRecordsPerPush -> num records per push * numRecordsOfGeneratedSegment -> num records of generated segment * generatedSegmentSize -> generated segment size * desiredSegmentSize -> desired segment size */ long numRecordsPerPush = 20 * MILLI...
@Override public MutableAnalysisMetadataHolder setBranch(Branch branch) { checkState(!this.branch.isInitialized(), "Branch has already been set"); boolean isCommunityEdition = editionProvider.get().filter(t -> t == EditionProvider.Edition.COMMUNITY).isPresent(); checkState( !isCommunityEdition || br...
@Test public void setBranch_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME)); assertThatThrownBy(() -> underTest.setBranch(new DefaultBranchImpl("main"))) .is...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void literal() throws ScanException { Tokenizer tokenizer = new Tokenizer("abc"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "abc"); assertEquals(witness, node); }
public static ImportResult merge(ImportResult ir1, ImportResult ir2) { if (ir1.getType() == ResultType.ERROR) { return ir1; } if (ir2.getType() == ResultType.ERROR) { return ir2; } ImportResult res = new ImportResult(ResultType.OK); res.bytes = Stream.of(ir1.getBytes(), ir2.getBytes(...
@Test public void mergeOk() { assertEquals(OK, ImportResult.merge(OK, OK)); }
@VisibleForTesting static List<Tuple2<ConfigGroup, String>> generateTablesForClass( Class<?> optionsClass, Collection<OptionWithMetaInfo> optionWithMetaInfos) { ConfigGroups configGroups = optionsClass.getAnnotation(ConfigGroups.class); List<OptionWithMetaInfo> allOptions = selectOptions...
@Test void testClassWithoutOptionsIsIgnored() { assertThat( ConfigOptionsDocGenerator.generateTablesForClass( EmptyConfigOptions.class, ConfigurationOptionLocator.extractConfigOptions( ...
@Override public Optional<ResultSubpartition.BufferAndBacklog> consumeBuffer( int nextBufferToConsume, Collection<Buffer> buffersToRecycle) throws Throwable { if (!checkAndGetFirstBufferIndexOrError(nextBufferToConsume, buffersToRecycle) .isPresent()) { return Optiona...
@Test void testConsumeBuffer() throws Throwable { TestingSubpartitionConsumerInternalOperation viewNotifier = new TestingSubpartitionConsumerInternalOperation(); HsSubpartitionFileReaderImpl subpartitionFileReader = createSubpartitionFileReader(0, viewNotifier); ...
public static DataMap convertMap(Map<String, ?> input, boolean stringify) { return convertMap(input, false, stringify); }
@Test void testConvertMapWithDataComplex() { DataMap parent = DataComplexUtil.convertMap(inputMapWithDataComplex()); Assert.assertNotNull(parent); Assert.assertEquals(parent.size(), 2); Assert.assertTrue(parent.containsKey("child1")); DataMap child1 = parent.getDataMap("child1"); Assert.a...
public List<String> getCwe() { return cwe; }
@Test @SuppressWarnings("squid:S2699") public void testGetCwe() { //already tested, this is just left so the IDE doesn't recreate it. }
public String map(AmountRequest request) { if (request instanceof OffsetBasedPageRequest && ((OffsetBasedPageRequest) request).getOffset() > 0L) { return sqlOffsetBasedPageRequestMapper.mapToSqlQuery((OffsetBasedPageRequest) request, jobTable); } else { return sqlAmountRequestMap...
@Test void sqlJobPageRequestMapperMapsOffsetBasedPageRequest() { OffsetBasedPageRequest offsetBasedPageRequest = ascOnUpdatedAt(20, 10); String filter = jobPageRequestMapper.map(offsetBasedPageRequest); assertThat(filter).isEqualTo(" ORDER BY updatedAt ASC LIMIT :limit OFFSET :offset"); ...
public InputStream acquire(UnderFileSystem ufs, String path, FileId fileId, OpenOptions openOptions) throws IOException { if (!ufs.isSeekable() || !CACHE_ENABLED) { // only seekable UFSes are cachable/reusable, always return a new input stream return ufs.openExistingFile(path, openOptions); } ...
@Test public void multipleCheckIn() throws Exception { mManager.acquire(mUfs, FILE_NAME, FILE_ID, OpenOptions.defaults().setOffset(2)); mManager.acquire(mUfs, FILE_NAME, FILE_ID, OpenOptions.defaults().setOffset(4)); mManager.acquire(mUfs, FILE_NAME, FILE_ID, OpenOptions.defaults().setOffset(6)); // 3...
public static int readUint16BE(ByteBuffer buf) throws BufferUnderflowException { return Short.toUnsignedInt(buf.order(ByteOrder.BIG_ENDIAN).getShort()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testReadUint16BEThrowsException1() { ByteUtils.readUint16BE(new byte[]{1}, 2); }
@Override protected int poll() throws Exception { // must reset for each poll shutdownRunningTask = null; pendingExchanges = 0; List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call(); // okay we have some response from aws so lets mark the cons...
@Test void shouldRequest11MessagesWithTwoReceiveRequest() throws Exception { // given var expectedMessages = IntStream.range(0, 11).mapToObj(Integer::toString).toList(); expectedMessages.stream().map(this::message).forEach(sqsClientMock::addMessage); try (var tested = createConsumer...
@Override public String selectForUpdateSkipLocked() { return supportsSelectForUpdateSkipLocked ? " FOR UPDATE SKIP LOCKED" : ""; }
@Test void mySQL830DoesSupportSelectForUpdateSkipLocked() { assertThat(new MySqlDialect("MySQL", "8.3.0").selectForUpdateSkipLocked()) .isEqualTo(" FOR UPDATE SKIP LOCKED"); }
@CanIgnoreReturnValue public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); ListMultimap<?, ?> extra = difference(actual, expectedMult...
@Test public void containsExactlyFailureBoth() { ImmutableMultimap<Integer, String> expected = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); ListMultimap<Integer, String> actual = LinkedListMultimap.create(expected); actual.remove(3, "six"); actual.remove(4, "five")...
public boolean shouldStartExecutor(String executorName) { return !notStartExecutors.contains(executorName) && (startExecutors.isEmpty() || startExecutors.contains(executorName)); }
@Test void shouldStartExecutor() { assertTrue(startExecutorService.shouldStartExecutor("ExecutorName")); startExecutorService.applyOptions(List.of("ExecutorName"), Collections.emptyList()); assertTrue(startExecutorService.shouldStartExecutor("ExecutorName")); startExecutorService.a...
public VersionMatchResult matches(DeploymentInfo info) { // Skip if no manifest configuration if(info.getManifest() == null || info.getManifest().size() == 0) { return VersionMatchResult.SKIPPED; } for (ManifestInfo manifest: info.getManifest()) { Versio...
@Test public void testFails() throws IOException { Set<MavenInfo> maven = new HashSet<MavenInfo>(); ManifestInfo manifest = new ManifestInfo(new java.util.jar.Manifest(this.getClass().getResourceAsStream("/org/hotswap/agent/versions/matcher/TEST.MF"))); DeploymentInfo info = new Deploymen...
public void set(String name, String value) { set(name, value, null); }
@Test public void testSettingKeyNull() throws Exception { Configuration config = new Configuration(); try { config.set(null, "test"); fail("Should throw an IllegalArgumentException exception "); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); assertEquals...
public SegmentCommitter createSegmentCommitter(SegmentCompletionProtocol.Request.Params params, String controllerVipUrl) throws URISyntaxException { boolean uploadToFs = _streamConfig.isServerUploadToDeepStore(); String peerSegmentDownloadScheme = _tableConfig.getValidationConfig().getPeerSegmentDow...
@Test(description = "when controller supports split commit, server should always use split segment commit") public void testSplitSegmentCommitterIsDefault() throws URISyntaxException { TableConfig config = createRealtimeTableConfig("test").build(); ServerSegmentCompletionProtocolHandler protocolHandler ...
public LinkParameter value(String value) { this.value = value; return this; }
@Test public void testValue() { LinkParameter linkParameter = new LinkParameter(); linkParameter.setValue("foo"); linkParameter.setValue("bar"); linkParameter.setValue("baz"); Assert.assertEquals(linkParameter.value("bar"), linkParameter); Assert.assertEquals(linkPar...
@Override public int hashCode() { int result = 1; result = 31 * result + status.hashCode(); result = 31 * result + super.hashCode(); return result; }
@Test public void testNotEquals() { HttpResponse ok = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse notFound = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); assertNotEquals(ok, notFound); assertNotEquals(ok.hashCode(...
@Override public Num getValue(int index) { return averageTrueRangeIndicator.getValue(index); }
@Test public void testXls() throws Exception { BarSeries xlsSeries = xls.getSeries(); Indicator<Num> indicator; indicator = getIndicator(xlsSeries, 1); assertIndicatorEquals(xls.getIndicator(1), indicator); assertEquals(4.8, indicator.getValue(indicator.getBarSeries().getEnd...
public static String intToHex(Integer i) { return prepareNumberHexString(i.longValue(), true, false, HEX_LEN_MIN, HEX_LEN_INT_MAX); }
@Test public void intToHex_Test() { Assertions.assertEquals("FFF5EE", TbUtils.intToHex(-2578)); Assertions.assertEquals("0xFFD8FFA6", TbUtils.intToHex(0xFFD8FFA6, true, true)); Assertions.assertEquals("0xA6FFD8FF", TbUtils.intToHex(0xFFD8FFA6, false, true)); Assertions.assertEquals("...
public void updateInstance(Service service, Instance instance, String clientId) { Service singleton = ServiceManager.getInstance().getSingleton(service); if (singleton.isEphemeral()) { throw new NacosRuntimeException(NacosException.INVALID_PARAM, String.format("Current se...
@Test void updateInstance() throws Exception { Field clientManagerField = PersistentClientOperationServiceImpl.class.getDeclaredField("clientManager"); clientManagerField.setAccessible(true); // Test register instance persistentClientOperationServiceImpl.updateInstance(service, insta...
@Nullable public byte[] getValue() { return mValue; }
@Test public void setValue_SFLOAT_hex() { final MutableData data = new MutableData(new byte[2]); data.setValue(10.1f, Data.FORMAT_SFLOAT, 0); assertArrayEquals(new byte[] { 0x65, (byte) 0xF0 }, data.getValue()); }
@Transactional(readOnly = true) public User readUserIfValid(String username, String password) { Optional<User> user = userService.readUserByUsername(username); if (!isExistUser(user)) { log.warn("해당 유저가 존재하지 않습니다. username: {}", username); throw new UserErrorException(UserEr...
@DisplayName("로그인 시, username에 해당하는 유저가 존재하지 않으면 UserErrorException을 발생시킨다.") @Test void readUserIfNotFound() { // given given(userService.readUserByUsername("pennyway")).willThrow(new UserErrorException(UserErrorCode.NOT_FOUND)); // when - then UserErrorException exception = as...
public long appendControlMessages(MemoryRecordsCreator valueCreator) { appendLock.lock(); try { ByteBuffer buffer = memoryPool.tryAllocate(maxBatchSize); if (buffer != null) { try { forceDrain(); MemoryRecords memoryRecords ...
@Test public void testInvalidControlRecordEpoch() { int leaderEpoch = 17; long baseOffset = 157; int lingerMs = 50; int maxBatchSize = 512; ByteBuffer buffer = ByteBuffer.allocate(maxBatchSize); Mockito.when(memoryPool.tryAllocate(maxBatchSize)) .then...
public Map<StepDependencyType, StepDependencies> getStepDependencies( String workflowId, long workflowInstanceId, long workflowRunId, String stepId, String stepAttempt) { try { return getStepInstanceFieldByIds( StepInstanceField.DEPENDENCIES, workflowId, ...
@Test public void testGetStepInstanceStepDependenciesSummary() { Map<StepDependencyType, StepDependencies> dependencies = stepDao.getStepDependencies(TEST_WORKFLOW_ID, 1, 1, "job1", "1"); StepDependencies stepDependencies = dependencies.get(StepDependencyType.SIGNAL); assertFalse(stepDependencies....
static JavaType constructType(Type type) { try { return constructTypeInner(type); } catch (Exception e) { throw new InvalidDataTableTypeException(type, e); } }
@Test void should_provide_canonical_representation_of_object() { JavaType javaType = TypeFactory.constructType(Object.class); assertThat(javaType.getTypeName(), is(Object.class.getTypeName())); }
@Override @CanIgnoreReturnValue public Key register(Watchable watchable, Iterable<? extends WatchEvent.Kind<?>> eventTypes) throws IOException { JimfsPath path = checkWatchable(watchable); Key key = super.register(path, eventTypes); Snapshot snapshot = takeSnapshot(path); synchronized (this...
@Test(timeout = 2000) public void testWatchForOneEventType() throws IOException, InterruptedException { JimfsPath path = createDirectory(); watcher.register(path, ImmutableList.of(ENTRY_CREATE)); Files.createFile(path.resolve("foo")); assertWatcherHasEvents(new Event<>(ENTRY_CREATE, 1, fs.getPath("f...
public static Set<String> configNames() { return CONFIG.names(); }
@Test public void testFromPropsInvalid() { GroupConfig.configNames().forEach(name -> { if (GroupConfig.CONSUMER_SESSION_TIMEOUT_MS_CONFIG.equals(name)) { assertPropertyInvalid(name, "not_a_number", "-0.1", "1.2"); } else if (GroupConfig.CONSUMER_HEARTBEAT_INTERVAL_MS_...
@Override public synchronized void execute() { boolean debugMode = conf.isLoadBalancerDebugModeEnabled() || log.isDebugEnabled(); if (debugMode) { log.info("Load balancer enabled: {}, Shedding enabled: {}.", conf.isLoadBalancerEnabled(), conf.isLoadBalancerSheddingEna...
@Test(timeOut = 30 * 1000) public void testExecuteMoreThenOnceWhenFirstNotDone() throws InterruptedException { AtomicReference<List<Metrics>> reference = new AtomicReference<>(); UnloadCounter counter = new UnloadCounter(); LoadManagerContext context = setupContext(); BrokerRegistry ...
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test public void testPolymorphicType() throws Exception { thrown.expect(RuntimeException.class); thrown.expectMessage(Matchers.containsString("Unable to infer a coder")); // Create won't infer a default coder in this case. p.apply(Create.of(new Record(), new Record2())); p.run(); }
@Nullable @Override public RecordAndPosition<E> next() { final RecordAndPosition<E> next = this.element; this.element = null; return next; }
@Test void testEmptyConstruction() { final SingletonResultIterator<Object> iter = new SingletonResultIterator<>(); assertThat(iter.next()).isNull(); }
public synchronized @Nullable WorkItemServiceState reportSuccess() throws IOException { checkState(!finalStateSent, "cannot reportSuccess after sending a final state"); checkState(worker != null, "setWorker should be called before reportSuccess"); if (wasAskedToAbort) { LOG.info("Service already asked...
@Test public void reportSuccess() throws IOException { when(worker.extractMetricUpdates()).thenReturn(Collections.emptyList()); statusClient.setWorker(worker, executionContext); statusClient.reportSuccess(); verify(workUnitClient).reportWorkItemStatus(statusCaptor.capture()); WorkItemStatus workS...
public PublisherAgreement signPublisherAgreement(UserData user) { checkApiUrl(); var eclipseToken = checkEclipseToken(user); var headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(eclipseToken.accessToken); headers.setAc...
@Test public void testSignPublisherAgreement() throws Exception { var user = mockUser(); Mockito.when(restTemplate.postForEntity(any(String.class), any(), eq(String.class))) .thenReturn(mockAgreementResponse()); Mockito.when(repositories.findVersionsByUser(user, false)) ...
@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 shouldThrowFromGetValueWithIdSchemaOnOtherException() throws Exception { // Given: when(srClient.getSchemaBySubjectAndId(any(), anyInt())) .thenThrow(new IOException("boom")); // When: final Exception e = assertThrows( KsqlException.class, () -> supplier.getV...
@Override public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) { if (stateManager.taskType() != TaskType.ACTIVE) { throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ...
@Test public void globalWindowStoreShouldBeReadOnly() { foreachSetUp(); when(stateManager.taskType()).thenReturn(TaskType.ACTIVE); when(stateManager.getGlobalStore(anyString())).thenReturn(null); final WindowStore<String, Long> windowStore = mock(WindowStore.class); when(st...
public List<PartitionInfo> getTopicMetadata(String topic, boolean allowAutoTopicCreation, Timer timer) { MetadataRequest.Builder request = new MetadataRequest.Builder(Collections.singletonList(topic), allowAutoTopicCreation); Map<String, List<PartitionInfo>> topicMetadata = getTopicMetadata(request, tim...
@Test public void testGetTopicMetadataInvalidTopic() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.INVALID_TOPIC_EXCEPTION)); assertThrows(InvalidTopicException.class, () -> topicMetadataFetcher.getTopicMetadata(topicName, true, t...
@Override public Set<Long> calculateUsers(DelegateExecution execution, String param) { Set<Long> postIds = StrUtils.splitToLongSet(param); List<AdminUserRespDTO> users = adminUserApi.getUserListByPostIds(postIds); return convertSet(users, AdminUserRespDTO::getId); }
@Test public void testCalculateUsers() { // 准备参数 String param = "1,2"; // mock 方法 List<AdminUserRespDTO> users = convertList(asSet(11L, 22L), id -> new AdminUserRespDTO().setId(id)); when(adminUserApi.getUserListByPostIds(eq(asSet(1L, 2L)))).thenReturn(users);...
public int[] startBatchWithRunStrategy( @NotNull String workflowId, @NotNull RunStrategy runStrategy, List<WorkflowInstance> instances) { if (instances == null || instances.isEmpty()) { return new int[0]; } return withMetricLogError( () -> { Set<String> uuids = ...
@Test public void testStartBatchRunStrategyWithQueue() throws Exception { List<WorkflowInstance> batch = prepareBatch(); int[] res = runStrategyDao.startBatchWithRunStrategy( TEST_WORKFLOW_ID, RunStrategy.create("PARALLEL"), batch); assertArrayEquals(new int[] {1, 0, 1}, res); asse...
@Override public User registerUser(RegisterRequest registerRequest) { return userServiceClient.register(registerRequest).getBody(); }
@Test void registerUser_ValidRegisterRequest_ReturnsUser() { // Given RegisterRequest registerRequest = RegisterRequest.builder() .email("valid.email@example.com") .password("validPassword123") .firstName("John") .lastName("Doe") ...
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR if (splittee == null || splitChar == null) { return new String[0]; } final String EMPTY_ELEMENT = ""; int spot; final int splitLength = splitChar.length(); final Stri...
@Test public void testSplitStringStringFalseWithTrailingSplitChars() { // Test ignore trailing split characters assertThat("Include the trailing split chars", JOrphanUtils.split("a,bc,,", ",", false), CoreMatchers.equalTo(new String[]{"a", "bc", "", ""})); }
@Override public Messages process(Messages messages) { try (Timer.Context ignored = executionTime.time()) { final State latestState = stateUpdater.getLatestState(); if (latestState.enableRuleMetrics()) { return process(messages, new RuleMetricsListener(metricRegistry)...
@Test @SuppressForbidden("Allow using default thread factory") public void testMetrics() { final RuleMetricsConfigService ruleMetricsConfigService = mock(RuleMetricsConfigService.class); when(ruleMetricsConfigService.get()).thenReturn(RuleMetricsConfigDto.createDefault()); final ClusterE...
public boolean isGreaterThanOrEqual(String clusterId, Version version) { return isGreaterThanOrEqual(() -> clusterVersionGetCommander.getCassandraVersion(clusterId), version); }
@Test void isGreaterThanOrEqual() { // given BDDMockito.when(clusterVersionGetCommander.getCassandraVersion(CLUSTER_ID)).thenReturn(Version.parse("4.0.1")); // when assertThat(clusterVersionEvaluator.isGreaterThanOrEqual(CLUSTER_ID, Version.parse("4.0.0"))).isTrue(); assertT...
@SuppressWarnings("unchecked") public static <T> AgentServiceLoader<T> getServiceLoader(final Class<T> service) { return (AgentServiceLoader<T>) LOADERS.computeIfAbsent(service, AgentServiceLoader::new); }
@Test void assertGetServiceLoaderWithEmptyInstances() { assertTrue(AgentServiceLoader.getServiceLoader(AgentServiceEmptySPIFixture.class).getServices().isEmpty()); }
public Optional<Object> evaluate(final Map<String, Object> columnPairsMap, final String outputColumn, final String regexField) { boolean matching = true; boolean isRegex = regexField != null && columnValues.containsKey(regexField) && (boolean) columnV...
@Test void evaluateKeyFoundMultipleNotMatching() { KiePMMLRow kiePMMLRow = new KiePMMLRow(COLUMN_VALUES); Map<String, Object> columnPairsMap = IntStream.range(0, 3).boxed() .collect(Collectors.toMap(i -> "KEY-" + i, integer -> integer)); ...
@Override public int length() { return 1; }
@Test public void testLength() { System.out.println("length"); ExponentialDistribution instance = new ExponentialDistribution(1.0); instance.rand(); assertEquals(1, instance.length()); }
public static Config getConfig( Configuration configuration, @Nullable HostAndPort externalAddress) { return getConfig( configuration, externalAddress, null, PekkoUtils.getForkJoinExecutorConfig( ActorSystemBoots...
@Test void getConfigDefaultsStartupTimeoutTo10TimesOfAskTimeout() { final Configuration configuration = new Configuration(); configuration.set(RpcOptions.ASK_TIMEOUT_DURATION, Duration.ofMillis(100)); final Config config = PekkoUtils.getConfig(configuration, new HostAndPort(...
@Override public String getOnuStatistics(String target) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId(...
@Test public void testInvalidGetOnuStatsInput() throws Exception { String reply; String target; for (int i = ZERO; i < INVALID_GET_STATS_TCS.length; i++) { target = INVALID_GET_STATS_TCS[i]; reply = voltConfig.getOnuStatistics(target); assertNull("Incorre...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_execute_prepared_and_bound_statements() { // Given String queries = "@prepare[ps]=INSERT INTO zeppelin.prepared(key,val) VALUES(?,?)\n" + "@prepare[select]=SELECT * FROM zeppelin.prepared WHERE key=:key\n" + "@bind[ps]='myKey','myValue'\n" + "@bind[select]='myKey'"; ...
public final AccessControlEntry entry() { return entry; }
@Test public void shouldThrowOnAnyPatternType() { assertThrows(IllegalArgumentException.class, () -> new AclBinding(new ResourcePattern(ResourceType.TOPIC, "foo", PatternType.ANY), ACL1.entry())); }
public static String getStringOrNull(String property, JsonNode node) { if (!node.has(property)) { return null; } JsonNode pNode = node.get(property); if (pNode != null && pNode.isNull()) { return null; } return getString(property, node); }
@Test public void getStringOrNull() throws JsonProcessingException { assertThat(JsonUtil.getStringOrNull("x", JsonUtil.mapper().readTree("{}"))).isNull(); assertThat(JsonUtil.getStringOrNull("x", JsonUtil.mapper().readTree("{\"x\": \"23\"}"))) .isEqualTo("23"); assertThat(JsonUtil.getStringOrNull(...
@Override public boolean containsKey(Object key) { return map1.containsKey(key) || map2.containsKey(key); }
@Test public void testContainsKey() { Map<String, String> map1 = new HashMap<>(); map1.put("key1", "value1"); Map<String, String> map2 = new HashMap<>(); map2.put("key2", "value2"); Map<String, String> aggregatingMap = AggregatingMap.aggregate(map1, map2); assertTru...
private BinPacking() {}
@Test void testBinPacking() { assertThat(asList(asList(1, 2), singletonList(3), singletonList(4), singletonList(5))) .as("Should pack the first 2 values") .isEqualTo(pack(asList(1, 2, 3, 4, 5), 3)); assertThat(asList(asList(1, 2), singletonList(3), singletonList(4), ...
public static InetAddress findFirstNonLoopbackAddress() { InetAddress result = null; try { int lowest = Integer.MAX_VALUE; for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); nics.hasMoreElements(); ) { N...
@Test void findFirstNonLoopbackAddress() { InetAddress address = InetUtils.findFirstNonLoopbackAddress(); assertNotNull(address); assertFalse(address.isLoopbackAddress()); }
@Override public void deleteClient(ClientDetailsEntity client) throws InvalidClientException { if (clientRepository.getById(client.getId()) == null) { throw new InvalidClientException("Client with id " + client.getClientId() + " was not found"); } // clean out any tokens that this client had issued tokenR...
@Test(expected = InvalidClientException.class) public void deleteClient_badId() { Long id = 12345L; ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); Mockito.when(client.getId()).thenReturn(id); Mockito.when(clientRepository.getById(id)).thenReturn(null); service.deleteClient(client); ...