focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void rebuild() { rules.removeIf(YamlGlobalRuleConfiguration.class::isInstance); if (null != authority) { rules.add(authority); } if (null != sqlParser) { rules.add(sqlParser); } if (null != transaction) { rules.add(transaction); ...
@Test void assertRebuild() { YamlJDBCConfiguration actual = new YamlJDBCConfiguration(); YamlAuthorityRuleConfiguration authorityRuleConfig = new YamlAuthorityRuleConfiguration(); actual.setAuthority(authorityRuleConfig); YamlSQLParserRuleConfiguration sqlParserRuleConfig = new YamlS...
@Udf public Long round(@UdfParameter final long val) { return val; }
@Test public void shouldRoundSimpleBigDecimalNegative() { assertThat(udf.round(new BigDecimal("-1.23")), is(new BigDecimal("-1"))); assertThat(udf.round(new BigDecimal("-1.0")), is(new BigDecimal("-1"))); assertThat(udf.round(new BigDecimal("-1.5")), is(new BigDecimal("-1"))); assertThat(udf.round(new...
protected boolean inList(String includeMethods, String excludeMethods, String methodName) { //判断是否在白名单中 if (!StringUtils.ALL.equals(includeMethods)) { if (!inMethodConfigs(includeMethods, methodName)) { return false; } } //判断是否在黑白单中 if (inM...
@Test public void notInListTest() { ProviderConfig providerConfig = new ProviderConfig(); DefaultProviderBootstrap defaultProviderBootstra = new DefaultProviderBootstrap(providerConfig); boolean result = defaultProviderBootstra.inList("hello1", "hello2", "hello3"); Assert.assertTrue...
@Override public void incrementWindowSize(Http2Stream stream, int delta) throws Http2Exception { assert ctx == null || ctx.executor().inEventLoop(); monitor.incrementWindowSize(state(stream), delta); }
@Test public void windowUpdateShouldChangeStreamWindow() throws Http2Exception { incrementWindowSize(STREAM_A, 100); assertEquals(DEFAULT_WINDOW_SIZE, window(CONNECTION_STREAM_ID)); assertEquals(DEFAULT_WINDOW_SIZE + 100, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(ST...
@Udf public String rpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (paddi...
@Test public void shouldPadEmptyInputString() { final String result = udf.rpad("", 4, "foo"); assertThat(result, is("foof")); }
public String kafkaClusterId() { if (kafkaClusterId == null) { kafkaClusterId = lookupKafkaClusterId(this); } return kafkaClusterId; }
@Test public void testKafkaClusterId() { Map<String, String> props = baseProps(); WorkerConfig config = new WorkerConfig(WorkerConfig.baseConfigDef(), props); assertEquals(CLUSTER_ID, config.kafkaClusterId()); workerConfigMockedStatic.verify(() -> WorkerConfig.lookupKafkaClusterId(an...
@Override public Instant currentProcessingTime() { return processingTimeClock.now(); }
@Test public void getProcessingTimeIsClockNow() { assertThat(internals.currentProcessingTime(), equalTo(clock.now())); Instant oldProcessingTime = internals.currentProcessingTime(); clock.advance(Duration.standardHours(12)); assertThat(internals.currentProcessingTime(), equalTo(clock.now())); as...
public String getThumbnailContent() { return Arrays.stream(content.split(LINE_BREAK)) .limit(THUMBNAIL_LINE_HEIGHT) .collect(Collectors.joining(LINE_BREAK)); }
@Test @DisplayName("성공: 썸네일(5줄) 추출 잘 되는지 확인") void getThumbnailContent() { // given Member member = MemberFixture.getFirstMember(); Category category = CategoryFixture.getFirstCategory(); Template template = new Template(member, "title", "description", category); SourceCo...
@Override public int sendSms(String numberTo, String message) throws SmsException { try { checkSmppSession(); SubmitSM request = new SubmitSM(); if (StringUtils.isNotEmpty(config.getServiceType())) { request.setServiceType(config.getServiceType()); ...
@Test public void testSendSms() throws Exception { when(smppSession.isOpened()).thenReturn(true); when(smppSession.submit(any())).thenReturn(new SubmitSMResp()); setDefaultSmppConfig(); String number = "123545"; String message = "message"; smppSmsSender.sendSms(numbe...
public String getArgs() { return args; }
@Test @DirtiesContext public void testCreateEndpointWithArgs2() throws Exception { String args = "arg1 \"arg2 \" arg3"; ExecEndpoint e = createExecEndpoint("exec:test?args=" + UnsafeUriCharactersEncoder.encode(args)); assertEquals(args, e.getArgs()); }
@Override protected String getKeyName() { return RateLimitEnum.LEAKY_BUCKET.getKeyName(); }
@Test public void getKeyNameTest() { assertThat("request_leaky_rate_limiter", is(leakyBucketRateLimiterAlgorithm.getKeyName())); }
protected void setDone() { done = true; }
@Test public void testEmpty() throws Exception { final TestSubscriber<String> testSubscriber = new TestSubscriber<>(); final TestPublisher testPublisher = new TestPublisher() { @Override TestPollingSubscription createSubscription( final Subscriber<String> subscriber ) { ret...
public static void sort(short[] array, ShortComparator comparator) { sort(array, 0, array.length, comparator); }
@Test void sorting_random_arrays_should_produce_identical_result_as_java_sort() { Random r = new Random(4234); for (int i = 0; i < 10000; i++) { short[] original = makeRandomArray(r); short[] javaSorted = Arrays.copyOf(original, original.length); short[] customSor...
static <S> FieldProbe createFieldProbe(Field field, Probe probe, SourceMetadata sourceMetadata) { ProbeType type = getType(field.getType()); if (type == null) { throw new IllegalArgumentException(format("@Probe field '%s' is of an unhandled type", field)); } if (type.getMaps...
@Test(expected = IllegalArgumentException.class) public void whenUnknownType() throws NoSuchFieldException { UnknownFieldType unknownFieldType = new UnknownFieldType(); Field field = unknownFieldType.getClass().getDeclaredField("field"); Probe probe = field.getAnnotation(Probe.class); ...
public static URI parse(String gluePath) { requireNonNull(gluePath, "gluePath may not be null"); if (gluePath.isEmpty()) { return rootPackageUri(); } // Legacy from the Cucumber Eclipse plugin // Older versions of Cucumber allowed it. if (CLASSPATH_SCHEME_PRE...
@Test void can_parse_classpath_form() { URI uri = GluePath.parse("classpath:com/example/app"); assertAll( () -> assertThat(uri.getScheme(), is("classpath")), () -> assertThat(uri.getSchemeSpecificPart(), is("com/example/app"))); }
@Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } if (namedCallbacks.containsKey(name)) { namedCallbacks.remove...
@Test public void testUnregisterSource() { MetricsSystem ms = new MetricsSystemImpl(); TestSource ts1 = new TestSource("ts1"); TestSource ts2 = new TestSource("ts2"); ms.register("ts1", "", ts1); ms.register("ts2", "", ts2); MetricsSource s1 = ms.getSource("ts1"); assertNotNull(s1); // s...
@Override public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext) { doEvaluateDisruptContext(request, requestContext); return _client.sendRequest(request, requestContext); }
@Test public void testSendRequest12() { when(_controller.getDisruptContext(any(String.class))).thenReturn(_disrupt); _client.sendRequest(_multiplexed, _multiplexedCallback); verify(_underlying, times(1)).sendRequest(eq(_multiplexed), any(RequestContext.class), eq(_multiplexedCallback)); }
public void retrieveDocuments() throws DocumentRetrieverException { boolean first = true; String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster); MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route); doc...
@Test void testEmptyClusterList() throws DocumentRetrieverException { Throwable exception = assertThrows(DocumentRetrieverException.class, () -> { ClientParameters params = createParameters() .setCluster("invalidclustername") .build(); Docume...
@VisibleForTesting String[] findClassNames(AbstractConfiguration config) { // Find individually-specified filter classes. String[] filterClassNamesStrArray = config.getStringArray("zuul.filters.classes"); Stream<String> classNameStream = Arrays.stream(filterClassNamesStrArra...
@Test void testMultiPackages() { Class<?> expectedClass1 = TestZuulFilter.class; Class<?> expectedClass2 = TestZuulFilter2.class; Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[0]); Mockito.when(configuration.getStringArray("zuul.filters.pac...
@Override public String toString() { return parameterValue; }
@Test void assertToString() { assertThat(new PostgreSQLTypeUnspecifiedSQLParameter("2020-08-23 15:57:03+08").toString(), is("2020-08-23 15:57:03+08")); }
public static boolean stop(final ThreadId id) { id.setError(RaftError.ESTOP.getNumber()); return true; }
@Test public void testStop() { final Replicator r = getReplicator(); this.id.unlock(); assertNotNull(r.getHeartbeatTimer()); assertNotNull(r.getRpcInFly()); Replicator.stop(this.id); assertNull(r.id); assertNull(r.getHeartbeatTimer()); assertNull(r.get...
public static String name(Class<?> clazz, String... parts) { return name(clazz.getSimpleName(), parts); }
@Test void name() { assertEquals("chat.MetricsUtilTest.metric", MetricsUtil.name(MetricsUtilTest.class, "metric")); assertEquals("chat.MetricsUtilTest.namespace.metric", MetricsUtil.name(MetricsUtilTest.class, "namespace", "metric")); }
public static ILogger getLogger(@Nonnull Class<?> clazz) { checkNotNull(clazz, "class must not be null"); return getLoggerInternal(clazz.getName()); }
@Test public void getLogger_whenInvalidConfiguration_thenCreateStandardLogger() { isolatedLoggingRule.setLoggingType("invalid"); assertInstanceOf(StandardLoggerFactory.StandardLogger.class, Logger.getLogger(getClass())); }
Map<String, DocumentField> readFields(String[] externalNames, String dataConnectionName, Map<String, String> options, boolean stream) { String collectionName = externalNames.length == 2 ...
@Test public void testResolvesFieldsViaSample() { try (MongoClient client = MongoClients.create(mongoContainer.getConnectionString())) { String databaseName = "testDatabase"; String collectionName = "people_2"; MongoDatabase testDatabase = client.getDatabase(databaseName)...
@VisibleForTesting static boolean isCompressed(String contentEncoding) { return contentEncoding.contains(HttpHeaderValues.GZIP.toString()) || contentEncoding.contains(HttpHeaderValues.DEFLATE.toString()) || contentEncoding.contains(HttpHeaderValues.BR.toString()) ...
@Test void detectsNonGzip() { assertFalse(HttpUtils.isCompressed("identity")); }
public URL getInterNodeListener( final Function<URL, Integer> portResolver ) { return getInterNodeListener(portResolver, LOGGER); }
@Test public void shouldResolveInterNodeListenerToFirstListenerWithAutoPortAssignmentAndTrailingSlash() { // Given: final URL autoPort = url("https://example.com:0/"); when(portResolver.apply(any())).thenReturn(2222); final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>buil...
public PlanNodeStatsEstimate addStatsAndSumDistinctValues(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right) { return addStats(left, right, RangeAdditionStrategy.ADD_AND_SUM_DISTINCT); }
@Test public void testAddRowCount() { PlanNodeStatsEstimate unknownStats = statistics(NaN, NaN, NaN, NaN, StatisticRange.empty()); PlanNodeStatsEstimate first = statistics(10, NaN, NaN, NaN, StatisticRange.empty()); PlanNodeStatsEstimate second = statistics(20, NaN, NaN, NaN, StatisticRa...
@Override public ZonedDateTime createdAt() { return ZonedDateTime.parse("2017-01-10T15:01:00Z"); }
@Test public void createdAt() throws Exception { assertThat(migration.createdAt()).isEqualTo(ZonedDateTime.parse("2017-01-10T15:01:00Z")); }
public static Finder filteredFinder(String query, String... excludeQueries) { var finder = Finder.contains(query); for (String q : excludeQueries) { finder = finder.not(Finder.contains(q)); } return finder; }
@Test void filteredFinderTest() { var res = filteredFinder(" was ", "many", "child").find(text()); assertEquals(1, res.size()); assertEquals("But we loved with a love that was more than love-", res.get(0)); }
public SendResult sendMessage( final String addr, final String brokerName, final Message msg, final SendMessageRequestHeader requestHeader, final long timeoutMillis, final CommunicationMode communicationMode, final SendMessageContext context, final Default...
@Test public void testSendMessageSync_WithException() throws InterruptedException, RemotingException { doAnswer(mock -> { RemotingCommand request = mock.getArgument(1); RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class); resp...
@Nullable public static TNetworkAddress getHost(long nodeId, List<TScanRangeLocation> locations, ImmutableMap<Long, ComputeNode> computeNodes, Reference<Long> nodeIdRef) { if (locat...
@Test public void testGetHostWithBackendIdInSharedDataMode() { // locations List<TScanRangeLocation> locations = new ArrayList<TScanRangeLocation>(); TScanRangeLocation locationA = new TScanRangeLocation(); locationA.setBackend_id(0); locations.add(locationA); // bac...
public TesseractOCRConfig getDefaultConfig() { return defaultConfig; }
@Test public void testArbitraryParams() throws Exception { try (InputStream is = getResourceAsStream( "/test-configs/tika-config-tesseract-arbitrary.xml")) { TikaConfig config = new TikaConfig(is); Parser p = config.getParser(); Parser tesseractOCRParser =...
static boolean firstIsCapitalized(String string) { if (string.isEmpty()) { return false; } return Character.isUpperCase(string.charAt(0)); }
@Test public void testFirstIsCapitalized() { assertFalse(MessageGenerator.firstIsCapitalized("")); assertTrue(MessageGenerator.firstIsCapitalized("FORTRAN")); assertFalse(MessageGenerator.firstIsCapitalized("java")); }
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public AppInfo get() { return getAppInfo(); }
@Test public void testInfoSlash() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("mapreduce") .path("info/").accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + "; " +...
@Override public CRMaterial deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN); }
@Test public void shouldDeserializePackageMaterialType() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("type", "package"); materialTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext); verify(jsonDeserializationContext).deserialize(jsonObject, C...
@Override public RouteContext route(final RouteContext routeContext, final BroadcastRule broadcastRule) { RouteMapper dataSourceMapper = getDataSourceRouteMapper(broadcastRule.getDataSourceNames()); routeContext.getRouteUnits().add(new RouteUnit(dataSourceMapper, createTableRouteMappers())); ...
@Test void assertRouteWithCreateViewStatementContext() { CreateViewStatementContext sqlStatementContext = mock(CreateViewStatementContext.class); Collection<String> logicTables = Collections.singleton("t_address"); ConnectionContext connectionContext = mock(ConnectionContext.class); ...
@Override public void execute(final List<String> args, final PrintWriter terminal) { CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP); if (args.isEmpty()) { terminal.println(restClient.getServerAddress()); return; } else { final String serverAddress = args.get(0); restClient.setS...
@Test public void shouldReportErrorIfFailedToGetRemoteKsqlServerInfo() { // Given: reset(restClient); givenServerAddressHandling(); when(restClient.getServerInfo()).thenThrow(genericConnectionIssue()); // When: command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal); // Then: ...
public static Tag<HttpRequest> requestHeader(String headerName) { return requestHeader(headerName, headerName); }
@Test void requestHeader() { when(request.header("User-Agent")).thenReturn("Mozilla/5.0"); HttpTags.requestHeader("User-Agent").tag(request, span); verify(span).tag("User-Agent", "Mozilla/5.0"); }
public static ChannelFuture sendUnsupportedVersionResponse(Channel channel) { return sendUnsupportedVersionResponse(channel, channel.newPromise()); }
@Test public void testUnsupportedVersion() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(); WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ch); ch.runPendingTasks(); Object msg = ch.readOutbound(); if (!(msg instanceof FullHttpResponse)) { ...
@Override public V getOrDefault(Object key, V defaultValue) { if (key instanceof String) { return Map.super.getOrDefault(((String) key).toLowerCase(), defaultValue); } return defaultValue; }
@Test void getOrDefault() { Assertions.assertEquals("Value", lowerCaseLinkHashMap.getOrDefault("Key", "abc")); Assertions.assertEquals("Value", lowerCaseLinkHashMap.getOrDefault("key", "abc")); Assertions.assertEquals("abc", lowerCaseLinkHashMap.getOrDefault("default", "abc")); }
@Override public Map<String, Object> getAttributes(boolean addSecureFields) { Map<String, Object> materialMap = new HashMap<>(); materialMap.put("type", "package"); materialMap.put("plugin-id", getPluginId()); Map<String, String> repositoryConfigurationMap = packageDefinition.getRepo...
@Test void shouldGetAttributesWithoutSecureFields() { PackageMaterial material = createPackageMaterialWithSecureConfiguration(); Map<String, Object> attributes = material.getAttributes(false); assertThat(attributes.get("type")).isEqualTo("package"); assertThat(attributes.get("plugin...
public void addComplexProperty(String name, Object complexProperty) { Method adderMethod = aggregationAssessor.findAdderMethod(name); // first let us use the addXXX method if (adderMethod != null) { Class<?>[] paramTypes = adderMethod.getParameterTypes(); if (!isSanityChe...
@Test public void testComplexCollection() { Window w1 = new Window(); w1.handle = 10; Window w2 = new Window(); w2.handle = 20; setter.addComplexProperty("window", w1); setter.addComplexProperty("window", w2); assertEquals(2, house.windowList.size()); ...
public boolean isUserAllowed(UserGroupInformation ugi) { return isUserInList(ugi); }
@Test public void testUseRealUserAclsForProxiedUser() { String realUser = "realUser"; AccessControlList acl = new AccessControlList(realUser); UserGroupInformation realUserUgi = UserGroupInformation.createRemoteUser(realUser); UserGroupInformation user1 = UserGroupInformation.createPro...
public ConcurrentLongHashMap<CompletableFuture<Producer>> getProducers() { return producers; }
@Test(timeOut = 30000) public void testProducerFailureOnEncryptionRequiredOnBroker() throws Exception { // (a) Set encryption-required at broker level pulsar.getConfig().setEncryptionRequireOnProducer(true); resetChannel(); setChannelConnected(); // (b) Set encryption_requir...
@Override public double mean() { return r * (1 - p) / p; }
@Test public void testMean() { System.out.println("mean"); NegativeBinomialDistribution instance = new NegativeBinomialDistribution(3, 0.3); instance.rand(); assertEquals(7, instance.mean(), 1E-7); }
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComStmtPreparePacket() { when(payload.readStringEOF()).thenReturn(""); assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_STMT_PREPARE, payload, connectionSession), instanceOf(MySQLComStmtPreparePacket.class)); }
static void cleanStackTrace(Throwable throwable) { new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet()); }
@Test public void causingThrowablesAreAlsoCleaned() { Throwable cause2 = createThrowableWithStackTrace("com.example.Foo", "org.junit.FilterMe"); Throwable cause1 = createThrowableWithStackTrace(cause2, "com.example.Bar", "org.junit.FilterMe"); Throwable rootThrowable = createThrowableWithS...
@Override public DictTypeDO getDictType(Long id) { return dictTypeMapper.selectById(id); }
@Test public void testGetDictType_id() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType); // 准备参数 Long id = dbDictType.getId(); // 调用 DictTypeDO dictType = dictTypeService.getDictType(id); // 断言 assertN...
public static SchemaAnnotationProcessResult process(List<SchemaAnnotationHandler> handlers, DataSchema dataSchema, AnnotationProcessOption options) { return process(handlers, dataSchema, options, true); }
@Test public void testHandlerResolveException() throws Exception { String failureMessage = "Intentional failure"; SchemaAnnotationHandler testHandler = new SchemaAnnotationHandler() { @Override public ResolutionResult resolve(List<Pair<String, Object>> propertiesOverrides, ...
CompletableFuture<Void> create(List<TopicInfo> topicInfos) { return CompletableFuture.runAsync(() -> createBlocking(topicInfos)); }
@Test void created() { KafkaFuture<Void> future = KafkaFuture.completedFuture(null); when(createTopicsResult.values()).thenReturn(singletonMap(topic, future)); topicCreator.create(singletonList(topicInfo)).join(); verify(admin).createTopics(captor.capture()); List<List<Ne...
@Override public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager) { ImmutableList.Builder<ScalarFunctionImplementationChoice> implementationChoices = ImmutableList.builder(); for (PolymorphicScalarFunctionCho...
@Test public void testSetsHiddenToTrueForOperators() { Signature signature = SignatureBuilder.builder() .operatorType(ADD) .kind(SCALAR) .returnType(parseTypeSignature("varchar(x)", ImmutableSet.of("x"))) .argumentTypes(parseTypeSignature("...
@Override public BranchRollbackRequestProto convert2Proto(BranchRollbackRequest branchRollbackRequest) { final short typeCode = branchRollbackRequest.getTypeCode(); final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType( MessageTypeProto.forNumber(...
@Test public void convert2Proto() { BranchRollbackRequest branchRegisterRequest = new BranchRollbackRequest(); branchRegisterRequest.setApplicationData("data"); branchRegisterRequest.setBranchType(BranchType.AT); branchRegisterRequest.setResourceId("resourceId"); branchRegis...
@PublicEvolving public static CongestionControlRateLimitingStrategyBuilder builder() { return new CongestionControlRateLimitingStrategyBuilder(); }
@Test void testInvalidAimdStrategy() { assertThatExceptionOfType(NullPointerException.class) .isThrownBy( () -> CongestionControlRateLimitingStrategy.builder() .setMaxInFlightRequests(10) ...
static GlobalPhaseSetup maybeMakeSetup(RankProfilesConfig.Rankprofile rp, RankProfilesEvaluator modelEvaluator) { var model = modelEvaluator.modelForRankProfile(rp.name()); Map<String, RankProfilesConfig.Rankprofile.Normalizer> availableNormalizers = new HashMap<>(); for (var n : rp.normalizer()...
@Test void queryFeaturesWithDefaults() { RankProfilesConfig rpCfg = readConfig("qf_defaults"); assertEquals(1, rpCfg.rankprofile().size()); RankProfilesEvaluator rpEvaluator = createEvaluator(rpCfg); var setup = GlobalPhaseSetup.maybeMakeSetup(rpCfg.rankprofile().get(0), rpEvaluator); ...
@Override public AppState getAppState(HttpServletRequest hsr, String appId) throws AuthorizationException { try { DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); if (interceptor != null) { return interceptor.getAppState(hsr, appId); } } catch (...
@Test public void testGetApplicationStateNotExists() throws IOException { ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); AppState response = interceptor.getAppState(null, appId.toString()); Assert.assertNull(response); }
@Override public void execute(List<RegisteredMigrationStep> steps, MigrationStatusListener listener) { Profiler globalProfiler = Profiler.create(LOGGER); globalProfiler.startInfo(GLOBAL_START_MESSAGE, databaseMigrationState.getTotalMigrations()); boolean allStepsExecuted = false; try { for (Regi...
@Test void execute_does_not_fail_when_stream_is_empty_and_log_start_stop_INFO() { underTest.execute(Collections.emptyList(), migrationStatusListener); verifyNoInteractions(migrationStatusListener); assertThat(logTester.logs()).hasSize(2); assertLogLevel(Level.INFO, "Executing 5 DB migrations...", "Ex...
@CheckForNull public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) { if (sourceLine == null) { return null; } DecorationDataHolder decorationDataHolder = new DecorationDataHolder(); if (StringUtils.isNotBlank(highlighting)) ...
@Test public void should_decorate_single_line() { String sourceLine = "package org.polop;"; String highlighting = "0,7,k"; String symbols = "8,17,42"; assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo( "<span class=\"k\">package</span> <span class=...
protected static boolean startMarketActivity( @NonNull Context context, @NonNull String marketKeyword) { try { Intent search = new Intent(Intent.ACTION_VIEW); Uri uri = new Uri.Builder() .scheme("market") .authority("search") .appendQueryParamete...
@Test public void testUtilityStart() { Application context = ApplicationProvider.getApplicationContext(); Application spy = Mockito.spy(context); Mockito.doThrow(new RuntimeException()).when(spy).startActivity(Mockito.any()); Assert.assertFalse(AddOnStoreSearchController.startMarketActivity(spy, "play...
@Override public E next(E reuse) throws IOException { /* There are three ways to handle object reuse: * 1) reuse and return the given object * 2) ignore the given object and return a new object * 3) exchange the given object for an existing object * * The first o...
@Test void testInvalidMerge() throws Exception { // iterators List<MutableObjectIterator<Tuple2<Integer, String>>> iterators = new ArrayList<>(); iterators.add( newIterator(new int[] {1, 2, 17, 23, 23}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( ...
public static Result calcPaths(List<Snap> snaps, FlexiblePathCalculator pathCalculator) { RoundTripCalculator roundTripCalculator = new RoundTripCalculator(pathCalculator); Result result = new Result(snaps.size() - 1); Snap start = snaps.get(0); for (int snapIndex = 1; snapIndex < snaps....
@Test public void testCalcRoundTrip() { BaseGraph g = createTestGraph(); LocationIndex locationIndex = new LocationIndexTree(g, new RAMDirectory()).prepareIndex(); Snap snap4 = locationIndex.findClosest(0.05, 0.25, EdgeFilter.ALL_EDGES); assertEquals(4, snap4.getClosestNode()); ...
public static StatementExecutorResponse execute( final ConfiguredStatement<ListQueries> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final RemoteHostExecutor remoteHostExecutor = RemoteHostExecuto...
@Test public void shouldScatterGatherAndMergeShowQueriesExtended() { // Given when(sessionProperties.getInternalRequest()).thenReturn(false); final ConfiguredStatement<?> showQueries = engine.configure("SHOW QUERIES EXTENDED;"); final StreamsTaskMetadata localTaskMetadata = mock(StreamsTaskMetada...
List<List<RingRange>> generateSplits(long totalSplitCount, List<BigInteger> ringTokens) { int tokenRangeCount = ringTokens.size(); List<RingRange> splits = new ArrayList<>(); for (int i = 0; i < tokenRangeCount; i++) { BigInteger start = ringTokens.get(i); BigInteger stop = ringTokens.get((i + ...
@Test public void testGenerateSegments() { List<BigInteger> tokens = Stream.of( "0", "1", "56713727820156410577229101238628035242", "56713727820156410577229101238628035243", "113427455640312821154458202477256070484", ...
@Udf(description = "Converts a string representation of a time in the given format" + " into the TIME value.") public Time parseTime( @UdfParameter( description = "The string representation of a time.") final String formattedTime, @UdfParameter( description = "The format pattern ...
@Test public void shouldThrowOnEmptyString() { // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> udf.parseTime("", "HHmmss") ); // Then: assertThat(e.getMessage(), containsString("Failed to parse time '' with formatter 'HHmmss'")); }
@VisibleForTesting /*package*/ ExpansionApi.ExpansionResponse expand(ExpansionApi.ExpansionRequest request) { LOG.info( "Expanding '{}' with URN '{}'", request.getTransform().getUniqueName(), request.getTransform().getSpec().getUrn()); LOG.debug("Full transform: {}", request.getTransfo...
@Test public void testConstructGenerateSequenceWithRegistration() { ExternalTransforms.ExternalConfigurationPayload payload = encodeRowIntoExternalConfigurationPayload( Row.withSchema( Schema.of( Field.of("start", FieldType.INT64), ...
public static String getPathWithoutScheme(Path path) { return path.toUri().getPath(); }
@Test public void testGetPathWithoutSchema() { final Path path = new Path("/foo/bar/baz"); final String output = HadoopUtils.getPathWithoutScheme(path); assertEquals("/foo/bar/baz", output); }
@Override public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { return uploadSegment(segmentFile, segmentName, _timeoutInMs); }
@Test public void testSuccessfulUpload() { SegmentUploader segmentUploader = new PinotFSSegmentUploader("hdfs://root", TIMEOUT_IN_MS, _serverMetrics); URI segmentURI = segmentUploader.uploadSegment(_file, _llcSegmentName); Assert.assertTrue(segmentURI.toString().startsWith(StringUtil .join(File.se...
public McastConfig setEgressVlan(VlanId vlanId) { if (vlanId == null) { object.remove(EGRESS_VLAN); } else { object.put(EGRESS_VLAN, vlanId.toString()); } return this; }
@Test public void setEgressVlan() throws Exception { config.setEgressVlan(EGRESS_VLAN_2); VlanId egressVlan = config.egressVlan(); assertNotNull("egressVlan should not be null", egressVlan); assertThat(egressVlan, is(EGRESS_VLAN_2)); }
void restoreBatch(final Collection<ConsumerRecord<byte[], byte[]>> records) { // compute the observed stream time at the end of the restore batch, in order to speed up // restore by not bothering to read from/write to segments which will have expired by the // time the restoration process is co...
@Test public void shouldRestoreWithNullsAndRepeatTimestamps() { final List<DataRecord> records = new ArrayList<>(); records.add(new DataRecord("k", "to_be_replaced", SEGMENT_INTERVAL + 20)); records.add(new DataRecord("k", null, SEGMENT_INTERVAL - 10)); records.add(new DataRecord("k"...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testViewWithUppercaseColumn() { analyze("SELECT * FROM v4"); }
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KST...
@Test public void shouldBuildCorrectFormatsForV2NonWindowedTable() { // Given: givenNonWindowedTable(); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSource, contextStacker ); // Then: assertThat(((TableSource) result...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabl...
@Test public void testListFileDot() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch( new Path(container, ...
@Override public String getFileId(final DriveItem.Metadata metadata) { final ItemReference parent = metadata.getParentReference(); if(metadata.getRemoteItem() != null) { final DriveItem.Metadata remoteMetadata = metadata.getRemoteItem(); final ItemReference remoteParent = rem...
@Test public void testRealConsumerFileIdResponseSharedWithMe() throws Exception { final DriveItem.Metadata metadata; try (final InputStream test = getClass().getResourceAsStream("/RealConsumerFileIdResponseSharedWithMe.json")) { final InputStreamReader reader = new InputStreamReader(test...
public FEELFnResult<Range> invoke(@ParameterName("from") String from) { if (from == null || from.isEmpty() || from.isBlank()) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "from", "cannot be null")); } Range.RangeBoundary startBoundary; if...
@Test void evaluateWithInvalidFunctionInvocationNode() { Object[][] data = invalidFunctionInvocationNodeData(); Arrays.stream(data).forEach(objects -> { String expression = String.format("[%1$s..%1$s]", objects[0]); FEELFnResult<Range> retrieved = rangeFunction.invoke(express...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldEvaluateTypeForMultiParamUdaf() { // Given: givenUdafWithNameAndReturnType("TEST_ETM", SqlTypes.STRING, aggregateFactory, aggregateFunction); final Expression expression = new FunctionCall( FunctionName.of("TEST_ETM"), ImmutableList.of( C...
protected Set<MediaType> getSupportedMediaTypesForInput() { return mSupportedMediaTypesUnmodifiable; }
@Test(expected = UnsupportedOperationException.class) public void testMediaTypesIsUnmodifiable() { mPackageScope.getSupportedMediaTypesForInput().add(MediaType.Image); }
public static String getByFilename(String filename) { String extension = FilenameUtils.getExtension(filename); String mime = null; if (!isNullOrEmpty(extension)) { mime = MAP.get(extension.toLowerCase(Locale.ENGLISH)); } return mime != null ? mime : DEFAULT; }
@Test public void getByFilename() { assertThat(MediaTypes.getByFilename("static/sqale/sqale.css")).isEqualTo("text/css"); assertThat(MediaTypes.getByFilename("sqale.css")).isEqualTo("text/css"); }
@VisibleForTesting static Map<String, Object> forCodec( Map<String, Object> codec, boolean replaceWithByteArrayCoder) { String coderType = (String) codec.get(PropertyNames.OBJECT_TYPE_NAME); // Handle well known coders. if (LENGTH_PREFIX_CODER_TYPE.equals(coderType)) { if (replaceWithByteArra...
@Test public void testLengthPrefixForLengthPrefixCoder() throws Exception { Coder<WindowedValue<KV<String, Integer>>> windowedValueCoder = WindowedValue.getFullCoder( KvCoder.of(StringUtf8Coder.of(), LengthPrefixCoder.of(VarIntCoder.of())), GlobalWindow.Coder.INSTANCE); Map<St...
@Override public void run() { try (MdcCloseable ignored = MdcUtils.withContext(MdcUtils.asContextData(jobId))) { doRun(); } finally { terminationFuture.complete(executionState); } }
@Test public void testCleanupWhenRestoreFails() throws Exception { createTaskBuilder() .setInvokable(InvokableWithExceptionInRestore.class) .build(Executors.directExecutor()) .run(); assertTrue(wasCleanedUp); }
@Override public float readFloat() throws EOFException { return Float.intBitsToFloat(readInt()); }
@Test public void testReadFloatForPositionByteOrder() throws Exception { double readFloat = in.readFloat(2, LITTLE_ENDIAN); int intB = Bits.readIntL(INIT_DATA, 2); double aFloat = Float.intBitsToFloat(intB); assertEquals(aFloat, readFloat, 0); }
public double getWeight() { return weight; }
@Test void getWeight() { final double weight = 33.45; assertThat(KIE_PMML_SEGMENT.getWeight()).isCloseTo(1.0, Offset.offset(0.0)); KIE_PMML_SEGMENT = BUILDER.withWeight(weight).build(); assertThat(KIE_PMML_SEGMENT.getWeight()).isCloseTo(weight, Offset.offset(0.0)); }
public static Ip6Prefix valueOf(byte[] address, int prefixLength) { return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfAddressNegativePrefixLengthIPv6() { Ip6Address ipAddress; Ip6Prefix ipPrefix; ipAddress = Ip6Address.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"); ipPrefix = Ip6Prefix.valueOf(ipAddress,...
public StickyPartitionCache() { this.indexCache = new ConcurrentHashMap<>(); }
@Test public void testStickyPartitionCache() { List<PartitionInfo> allPartitions = asList(new PartitionInfo(TOPIC_A, 0, NODES[0], NODES, NODES), new PartitionInfo(TOPIC_A, 1, NODES[1], NODES, NODES), new PartitionInfo(TOPIC_A, 2, NODES[2], NODES, NODES), new PartitionInfo...
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) { return index(keyFunction, Function.identity()); }
@Test public void index_fails_if_key_function_is_null() { assertThatThrownBy(() -> index(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't be null"); }
@Override public void completeRestoration(final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) { switch (state()) { case RUNNING: return; case RESTORING: resetOffsetsIfNeededAndInitializeMetadata(offsetResetter); init...
@Test public void shouldThrowStreamsExceptionWhenFetchCommittedFailed() { when(stateManager.taskId()).thenReturn(taskId); when(stateManager.taskType()).thenReturn(TaskType.ACTIVE); final Consumer<byte[], byte[]> consumer = new MockConsumer<byte[], byte[]>(OffsetResetStrategy.EARLIEST) { ...
public boolean isSameProtocolAndStorageTypes() { return storageTypes.values().stream().allMatch(protocolType::equals); }
@Test void assertIsDifferentProtocolAndStorageTypes() { GenericSchemaBuilderMaterial material = new GenericSchemaBuilderMaterial(TypedSPILoader.getService(DatabaseType.class, "FIXTURE"), Collections.singletonMap("foo", null), Collections.emptyMap(), Collections.emptyList(), n...
public static FileIO loadFileIO(String impl, Map<String, String> properties, Object hadoopConf) { LOG.info("Loading custom FileIO implementation: {}", impl); DynConstructors.Ctor<FileIO> ctor; try { ctor = DynConstructors.builder(FileIO.class) .loader(CatalogUtil.class.getClass...
@Test public void loadCustomFileIO_hadoopConfigConstructor() { Configuration configuration = new Configuration(); configuration.set("key", "val"); FileIO fileIO = CatalogUtil.loadFileIO(HadoopFileIO.class.getName(), Maps.newHashMap(), configuration); assertThat(fileIO).isInstanceOf(HadoopFileI...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Test SchemaProperties and additionalProperties annotations") public void testSchemaProperties() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(SchemaPropertiesResource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + ...
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokeNegative() { FunctionTestUtil.assertResultBigDecimal(ceilingFunction.invoke(BigDecimal.valueOf(-10.2)), BigDecimal.valueOf(-10)); }
@Override public void execute(SensorContext context) { FilePredicates p = context.fileSystem().predicates(); List<InputFile> sourceFiles = StreamSupport.stream( context.fileSystem().inputFiles( p.and( p.hasType(InputFile.Type.MAIN), p.hasLanguage("java") ) ).spl...
@Test public void testExclusions() { file.setExcludedForDuplication(true); new JavaCpdBlockIndexerSensor(index).execute(context); verifyNoInteractions(index); }
void processSingleResource(FileStatus resource) { Path path = resource.getPath(); // indicates the processing status of the resource ResourceStatus resourceStatus = ResourceStatus.INIT; // first, if the path ends with the renamed suffix, it indicates the // directory was moved (as stale) but someho...
@Test void testProcessEvictableResource() throws Exception { FileSystem fs = mock(FileSystem.class); CleanerMetrics metrics = mock(CleanerMetrics.class); SCMStore store = mock(SCMStore.class); CleanerTask task = createSpiedTask(fs, store, metrics, new ReentrantLock()); // mock an evictab...
public static double parseDouble(String number) { if (StrUtil.isBlank(number)) { return 0D; } try { return Double.parseDouble(number); } catch (NumberFormatException e) { return parseNumber(number).doubleValue(); } }
@Test public void parseDoubleTest() { // -------------------------- Parse failed ----------------------- assertNull(NumberUtil.parseDouble("abc", null)); assertNull(NumberUtil.parseDouble("a123.33", null)); assertNull(NumberUtil.parseDouble("..123", null)); assertEquals(1233D, NumberUtil.parseDouble(StrUti...
@Override public S3ClientBuilder createBuilder(S3Options s3Options) { return createBuilder(S3Client.builder(), s3Options); }
@Test public void testSetRegion() { when(s3Options.getAwsRegion()).thenReturn(Region.US_WEST_1); DefaultS3ClientBuilderFactory.createBuilder(builder, s3Options); verify(builder).region(Region.US_WEST_1); verifyNoMoreInteractions(builder); }
@Override public void unregister(String pluginId) { }
@Test public void testUnregister() { manager.register(new TestPlugin()); manager.unregister(TestPlugin.class.getSimpleName()); Assert.assertTrue(isEmpty(manager)); }
@CanIgnoreReturnValue public GsonBuilder excludeFieldsWithModifiers(int... modifiers) { Objects.requireNonNull(modifiers); excluder = excluder.withModifiers(modifiers); return this; }
@Test public void testExcludeFieldsWithModifiers() { Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE).create(); assertThat(gson.toJson(new HasModifiers())).isEqualTo("{\"d\":\"d\"}"); }
@Override public Long createNotifyTemplate(NotifyTemplateSaveReqVO createReqVO) { // 校验站内信编码是否重复 validateNotifyTemplateCodeDuplicate(null, createReqVO.getCode()); // 插入 NotifyTemplateDO notifyTemplate = BeanUtils.toBean(createReqVO, NotifyTemplateDO.class); notifyTemplate.se...
@Test public void testCreateNotifyTemplate_success() { // 准备参数 NotifyTemplateSaveReqVO reqVO = randomPojo(NotifyTemplateSaveReqVO.class, o -> o.setStatus(randomCommonStatus())) .setId(null); // 防止 id 被赋值 // 调用 Long notifyTemplateId = notifyTemplateSer...
@Override public int hashCode() { return Objects.hash(username, password); }
@Test void hasAWorkingHashCode() { assertThat(credentials.hashCode()) .hasSameHashCodeAs(new BasicCredentials("u", "p")) .isNotEqualTo(new BasicCredentials("u1", "p").hashCode()) .isNotEqualTo(new BasicCredentials("u", "p1").hashCode()); }
public static ExpressionEvaluator compileExpression( String expression, List<String> argumentNames, List<Class<?>> argumentClasses, Class<?> returnClass) { ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator(); expressionEvaluator.setParamete...
@Test public void testJaninoCharCompare() throws InvocationTargetException { String expression = "String.valueOf('2').equals(col1)"; List<String> columnNames = Arrays.asList("col1"); List<Class<?>> paramTypes = Arrays.asList(String.class); List<Object> params = Arrays.asList("2"); ...
@Override public void copyParametersFrom( NamedParams aParam ) { if ( params != null && aParam != null ) { params.clear(); String[] keys = aParam.listParameters(); for ( int idx = 0; idx < keys.length; idx++ ) { String desc; try { desc = aParam.getParameterDescription( ...
@Test public void testCopyParametersFrom() throws Exception { NamedParams namedParams2 = new NamedParamsDefault(); namedParams2.addParameterDefinition( "key", "default value", "description" ); namedParams2.setParameterValue( "key", "value" ); assertNull( namedParams.getParameterValue( "key" ) ); n...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthNewBlockFilter() throws Exception { web3j.ethNewBlockFilter().send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_newBlockFilter\"," + "\"params\":[],\"id\":1}"); }
public static RetryRegistry of(Configuration configuration, CompositeCustomizer<RetryConfigCustomizer> customizer) { CommonRetryConfigurationProperties retryConfiguration = CommonsConfigurationRetryConfiguration.of(configuration); Map<String, RetryConfig> retryConfigMap = retryConfiguration.getInstances...
@Test public void testRetryRegistryFromYamlFile() throws ConfigurationException { Configuration config = CommonsConfigurationUtil.getConfiguration(YAMLConfiguration.class, TestConstants.RESILIENCE_CONFIG_YAML_FILE_NAME); RetryRegistry registry = CommonsConfigurationRetryRegistry.of(config, new Comp...