focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public ResultSet executeQuery(String sql) throws SQLException { StatementResult result = executeInternal(sql); if (!result.isQueryResult()) { result.close(); throw new SQLException(String.format("Statement[%s] is not a query.", sql)); } currentResult...
@Test @Timeout(value = 60) public void testExecuteQuery() throws Exception { try (FlinkConnection connection = new FlinkConnection(getDriverUri())) { try (Statement statement = connection.createStatement()) { // CREATE TABLE is not a query and has no results a...
public Optional<String> validate(MonitoringInfo monitoringInfo) { if (monitoringInfo.getUrn().isEmpty() || monitoringInfo.getType().isEmpty()) { return Optional.of( String.format( "MonitoringInfo requires both urn %s and type %s to be specified.", monitoringInfo.getUrn()...
@Test public void validateReturnsErrorOnInvalidMonitoringInfoLabels() { MonitoringInfo testInput = MonitoringInfo.newBuilder() .setUrn(MonitoringInfoConstants.Urns.ELEMENT_COUNT) .setType(TypeUrns.SUM_INT64_TYPE) .putLabels(MonitoringInfoConstants.Labels.PTRANSFORM, "un...
public static ErrorResponse fromJson(int code, String json) { return JsonUtil.parse(json, node -> OAuthErrorResponseParser.fromJson(code, node)); }
@Test public void testOAuthErrorResponseFromJson() { String error = OAuth2Properties.INVALID_CLIENT_ERROR; String description = "Credentials given were invalid"; String uri = "http://iceberg.apache.org"; String json = String.format( "{\"error\":\"%s\",\"error_description\":\"%s\",\...
@Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof ChangesOnMyIssuesNotification)) { return null; } ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif; if (notification.getChange() instanceof AnalysisChange) { ...
@Test public void format_set_html_message_with_issue_status_title_handles_plural_when_change_from_analysis() { Project project = newProject("foo"); Rule rule = newRandomNotAHotspotRule("bar"); Set<ChangedIssue> closedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(status -> newCha...
void refreshNamenodes(Configuration conf) throws IOException { LOG.info("Refresh request received for nameservices: " + conf.get(DFSConfigKeys.DFS_NAMESERVICES)); Map<String, Map<String, InetSocketAddress>> newAddressMap = null; Map<String, Map<String, InetSocketAddress>> newLifelineAddressMa...
@Test public void testSimpleSingleNS() throws Exception { Configuration conf = new Configuration(); conf.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://mock1:8020"); bpm.refreshNamenodes(conf); assertEquals("create #1\n", log.toString()); }
public URL convert(String value) { if (isBlank(value)) { throw new ParameterException(getErrorString("a blank value", "a valid URL")); } try { return URLUtil.parseURL(value); } catch (IllegalArgumentException e) { throw new ParameterException(getError...
@Test public void urlIsCreatedFromFilePath() { URL url = converter.convert("/path/to/something"); // on *ux the path part of the URL is equal to the given path // on Windows C: is prepended, which is expected assertThat(url.getPath(), endsWith("/path/to/something")); }
@Override public String execute(CommandContext commandContext, String[] args) { if (ArrayUtils.isEmpty(args)) { return "Please input the index of the method you want to invoke, eg: \r\n select 1"; } Channel channel = commandContext.getRemote(); String message = args[0]; ...
@Test void testInvokeWithoutMethodList() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) ...
ControllerResult<Map<String, ApiError>> updateFeatures( Map<String, Short> updates, Map<String, FeatureUpdate.UpgradeType> upgradeTypes, boolean validateOnly ) { TreeMap<String, ApiError> results = new TreeMap<>(); List<ApiMessageAndVersion> records = BoundedL...
@Test public void testCannotUnsafeDowngradeToHigherVersion() { FeatureControlManager manager = TEST_MANAGER_BUILDER1.build(); assertEquals(ControllerResult.of(Collections.emptyList(), singletonMap(MetadataVersion.FEATURE_NAME, new ApiError(Errors.INVALID_UPDATE_VERSION, "...
public static WorkflowInstanceAggregatedInfo computeAggregatedView( WorkflowInstance workflowInstance, boolean statusKnown) { if (workflowInstance == null) { // returning empty object since cannot access state of the current instance run return new WorkflowInstanceAggregatedInfo(); } Work...
@Test public void testAggregatedViewFailed() { WorkflowInstance run1 = getGenericWorkflowInstance( 1, WorkflowInstance.Status.FAILED, RunPolicy.START_FRESH_NEW_RUN, null); Workflow runtimeWorkflow = mock(Workflow.class); Map<String, StepRuntimeState> decodedOverview = new LinkedHashM...
@Nonnull public HazelcastInstance getClient() { if (getConfig().isShared()) { retain(); return proxy.get(); } else { return HazelcastClient.newHazelcastClient(clientConfig); } }
@Test public void shared_client_should_return_same_instance() { DataConnectionConfig dataConnectionConfig = sharedDataConnectionConfig(clusterName); hazelcastDataConnection = new HazelcastDataConnection(dataConnectionConfig); HazelcastInstance c1 = hazelcastDataConnection.getClient(); ...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { if(containerService.isContainer(folder)) { final S3BucketCreateService service = new S3BucketCreateService(session); service.create(folder, StringUtils.isBlank(status.getRegion())...
@Test public void testCreatePlaceholderVirtualHost() throws Exception { final S3AccessControlListFeature acl = new S3AccessControlListFeature(virtualhost); final Path test = new S3DirectoryFeature(virtualhost, new S3WriteFeature(virtualhost, acl), acl).mkdir( new Path(new Alphanumeri...
public static String getDurationStringLong(int duration) { if (duration <= 0) { return "00:00:00"; } else { int[] hms = millisecondsToHms(duration); return String.format(Locale.getDefault(), "%02d:%02d:%02d", hms[0], hms[1], hms[2]); } }
@Test public void testGetDurationStringLong() { String expected = "13:05:10"; int input = 47110000; assertEquals(expected, Converter.getDurationStringLong(input)); }
@Override public void createNetwork(Network osNet) { checkNotNull(osNet, ERR_NULL_NETWORK); checkArgument(!Strings.isNullOrEmpty(osNet.getId()), ERR_NULL_NETWORK_ID); osNetworkStore.createNetwork(osNet); OpenstackNetwork finalAugmentedNetwork = buildAugmentedNetworkFromType(osNet);...
@Test(expected = IllegalArgumentException.class) public void testCreateNetworkWithNullId() { final Network testNet = NeutronNetwork.builder().build(); target.createNetwork(testNet); }
public static Applications toApplications(Map<String, Application> applicationMap) { Applications applications = new Applications(); for (Application application : applicationMap.values()) { applications.addApplication(application); } return updateMeta(applications); }
@Test public void testToApplicationsIfNotNullReturnApplicationsFromMapOfApplication() { HashMap<String, Application> hashMap = new HashMap<>(); hashMap.put("foo", new Application("foo")); hashMap.put("bar", new Application("bar")); hashMap.put("baz", new Application("baz")); ...
@Override public void chunk(final Path directory, final AttributedList<Path> list) throws ListCanceledException { if(directory.isRoot()) { if(list.size() >= container) { // Allow another chunk until limit is reached again container += preferences.getInteger("brows...
@Test(expected = ListCanceledException.class) public void testChunkLimitFolder() throws Exception { new LimitedListProgressListener(new DisabledProgressListener()).chunk( new Path("/container", EnumSet.of(Path.Type.volume, Path.Type.directory)), new AttributedList<Path>() { ...
public ConvertedTime getConvertedTime(long duration) { Set<Seconds> keys = RULES.keySet(); for (Seconds seconds : keys) { if (duration <= seconds.getSeconds()) { return RULES.get(seconds).getConvertedTime(duration); } } return new TimeConverter.Ove...
@Test public void testShouldReportAbout1HourFor44Minutes30Seconds() throws Exception { assertEquals(TimeConverter.ABOUT_1_HOUR_AGO, timeConverter.getConvertedTime(44 * 60 + 30)); }
@Override public long getPeriodMillis() { return periodMillis; }
@Test public void testGetPeriodMillis() { long periodMillis = plugin.getPeriodMillis(); assertEquals(SECONDS.toMillis(1), periodMillis); }
public BackgroundException map(HttpResponse response) throws IOException { final S3ServiceException failure; if(null == response.getEntity()) { failure = new S3ServiceException(response.getStatusLine().getReasonPhrase()); } else { EntityUtils.updateEntity(response...
@Test public void testBadRequest() { final ServiceException f = new ServiceException("m", "<null/>"); f.setErrorMessage("m"); f.setResponseCode(400); assertTrue(new S3ExceptionMappingService().map(f) instanceof InteroperabilityException); }
public LLCSegmentName(String segmentName) { String[] parts = StringUtils.splitByWholeSeparator(segmentName, SEPARATOR); Preconditions.checkArgument(parts.length == 4, "Invalid LLC segment name: %s", segmentName); _tableName = parts[0]; _partitionGroupId = Integer.parseInt(parts[1]); _sequenceNumber ...
@Test public void testLLCSegmentName() { String tableName = "myTable"; final int partitionGroupId = 4; final int sequenceNumber = 27; final long msSinceEpoch = 1466200248000L; final String creationTime = "20160617T2150Z"; final long creationTimeInMs = 1466200200000L; final String segmentNa...
public Connection create(Connection connection) { return connectionRepository.saveAndFlush(connection); }
@Test void createConnection() { when(connectionRepositoryMock.saveAndFlush(any(Connection.class))).thenReturn(new Connection()); Connection result = connectionServiceMock.create(new Connection()); verify(connectionRepositoryMock, times(1)).saveAndFlush(any(Connection.class)); asser...
@Override public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListener listener) throws Http2Exception { if (readError) { input.skipBytes(input.readableBytes()); return; } try { do { if (readingHeaders && !...
@Test public void readHeaderFrameAndContinuationFrame() throws Http2Exception { final int streamId = 1; ByteBuf input = Unpooled.buffer(); try { Http2Headers headers = new DefaultHttp2Headers() .authority("foo") .method("get") ...
@Override public Set<String> listTopicNames() { try { return ExecutorUtil.executeWithRetries( () -> adminClient.get().listTopics().names().get(), ExecutorUtil.RetryBehaviour.ON_RETRYABLE); } catch (final Exception e) { throw new KafkaResponseGetFailedException("Failed to retrie...
@Test public void shouldListTopicNames() { // When: givenTopicExists("topicA", 1, 1); givenTopicExists("topicB", 1, 2); when(adminClient.listTopics()) .thenAnswer(listTopicResult()); // When: final Set<String> names = kafkaTopicClient.listTopicNames(); // Then: assertThat(na...
public void setRequestProtocol(String requestProtocol) { this.requestProtocol = requestProtocol; }
@Test void testSetRequestProtocol() { assertNull(basicContext.getRequestProtocol()); basicContext.setRequestProtocol(BasicContext.HTTP_PROTOCOL); assertEquals(BasicContext.HTTP_PROTOCOL, basicContext.getRequestProtocol()); basicContext.setRequestProtocol(BasicContext.GRPC_PROTOCOL); ...
@Override public Optional<NotificationDispatcherMetadata> getMetadata() { return Optional.empty(); }
@Test public void getMetadata_returns_empty() { assertThat(underTest.getMetadata()).isEmpty(); }
public void computeCpd(Component component, Collection<Block> originBlocks, Collection<Block> duplicationBlocks) { CloneIndex duplicationIndex = new PackedMemoryCloneIndex(); populateIndex(duplicationIndex, originBlocks); populateIndex(duplicationIndex, duplicationBlocks); List<CloneGroup> duplications...
@Test public void do_not_compute_more_than_one_hundred_duplications_when_too_many_duplicated_references() { Collection<Block> originBlocks = new ArrayList<>(); Collection<Block> duplicatedBlocks = new ArrayList<>(); Block.Builder blockBuilder = new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) ...
static PublicationParams getPublicationParams( final ChannelUri channelUri, final MediaDriver.Context ctx, final DriverConductor driverConductor, final boolean isIpc) { final PublicationParams params = new PublicationParams(ctx, isIpc); params.getEntityTag(channelUri...
@Test void basicParse() { final ChannelUri uri = ChannelUri.parse("aeron:udp?endpoint=localhost:1010"); final PublicationParams params = PublicationParams.getPublicationParams(uri, ctx, conductor, false); assertFalse(params.hasMaxResend); }
@SuppressWarnings("unchecked") public static <T> T[] insert(T[] buffer, int index, T... newElements) { return (T[]) insert((Object) buffer, index, newElements); }
@Test public void testInsertPrimitive() { final boolean[] booleans = new boolean[10]; final byte[] bytes = new byte[10]; final char[] chars = new char[10]; final short[] shorts = new short[10]; final int[] ints = new int[10]; final long[] longs = new long[10]; final float[] floats = new float[10]; fina...
public static void copyBody(Message source, Message target) { // Preserve the DataType if both messages are DataTypeAware if (source.hasTrait(MessageTrait.DATA_AWARE)) { target.setBody(source.getBody()); target.setPayloadForTrait(MessageTrait.DATA_AWARE, sourc...
@Test void shouldCopyBodyIfBothDataTypeAwareWithDataTypeSet() { Object body = new Object(); DataType type = new DataType("foo"); DefaultMessage m1 = new DefaultMessage((Exchange) null); m1.setBody(body, type); DefaultMessage m2 = new DefaultMessage((Exchange) null); c...
@GetMapping("/getUserPermissionByToken") public ShenyuAdminResult getUserPermissionByToken(@RequestParam(name = "token") final String token) { PermissionMenuVO permissionMenuVO = permissionService.getPermissionMenu(token); return Optional.ofNullable(permissionMenuVO) .map(item -> She...
@Test public void testGetUserPermissionByTokenNull() { when(mockPermissionService.getPermissionMenu("token")).thenReturn(null); final ShenyuAdminResult result = permissionController.getUserPermissionByToken("token"); assertThat(result.getCode(), is(CommonErrorCode.ERROR)); assertThat...
@Override public ResourceId getCurrentDirectory() { if (isDirectory()) { return this; } return fromComponents(scheme, getBucket(), key.substring(0, key.lastIndexOf('/') + 1)); }
@Test public void testGetCurrentDirectory() { // Tests s3 paths. assertEquals( S3ResourceId.fromUri("s3://my_bucket/tmp dir/"), S3ResourceId.fromUri("s3://my_bucket/tmp dir/").getCurrentDirectory()); // Tests path with unicode. assertEquals( S3ResourceId.fromUri("s3://my_bucke...
@Restricted(NoExternalUse.class) public static Icon tryGetIcon(String iconGuess) { // Jenkins Symbols don't have metadata so return null if (iconGuess == null || iconGuess.startsWith("symbol-")) { return null; } Icon iconMetadata = IconSet.icons.getIconByClassSpec(iconGu...
@Test public void tryGetIcon_shouldReturnMetadataForExactSpec() throws Exception { assertThat(Functions.tryGetIcon("icon-help icon-sm"), is(not(nullValue()))); }
@Override public ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) { return new InstrumentedScheduledExecutorService( threadPoolFactory.newScheduledThreadPool(profile, threadFactory), metricRegistry, profile.getId()); }
@Test public void testNewScheduledThreadPool() { final ScheduledExecutorService scheduledExecutorService = instrumentedThreadPoolFactory.newScheduledThreadPool(profile, threadFactory); assertThat(scheduledExecutorService, is(notNullValue())); assertThat(scheduledExecutorServ...
@Override public Health health() { final Health.Builder health = Health.unknown(); if (!jobRunrProperties.getBackgroundJobServer().isEnabled()) { health .up() .withDetail("backgroundJobServer", "disabled"); } else { final Backgr...
@Test void givenEnabledBackgroundJobServerAndBackgroundJobServerRunning_ThenHealthIsUp() { when(backgroundJobServerProperties.isEnabled()).thenReturn(true); when(backgroundJobServer.isRunning()).thenReturn(true); assertThat(jobRunrHealthIndicator.health().getStatus()).isEqualTo(Status.UP); ...
@ShellMethod(key = "compaction show", value = "Shows compaction details for a specific compaction instant") public String compactionShow( @ShellOption(value = "--instant", help = "Base path for the target hoodie table") final String compactionInstantTime, @ShellOption(value = {"--limit"}, he...
@Test public void testCompactionShow() throws IOException { // create MOR table. new TableCommand().createTable( tablePath, tableName, HoodieTableType.MERGE_ON_READ.name(), "", TimelineLayoutVersion.VERSION_1, HoodieAvroPayload.class.getName()); CompactionTestUtils.setupAndValidateCompact...
@Override public void dropPartition(String dbName, String tableName, List<String> partValues, boolean deleteData) { List<String> partitionColNames = getTable(dbName, tableName).getPartitionColumnNames(); try { metastore.dropPartition(dbName, tableName, partValues, deleteData); } ...
@Test public void testDropPartition() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); cachingHiveMetastore.dropPartition("db", "table", Lists.newArrayList("1"), false); }
@GetMapping("/status") public EmailStatusResult getEmailStatus(@RequestHeader(MijnDigidSession.MIJN_DIGID_SESSION_HEADER) String mijnDigiDsessionId){ MijnDigidSession mijnDigiDSession = retrieveMijnDigiDSession(mijnDigiDsessionId); return accountService.getEmailStatus(mijnDigiDSession.getAccountId(...
@Test public void validEmailStatusNotVerified() { EmailStatusResult result = new EmailStatusResult(); result.setStatus(Status.OK); result.setError("error"); result.setEmailStatus(EmailStatus.NOT_VERIFIED); result.setEmailAddress("address"); result.setActionNeeded(true...
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_throw_when_fails_to_parse() { properties.put(Constants.OBJECT_FACTORY_PROPERTY_NAME, "garbage"); CucumberException exception = assertThrows( CucumberException.class, () -> cucumberPropertiesParser.parse(properties).build()); assertThat(exception.getM...
@Override public UserIdentity create(GsonUser user, @Nullable String email, @Nullable List<GsonTeam> teams) { UserIdentity.Builder builder = UserIdentity.builder() .setProviderId(user.getId()) .setProviderLogin(user.getLogin()) .setName(generateName(user)) .setEmail(email); if (teams !...
@Test public void null_name_is_replaced_by_provider_login() { GsonUser gson = new GsonUser("ABCD", "octocat", null, "octocat@github.com"); UserIdentity identity = underTest.create(gson, null, null); assertThat(identity.getName()).isEqualTo("octocat"); }
@Override public final String getLocation() { return getFullLocationLocation(); }
@Test void test() throws NoSuchMethodException { Method method = AbstractGlueDefinitionTest.class.getMethod("method"); AbstractGlueDefinition definition = new AbstractGlueDefinition(method, lookup) { }; assertThat(definition.getLocation(), startsWith("io.cucumber.java.AbstractGlueD...
public BucketInfo addInsert(String partitionPath) { // for new inserts, compute buckets depending on how many records we have for each partition SmallFileAssign smallFileAssign = getSmallFileAssign(partitionPath); // first try packing this into one of the smallFiles if (smallFileAssign != null && small...
@Test public void testInsertWithSmallFiles() { SmallFile f0 = new SmallFile(); f0.location = new HoodieRecordLocation("t0", "f0"); f0.sizeBytes = 12; SmallFile f1 = new SmallFile(); f1.location = new HoodieRecordLocation("t0", "f1"); f1.sizeBytes = 122879; // no left space to append new recor...
public static HostName getControllerHostName(ApplicationInstance application, ClusterId contentClusterId) { // It happens that the master Cluster Controller is the one with the lowest index, if up. return getClusterControllerInstancesInOrder(application, contentClusterId).stream() .find...
@Test public void testGetControllerHostName() { HostName host = VespaModelUtil.getControllerHostName(application, CONTENT_CLUSTER_ID); assertEquals(controller0Host, host); }
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) { String highwayValue = way.getTag("highway"); if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service"))) return; int ...
@Test public void temporalAccess() { int edgeId = 0; ArrayEdgeIntAccess access = new ArrayEdgeIntAccess(1); ReaderWay way = new ReaderWay(1); way.setTag("highway", "primary"); way.setTag("access:conditional", "no @ (May - June)"); parser.handleWayTags(edgeId, access, ...
public static <T1,T2> double mi(Set<List<T1>> first, Set<List<T2>> second) { List<Row<T1>> firstList = new RowList<>(first); List<Row<T2>> secondList = new RowList<>(second); return mi(firstList,secondList); }
@Test public void testMi() { List<Integer> a = Arrays.asList(0, 3, 2, 3, 4, 4, 4, 1, 3, 3, 4, 3, 2, 3, 2, 4, 2, 2, 1, 4, 1, 2, 0, 4, 4, 4, 3, 3, 2, 2, 0, 4, 0, 1, 3, 0, 4, 0, 0, 4, 0, 0, 2, 2, 2, 2, 0, 3, 0, 2, 2, 3, 1, 0, 1, 0, 3, 4, 4, 4, 0, 1, 1, 3, 3, 1, 3, 4, 0, 3, 4, 1, 0, 3, 2, 2, 2, 1, 1, 2, 3, 2, 1...
public MapStoreConfig setWriteDelaySeconds(int writeDelaySeconds) { this.writeDelaySeconds = writeDelaySeconds; return this; }
@Test public void setWriteDelaySeconds() { assertEquals(DEFAULT_WRITE_DELAY_SECONDS + 1, cfgNonDefaultWriteDelaySeconds.getWriteDelaySeconds()); assertEquals(new MapStoreConfig().setWriteDelaySeconds(DEFAULT_WRITE_DELAY_SECONDS + 1), cfgNonDefaultWriteDelaySeconds); }
@SuppressWarnings("unchecked") public E get(int index) { return (E) storage.get(index); }
@Test public void testGet() { // try empty array verify(0); verify(1000); verify(-1); verify(); // try dense for (int i = 0; i < ARRAY_STORAGE_32_MAX_SPARSE_SIZE / 2; ++i) { set(i); verify(i); verify(); set(i, 1...
public CoercedExpressionResult coerce() { final Class<?> leftClass = left.getRawClass(); final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass); final Class<?> rightClass = right.getRawClass(); final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass); ...
@Test public void avoidCoercingStrings2() { final TypedExpression left = expr(THIS_PLACEHOLDER + ".getAge()", int.class); final TypedExpression right = expr("\"50\"", String.class); final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, false).coerce(); ...
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) { // Set of Visited Schemas IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>(); // Stack that contains the Schemas to process and afterVisitNonTerminal // functions. // Deque<Either<Schema, Supplier<SchemaVi...
@Test public void testVisit2() { String s2 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}" + "]}"; Assert.assertEquals("c1.\"int\"!", Schemas.visit(new Schema.Parser().parse(s2), new TestVisitor())); }
@Override public RuleConfig newRuleConfig() { return new RuleConfigImpl(); }
@Test public void addEventListeners() { TestAgendaEventListener testAgendaEventListener = new TestAgendaEventListener(); TestRuleRuntimeEventListener testRuleRuntimeEventListener = new TestRuleRuntimeEventListener(); TestRuleEventListener testRuleEventListener = new TestRuleEventListener(); ...
@Override public boolean isAction() { if (expression != null) { return expression.isAction(); } return false; }
@Test public void isAction() { when(expr.isAction()).thenReturn(true).thenReturn(false); assertTrue(test.isAction()); assertFalse(test.isAction()); verify(expr, times(2)).isAction(); verifyNoMoreInteractions(expr); }
public static ScmInfo create(ScannerReport.Changesets changesets) { requireNonNull(changesets); Changeset[] lineChangesets = new Changeset[changesets.getChangesetIndexByLineCount()]; LineIndexToChangeset lineIndexToChangeset = new LineIndexToChangeset(changesets); for (int i = 0; i < changesets.getChan...
@Test public void fail_with_ISE_when_no_changeset() { assertThatThrownBy(() -> ReportScmInfo.create(ScannerReport.Changesets.newBuilder().build())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ScmInfo cannot be empty"); }
@Override public String getPrefix() { return String.format("%s.%s", this.getClass().getPackage().getName(), "Dropbox"); }
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.dropbox.Dropbox", new DropboxProtocol().getPrefix()); }
@Override public ContentElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, ParseException, SmackParsingException { ContentElement.Builder builder = ContentElement.builder(); while (true) { XmlPullP...
@Test public void testParsing() throws XmlPullParserException, IOException, SmackParsingException, ParseException { String xml = "" + "<content xmlns='urn:xmpp:sce:0'>\n" + " <payload>\n" + " <body xmlns='jabber:client'>Have you seen that new movie?</body>...
public static Collection<java.nio.file.Path> listFilesInDirectory( final java.nio.file.Path directory, final Predicate<java.nio.file.Path> fileFilter) throws IOException { checkNotNull(directory, "directory"); checkNotNull(fileFilter, "fileFilter"); if (!Files.exists(dir...
@Test void testFollowSymbolicDirectoryLink() throws IOException { final File directory = TempDirUtils.newFolder(temporaryFolder, "a"); final File file = new File(directory, "a.jar"); assertThat(file.createNewFile()).isTrue(); final File otherDirectory = TempDirUtils.newFolder(tempor...
@Override public Processor<K, Change<V1>, K, Change<VOut>> get() { return new KTableKTableLeftJoinProcessor(valueGetterSupplier2.get()); }
@Test public void shouldLogAndMeterSkippedRecordsDueToNullLeftKey() { final StreamsBuilder builder = new StreamsBuilder(); @SuppressWarnings("unchecked") final Processor<String, Change<String>, String, Change<Object>> join = new KTableKTableLeftJoin<>( (KTableImpl<String, String...
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter, MetricsRecorder metricsRecorder, BufferSupplier bufferSupplier) { if (sourceCompressionType == Co...
@Test public void testAbsoluteOffsetAssignmentNonCompressed() { MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V0, RecordBatch.NO_TIMESTAMP, Compression.NONE); long offset = 1234567; checkOffsets(records, 0); checkOffsets( new LogValidator( ...
@SuppressWarnings("unchecked") public Output run(RunContext runContext) throws Exception { Logger logger = runContext.logger(); try (HttpClient client = this.client(runContext, this.method)) { HttpRequest<String> request = this.request(runContext); HttpResponse<String> respo...
@Test void multipart() throws Exception { File file = new File(Objects.requireNonNull(RequestTest.class.getClassLoader().getResource("application-test.yml")).toURI()); URI fileStorage = storageInterface.put( null, new URI("/" + FriendlyId.createFriendlyId()), new...
@Override public InterpreterResult interpret(String sql, InterpreterContext contextInterpreter) { logger.info("Run SQL command '{}'", sql); return executeSql(sql); }
@Test void sqlSuccess() { InterpreterResult ret = bqInterpreter.interpret(constants.getOne(), context); assertEquals(InterpreterResult.Code.SUCCESS, ret.code()); assertEquals(InterpreterResult.Type.TABLE, ret.message().get(0).getType()); }
private ArrayAccess() { }
@Test public void shouldBeOneIndexed() { // Given: final List<Integer> list = ImmutableList.of(1, 2); // When: final Integer access = ArrayAccess.arrayAccess(list, 1); // Then: assertThat(access, is(1)); }
@Override public DeleteTopicsResult deleteTopics(final TopicCollection topics, final DeleteTopicsOptions options) { if (topics instanceof TopicIdCollection) return DeleteTopicsResult.ofTopicIds(handleDeleteTopicsUsingIds(((TopicIdCollection) topics).top...
@Test public void testDeleteTopicsRetryThrottlingExceptionWhenEnabledUntilRequestTimeOut() throws Exception { long defaultApiTimeout = 60000; MockTime time = new MockTime(); try (AdminClientUnitTestEnv env = mockClientEnv(time, AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, St...
public List<String> parseToPlainTextChunks() throws IOException, SAXException, TikaException { final List<String> chunks = new ArrayList<>(); chunks.add(""); ContentHandlerDecorator handler = new ContentHandlerDecorator() { @Override public void characters(char[] ch, int ...
@Test public void testParseToPlainTextChunks() throws IOException, SAXException, TikaException { List<String> result = example.parseToPlainTextChunks(); assertEquals(3, result.size()); for (String chunk : result) { assertTrue(chunk.length() <= example.MAXIMUM_TEXT_CHUNK_SIZE, "C...
public void replay( long recordOffset, long producerId, OffsetCommitKey key, OffsetCommitValue value ) { final String groupId = key.group(); final String topic = key.topic(); final int partition = key.partition(); if (value != null) { // T...
@Test public void testReplayWithTombstoneAndPendingTransactionalOffsets() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); // Add the offsets. verifyReplay(context, "foo", "bar", 0, new OffsetAndMetadata( 0L, 100L, ...
public static int scale(final Schema schema) { requireDecimal(schema); final String scaleString = schema.parameters() .get(org.apache.kafka.connect.data.Decimal.SCALE_FIELD); if (scaleString == null) { throw new KsqlException("Invalid Decimal schema: scale parameter not found."); } tr...
@Test public void shouldExtractScaleFromDecimalSchema() { // When: final int scale = DecimalUtil.scale(DECIMAL_SCHEMA); // Then: assertThat(scale, is(1)); }
@Override public PageResult<ProductBrandDO> getBrandPage(ProductBrandPageReqVO pageReqVO) { return brandMapper.selectPage(pageReqVO); }
@Test public void testGetBrandPage() { // mock 数据 ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class, o -> { // 等会查询到 o.setName("芋道源码"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCreateTime(buildTime(2022, 2, 1)); }); brandMapper.insert...
public boolean hasCommand(String commandName) { BaseCommand command; try { command = frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName); } catch (Throwable throwable) { return false; } return command != null; }
@Test void testHasCommand() { assertTrue(commandHelper.hasCommand("greeting")); assertFalse(commandHelper.hasCommand("not-exiting")); }
@CanIgnoreReturnValue public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) { List<@Nullable Object> expected = (varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs); return containsExactlyElementsIn( expected, varargs != null && varargs.length == 1...
@Test public void iterableContainsExactlyWithDuplicatesMissingAndExtraItemsWithNewlineFailure() { expectFailureWhenTestingThat(asList("a\nb", "a\nb")).containsExactly("foo\nbar", "foo\nbar"); assertFailureKeys( "missing (2)", "#1 [2 copies]", "", "unexpected (2)", "#1 [...
@Udf(description = "Converts a TIME value into the" + " string representation of the time in the given format." + " The format pattern should be in the format expected" + " by java.time.format.DateTimeFormatter") public String formatTime( @UdfParameter( description = "TIME value.") f...
@Test public void shoudlReturnNull() { // When: final Object result = udf.formatTime(null, "HH:mm:ss.SSS"); // Then: assertNull(result); }
public String getString(@NotNull final String key, @Nullable final String defaultValue) { return System.getProperty(key, props.getProperty(key, defaultValue)); }
@Test public void testGetString() { String key = Settings.KEYS.NVD_API_DATAFEED_VALID_FOR_DAYS; String expResult = "7"; String result = getSettings().getString(key); Assert.assertTrue(result.endsWith(expResult)); }
@Override public Map<Errors, Integer> errorCounts() { HashMap<Errors, Integer> counts = new HashMap<>(); updateErrorCounts(counts, Errors.forCode(data.errorCode())); return counts; }
@Test public void testErrorCountsReturnsNoneWhenNoErrors() { GetTelemetrySubscriptionsResponseData data = new GetTelemetrySubscriptionsResponseData() .setErrorCode(Errors.NONE.code()); GetTelemetrySubscriptionsResponse response = new GetTelemetrySubscriptionsResponse(data); a...
@SuppressWarnings({"rawtypes", "unchecked"}) public static ConfigDef enrich(Plugins plugins, ConfigDef baseConfigDef, Map<String, String> props, boolean requireFullConfig) { ConfigDef newDef = new ConfigDef(baseConfigDef); new EnrichablePlugin<Transformation<?>>("Transformation", TRANSFORMS_CONFIG, ...
@Test public void testEnrichedConfigDef() { String alias = "hdt"; String prefix = ConnectorConfig.TRANSFORMS_CONFIG + "." + alias + "."; Map<String, String> props = new HashMap<>(); props.put(ConnectorConfig.TRANSFORMS_CONFIG, alias); props.put(prefix + "type", HasDuplicateCo...
public static Processor createProcessor( CamelContext camelContext, DynamicRouterConfiguration cfg, BiFunction<CamelContext, Expression, RecipientList> recipientListSupplier) { RecipientList recipientList = recipientListSupplier.apply(camelContext, RECIPIENT_LIST_EXPRESSION); set...
@Test void testCreateProcessor() { when(camelContext.getExecutorServiceManager()).thenReturn(manager); when(mockRecipientListSupplier.apply(eq(camelContext), any(Expression.class))).thenReturn(recipientList); Processor processor = DynamicRouterRecipientListHelper.createProces...
Meter.Type getMetricsType(String remaining) { String type = StringHelper.before(remaining, ":"); return type == null ? DEFAULT_METER_TYPE : MicrometerUtils.getByName(type); }
@Test public void testGetMetricsTypeNotSet() { assertThat(component.getMetricsType("no-metrics-type"), is(MicrometerComponent.DEFAULT_METER_TYPE)); }
@Override public boolean nextConfig(long timeout) { file.validateFile(); if (checkReloaded()) { log.log(FINE, () -> "User forced config reload at " + System.currentTimeMillis()); // User forced reload setConfigIfChanged(updateConfig()); ConfigState<T> ...
@Test(expected = IllegalArgumentException.class) public void require_that_bad_file_throws_exception() throws IOException { // A little trick to ensure that we can create the subscriber, but that we get an error when reading. writeConfig("intval", "23"); ConfigSubscription<SimpletypesConfig> ...
@Override public void processElement(StreamRecord<FlinkInputSplit> element) { splits.add(element.getValue()); enqueueProcessSplits(); }
@TestTemplate public void testTriggerCheckpoint() throws Exception { // Received emitted splits: split1, split2, split3, checkpoint request is triggered when reading // records from // split1. List<List<Record>> expectedRecords = generateRecordsAndCommitTxn(3); List<FlinkInputSplit> splits = gene...
public DecoderResult decode(AztecDetectorResult detectorResult) throws FormatException { ddata = detectorResult; BitMatrix matrix = detectorResult.getBits(); boolean[] rawbits = extractBits(matrix); CorrectedBitsResult correctedBits = correctBits(rawbits); byte[] rawBytes = convertBoolArrayToByteArr...
@Test public void testAztecResultECI() throws FormatException { BitMatrix matrix = BitMatrix.parse( " X X X X X X \n" + " X X X X X X X X X X X X \n" + " X X X X \n" + " X X X X X X X X X X X X X X X X X \n" + ...
public final Source source(final Source source) { return new Source() { @Override public long read(Buffer sink, long byteCount) throws IOException { boolean throwOnTimeout = false; enter(); try { long result = source.read(sink, byteCount); throwOnTimeout = true; ...
@Test public void wrappedSourceTimesOut() throws Exception { Source source = new ForwardingSource(new Buffer()) { @Override public long read(Buffer sink, long byteCount) throws IOException { try { Thread.sleep(500); return -1; } catch (InterruptedException e) { th...
@Bean public PluginDataHandler sentinelRuleHandle() { return new SentinelRuleHandle(); }
@Test public void testSentinelRuleHandle() { applicationContextRunner.run(context -> { PluginDataHandler handler = context.getBean("sentinelRuleHandle", PluginDataHandler.class); assertNotNull(handler); } ); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldFetchWithNoBounds() { // When: table.get(A_KEY, PARTITION, Range.all(), Range.all()); // Then: verify(cacheBypassFetcher).fetch( eq(tableStore), any(), eq(Instant.ofEpochMilli(0)), eq(Instant.ofEpochMilli(Long.MAX_VALUE)) ); }
public static int hash(Object o) { if (o == null) { return 0; } if (o instanceof Long) { return hashLong((Long) o); } if (o instanceof Integer) { return hashLong((Integer) o); } if (o instanceof Double) { return hash...
@Test public void testHash() throws Exception { final long actualHash = MurmurHash.hash("hashthis"); final long expectedHash = -1974946086L; assertEquals("MurmurHash.hash(String) returns wrong hash value", expectedHash, actualHash); }
public final void isNotNaN() { if (actual == null) { failWithActual(simpleFact("expected a double other than NaN")); } else { isNotEqualTo(NaN); } }
@Test public void isNotNaN() { assertThat(1.23).isNotNaN(); assertThat(Double.MAX_VALUE).isNotNaN(); assertThat(-1.0 * Double.MIN_VALUE).isNotNaN(); assertThat(Double.POSITIVE_INFINITY).isNotNaN(); assertThat(Double.NEGATIVE_INFINITY).isNotNaN(); }
public String getStructuralGuid() { return this.structuralGuid; }
@Test public void queriesWithSameAnonFormShouldGetSameStructurallySimilarId() { // Given: final String query1 = "CREATE STREAM my_stream (profileId VARCHAR, latitude DOUBLE) " + "WITH (kafka_topic='locations', value_format='json', partitions=1);"; final String query2 = "CREATE STREAM my_stream (us...
@Override public boolean match(Message msg, StreamRule rule) { if (msg.getField(rule.getField()) == null) return rule.getInverted(); try { final Pattern pattern = patternCache.get(rule.getValue()); final CharSequence charSequence = new InterruptibleCharSequence(m...
@Test public void testInvertedNullFieldShouldMatch() throws Exception { final String fieldName = "nullfield"; final StreamRule rule = getSampleRule(); rule.setField(fieldName); rule.setValue("^foo"); rule.setInverted(true); final Message msg = getSampleMessage(); ...
@Override public int hashCode() { int result = storageRef.get().hashCode(); result = 31 * result + (name != null ? name.hashCode() : 0); return result; }
@Test public void testHashCode() { assertEquals(recordStore.hashCode(), recordStore.hashCode()); assertEquals(recordStoreSameAttributes.hashCode(), recordStore.hashCode()); assumeDifferentHashCodes(); assertNotEquals(recordStoreOtherStorage.hashCode(), recordStore.hashCode()); ...
@Override public void processElement(StreamRecord<T> element) throws Exception { writer.write(element.getValue()); }
@TestTemplate public void testTableWithoutSnapshot() throws Exception { try (OneInputStreamOperatorTestHarness<RowData, WriteResult> testHarness = createIcebergStreamWriter()) { assertThat(testHarness.extractOutputValues()).isEmpty(); } // Even if we closed the iceberg stream writer, there's...
@Override public UniquenessLevel getIndexUniquenessLevel() { return UniquenessLevel.SCHEMA_LEVEL; }
@Test void assertGetIndexUniquenessLevel() { assertThat(uniquenessLevelProvider.getIndexUniquenessLevel(), is(UniquenessLevel.SCHEMA_LEVEL)); }
public static ReadOnlyHttp2Headers trailers(boolean validateHeaders, AsciiString... otherHeaders) { return new ReadOnlyHttp2Headers(validateHeaders, EMPTY_ASCII_STRINGS, otherHeaders); }
@Test public void nullHeaderNameNotChecked() { ReadOnlyHttp2Headers.trailers(false, null, null); }
@Override public PermissionOverwrite run(final Session<?> session) throws BackgroundException { final UnixPermission feature = session.getFeature(UnixPermission.class); if(log.isDebugEnabled()) { log.debug(String.format("Run with feature %s", feature)); } final List<Permi...
@Test public void testRun() throws Exception { final ReadPermissionWorker worker = new ReadPermissionWorker( Arrays.asList( new Path("/a", EnumSet.of(Path.Type.file), new TestPermissionAttributes(Permission.Action.all, Permission.Action.all, Permission.Action.none)), ...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public ClusterInfo get() { return getClusterInfo(); }
@Test public void testClusterSchedulerFifoSlash() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("cluster") .path("scheduler/").accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(MediaType.APPLI...
@Override public void resolve(ConcurrentJobModificationException e) { final List<Job> concurrentUpdatedJobs = e.getConcurrentUpdatedJobs(); final List<ConcurrentJobModificationResolveResult> failedToResolve = concurrentUpdatedJobs .stream() .map(this::resolve) ...
@Test void concurrentStateChangeForJobThatIsPerformedOnOtherBackgroundJobServerIsAllowed() { final Job jobInProgress = aJobInProgress().build(); Job localJob = aCopyOf(jobInProgress).withVersion(3).build(); Job storageProviderJob = aCopyOf(jobInProgress).withVersion(6).withFailedState().with...
@Override public List<Intent> compile(SinglePointToMultiPointIntent intent, List<Intent> installable) { Set<Link> links = new HashSet<>(); final boolean allowMissingPaths = intentAllowsPartialFailure(intent); boolean hasPaths = false; boolean missingS...
@Test public void testSameDeviceCompilation() { FilteredConnectPoint ingress = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)); Set<FilteredConnectPoint> egress = Sets.newHashSet(new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_2)), ...
@GetMapping("/logs/dataInfluences/field") @PreAuthorize(value = "@apolloAuditLogQueryApiPreAuthorizer.hasQueryPermission()") public List<ApolloAuditLogDataInfluenceDTO> findDataInfluencesByField( @RequestParam String entityName, @RequestParam String entityId, @RequestParam String fieldName, int page, in...
@Test public void testFindDataInfluencesByField() throws Exception { final String entityName = "query-entity-name"; final String entityId = "query-entity-id"; final String fieldName = "query-field-name"; { List<ApolloAuditLogDataInfluenceDTO> mockDataInfluenceDTOList = MockBeanFactory.mockDataIn...
@Override @SuppressWarnings("checkstyle:magicnumber") public void process(int ordinal, @Nonnull Inbox inbox) { try { switch (ordinal) { case 0: process0(inbox); break; case 1: process1(inbox); ...
@Test public void when_processInbox1_then_tryProcess1Called() { // When tryProcessP.process(ORDINAL_1, inbox); // Then tryProcessP.validateReceptionOfItem(ORDINAL_1, MOCK_ITEM); }
public static JobId toJobID(String jid) { return TypeConverter.toYarn(JobID.forName(jid)); }
@Test @Timeout(120000) public void testJobIDShort() { assertThrows(IllegalArgumentException.class, () -> { MRApps.toJobID("job_0_0_0"); }); }
public ServiceListResponse checkConvergenceForAllServices(Application application, Duration timeoutPerService) { return checkConvergence(application, timeoutPerService, new HostsToCheck(Set.of())); }
@Test public void service_list_convergence() { { wireMock.stubFor(get(urlEqualTo("/state/v1/config")).willReturn(okJson("{\"config\":{\"generation\":3}}"))); ServiceListResponse response = checker.checkConvergenceForAllServices(application, clientTimeout); assertEquals(3...
public static <V> DeferredValue<V> withValue(V value) { if (value == null) { return NULL_VALUE; } DeferredValue<V> deferredValue = new DeferredValue<>(); deferredValue.value = value; deferredValue.valueExists = true; return deferredValue; }
@Test public void testEquals_WithValue() { DeferredValue<String> v1 = withValue(expected); DeferredValue<String> v2 = withValue(expected); assertEquals(v1, v2); }
@Override public void failover(NamedNode master) { connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName()); }
@Test public void testFailover() throws InterruptedException { Collection<RedisServer> masters = connection.masters(); connection.failover(masters.iterator().next()); Thread.sleep(10000); RedisServer newMaster = connection.masters().iterator().next(); assert...
@Override // Exposes internal mutable reference by design - Spotbugs is right to warn that this is dangerous public synchronized byte[] toByteArray() { // Note: count == buf.length is not a correct criteria to "return buf;", because the internal // buf may be reused after reset(). if (!isFallback && cou...
@Test public void testWriteSingleArrayFast() throws IOException { writeToBothFast(TEST_DATA); assertStreamContentsEquals(stream, exposedStream); assertSame(TEST_DATA, exposedStream.toByteArray()); }
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testPkcs1AesEncryptedRsaWrongPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_aes_encrypted.key") ...
@Override public boolean isHostnameConfigurable() { return true; }
@Test public void testConfigurable() { assertTrue(new SwiftProtocol().isHostnameConfigurable()); assertTrue(new SwiftProtocol().isPortConfigurable()); }
static void cleanStackTrace(Throwable throwable) { new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet()); }
@Test public void allFramesBelowJUnitStatementCleaned() { Throwable throwable = createThrowableWithStackTrace( "com.google.common.truth.StringSubject", "com.google.example.SomeTest", SomeStatement.class.getName(), "com.google.example.SomeClass"); StackT...
@Override public TenantPackageDO validTenantPackage(Long id) { TenantPackageDO tenantPackage = tenantPackageMapper.selectById(id); if (tenantPackage == null) { throw exception(TENANT_PACKAGE_NOT_EXISTS); } if (tenantPackage.getStatus().equals(CommonStatusEnum.DISABLE.getS...
@Test public void testValidTenantPackage_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> tenantPackageService.validTenantPackage(id), TENANT_PACKAGE_NOT_EXISTS); }