focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Block toBlock(Type desiredType) { checkArgument(BIGINT.equals(desiredType), "type doesn't match: %s", desiredType); int numberOfRecords = numberOfRecords(); return new LongArrayBlock( numberOfRecords, Optional.ofNullable(nulls), ...
@Test public void testReadBlock() { PrestoThriftBlock columnsData = longColumn( new boolean[] {false, true, false, false, false, false, true}, new long[] {2, 0, 1, 3, 8, 4, 0}); Block actual = columnsData.toBlock(BIGINT); assertBlockEquals(actual, list(2L,...
public static Collection<PerStepNamespaceMetrics> convert( String stepName, Map<MetricName, Long> counters, Map<MetricName, LockFreeHistogram.Snapshot> histograms, Map<MetricName, LabeledMetricNameUtils.ParsedMetricName> parsedPerWorkerMetricsCache) { Map<String, PerStepNamespaceMetrics> me...
@Test public void testConvert_skipInvalidMetricNames() { Map<MetricName, LabeledMetricNameUtils.ParsedMetricName> parsedMetricNames = new HashMap<>(); Map<MetricName, Long> counters = new HashMap<>(); MetricName invalidName1 = MetricName.named("BigQuerySink", "**"); counters.put(invalidName1, 5L); ...
@Override public ObjectNode encode(KubevirtNode node, CodecContext context) { checkNotNull(node, "Kubevirt node cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(HOST_NAME, node.hostname()) .put(TYPE, node.type().name()) ....
@Test public void testKubevirtComputeNodeEncode() { KubevirtPhyInterface phyIntf1 = DefaultKubevirtPhyInterface.builder() .network("mgmtnetwork") .intf("eth3") .physBridge(DEVICE_ID_1) .build(); KubevirtPhyInterface phyIntf2 = DefaultK...
public boolean isValid() { if (tokens == null) getTokens(); return valid; }
@Test public void testValidationProcess() { // TopicMultiInTheMiddle assertThat(new Topic("finance/#/closingprice")).isInValid(); // MultiNotAfterSeparator assertThat(new Topic("finance#")).isInValid(); // TopicMultiNotAlone assertThat(new Topic("/finance/#closingpr...
public String stringify(boolean value) { throw new UnsupportedOperationException( "stringify(boolean) was called on a non-boolean stringifier: " + toString()); }
@Test public void testDefaultStringifier() { PrimitiveStringifier stringifier = DEFAULT_STRINGIFIER; assertEquals("true", stringifier.stringify(true)); assertEquals("false", stringifier.stringify(false)); assertEquals("0.0", stringifier.stringify(0.0)); assertEquals("123456.7891234567", stringif...
public static String buildErrorMessage(final Throwable throwable) { if (throwable == null) { return ""; } final List<String> messages = dedup(getErrorMessages(throwable)); final String msg = messages.remove(0); final String causeMsg = messages.stream() .filter(s -> !s.isEmpty()) ...
@Test public void shouldHandleRecursiveExceptions() { assertThat( buildErrorMessage(new RecursiveException("It went boom")), is("It went boom") ); }
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testLessThanEqualsOperand() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); SearchArgument arg = builder.startAnd().lessThanEquals("salary", PredicateLeaf.Type.LONG, 3000L).end().build(); UnboundPredicate expected = Expressions.lessThanOrEqual("salary", 30...
@Override public List<Long> selectAllComputeNodes() { List<Long> nodeIds = availableID2ComputeNode.values().stream() .map(ComputeNode::getId) .collect(Collectors.toList()); nodeIds.forEach(this::selectWorkerUnchecked); return nodeIds; }
@Test public void testChooseAllComputedNodes() { { // empty compute nodes WorkerProvider workerProvider = new DefaultSharedDataWorkerProvider(ImmutableMap.of(), ImmutableMap.of()); Assert.assertTrue(workerProvider.selectAllComputeNodes().isEmpty()); } ...
public Map<String, Object> getContext(Map<String, Object> modelMap, Class<? extends SparkController> controller, String viewName) { Map<String, Object> context = new HashMap<>(modelMap); context.put("currentGoCDVersion", CurrentGoCDVersion.getInstance().getGocdDistVersion()); context.put("railsA...
@Test void shouldNotShowAnalyticsDashboardPluginIsNotPresent() { Map<String, Object> modelMap = new HashMap<>(); when(securityService.isUserAdmin(any(Username.class))).thenReturn(true); when(pluginInfoFinder.allPluginInfos(PluginConstants.ANALYTICS_EXTENSION)).thenReturn(List.of(new Combined...
protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String...
@Test public void postRequest() throws HttpException, IOException { // Processor is required because it will determine the final request body including // headers before outgoing. RequestContent processor = new RequestContent(); Map<String, String> params = new HashMap<String, String...
public static DataSource createDataSource(final File yamlFile) throws SQLException, IOException { YamlJDBCConfiguration rootConfig = YamlEngine.unmarshal(yamlFile, YamlJDBCConfiguration.class); return createDataSource(new YamlDataSourceConfigurationSwapper().swapToDataSources(rootConfig.getDataSources()...
@Test void assertCreateDataSourceWithBytesForExternalDataSources() throws Exception { Map<String, DataSource> dataSourceMap = new HashMap<>(2, 1F); dataSourceMap.put("ds_0", new MockedDataSource()); dataSourceMap.put("ds_1", new MockedDataSource()); assertDataSource(YamlShardingSpher...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsAtLeast_primitiveFloatArray_inOrder_success() { assertThat(array(1.1f, TOLERABLE_2POINT2, 3.3f)) .usingTolerance(DEFAULT_TOLERANCE) .containsAtLeast(array(1.1f, 2.2f)) .inOrder(); }
public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) { Socket pipe = ctx.createSocket(SocketType.PAIR); assert (pipe != null); pipe.bind(String.format(Locale.ENGLISH, "inproc://zctx-pipe-%d", pipe.hashCode())); // Connect child pipe to our pipe ...
@Test @Ignore public void testClosePipe() { ZContext ctx = new ZContext(); Socket pipe = ZThread.fork(ctx, (args, ctx1, pipe1) -> { pipe1.recvStr(); pipe1.send("pong"); }); assertThat(pipe, notNullValue()); boolean rc = pipe.send("ping"); ...
public boolean areAllowedAllNamespaces(String tenant, String fromTenant, String fromNamespace) { return true; }
@Test void areAllowedAllNamespaces() { assertTrue(flowService.areAllowedAllNamespaces("tenant", "fromTenant", "fromNamespace")); }
public void addServletListeners(EventListener... listeners) { for (EventListener listener : listeners) { handler.addEventListener(listener); } }
@Test void addsServletListeners() { final ServletContextListener listener = new DebugListener(); environment.addServletListeners(listener); assertThat(handler.getEventListeners()).contains(listener); }
@Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { // 1.1 参数校验 if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } ...
@Test public void testImportUserList_03() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setStatus(randomEle(CommonStatusEnum.values()).getStatus...
public static Field p(String fieldName) { return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName); }
@Test void fuzzy() { String q = Q.p("f1").fuzzy("text to match").build(); assertEquals("yql=select * from sources * where f1 contains (fuzzy(\"text to match\"))", q); }
public static String getGlobalContextEntry(String key) { return GLOBAL_CONTEXT_MAP.get(key); }
@Test public void testVerifyProcessID() throws Throwable { assertThat( getGlobalContextEntry(PARAM_PROCESS)) .describedAs("global context value of %s", PARAM_PROCESS) .isEqualTo(PROCESS_ID); }
public static BytesInput concat(BytesInput... inputs) { return new SequenceBytesIn(Arrays.asList(inputs)); }
@Test public void testConcat() throws IOException { byte[] data = new byte[1000]; RANDOM.nextBytes(data); Supplier<BytesInput> factory = () -> BytesInput.concat( BytesInput.from(toByteBuffer(data, 0, 250)), BytesInput.empty(), BytesInput.from(toByteBuffer(data, 250, 250)), ...
public String getFiltersFile() { return filtersFile; }
@Test public void testExclusionsOption() { final DistCpOptions.Builder builder = new DistCpOptions.Builder( new Path("hdfs://localhost:8020/source/first"), new Path("hdfs://localhost:8020/target/")); Assert.assertNull(builder.build().getFiltersFile()); builder.withFiltersFile("/tmp/filter...
@Cacheable(value = "metadata-response", key = "#samlMetadataRequest.cacheableKey()") public SamlMetadataResponse resolveSamlMetadata(SamlMetadataRequest samlMetadataRequest) { LOGGER.info("Cache not found for saml-metadata {}", samlMetadataRequest.hashCode()); Connection connection = connectionServ...
@Test void serviceNotFoundTest() { Connection connection = newConnection(SAML_COMBICONNECT, true, true, true); when(connectionServiceMock.getConnectionByEntityId(anyString())).thenReturn(connection); when(serviceServiceMock.serviceExists(any(Connection.class), anyString(), anyString())).the...
public String createULID(Message message) { checkTimestamp(message.getTimestamp().getMillis()); try { return createULID(message.getTimestamp().getMillis(), message.getSequenceNr()); } catch (Exception e) { LOG.error("Exception while creating ULID.", e); return...
@Test public void intMaxGenerate() { final MessageULIDGenerator generator = new MessageULIDGenerator(new ULID()); final long ts = Tools.nowUTC().getMillis(); ULID.Value parsedULID = ULID.parseULID(generator.createULID(ts, Integer.MAX_VALUE)); assertThat(extractSequenceNr(parsedULI...
@Override public boolean exists() { setupClientIfNeeded(); try (Reader<String> historyReader = createHistoryReader()) { return historyReader.hasMessageAvailable(); } catch (IOException e) { log.error("Encountered issues on checking existence of database history", e); ...
@Test public void testExists() throws Exception { // happy path testHistoryTopicContent(true, false); assertTrue(history.exists()); // Set history to use dummy topic Configuration config = Configuration.create() .with(PulsarDatabaseHistory.SERVICE_URL, brokerUrl....
@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 shouldReturnEmptyStringForZeroLength() { final String result = udf.rpad("foo", 0, "bar"); assertThat(result, is("")); }
public int runInteractively() { displayWelcomeMessage(); RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient); boolean eof = false; while (!eof) { try { handleLine(nextNonCliCommand()); } catch (final EndOfFileException exception) { // EOF is fine, just t...
@Test public void shouldPrintWarningOnUnknownServerVersion() throws Exception { givenRunInteractivelyWillExit(); final KsqlRestClient mockRestClient = givenMockRestClient("bad-version"); new Cli(1L, 1L, mockRestClient, console) .runInteractively(); assertThat( terminal.getOutputStri...
@Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList()); response.remov...
@Test public void testInterceptorMultipleHeaderFilteredWarning() throws IOException, HttpException { OpenSearchFilterDeprecationWarningsInterceptor interceptor = new OpenSearchFilterDeprecationWarningsInterceptor(); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersi...
@ScalarOperator(LESS_THAN) @SqlType(StandardTypes.BOOLEAN) public static boolean lessThan(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right) { return left < right; }
@Test public void testLessThan() { assertFunction("INTEGER'37' < INTEGER'37'", BOOLEAN, false); assertFunction("INTEGER'37' < INTEGER'17'", BOOLEAN, false); assertFunction("INTEGER'17' < INTEGER'37'", BOOLEAN, true); assertFunction("INTEGER'17' < INTEGER'17'", BOOLEAN, false); ...
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testParseNewStyleResourceMemoryNegative() throws Exception { expectNegativeValueOfResource("memory"); parseResourceConfigValue("memory-mb=-5120,vcores=2"); }
@Override void toHtml() throws IOException { writeHtmlHeader(); htmlCoreReport.toHtml(); writeHtmlFooter(); }
@Test public void testEmptyCounter() throws IOException { final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); // rapport avec counter sans requête counter.clear(); errorCounter.clear(); htmlReport.toHtml(null, null); assertNotEmptyAndClear(writer); ...
@Override public void close() { if (_executionFuture != null) { _executionFuture.cancel(true); } }
@Test public void shouldNotErrorOutWhenIncorrectDataSchemaProvidedWithEmptyRowsSelection() { // Given: QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT strCol, intCol FROM tbl"); DataSchema resultSchema = new DataSchema(new String[]{"strCol", "intCol"}, new DataSchema...
public static String getHeartbeatClientIp() { String ip = SentinelConfig.getConfig(HEARTBEAT_CLIENT_IP, true); if (StringUtil.isBlank(ip)) { ip = HostNameUtil.getIp(); } return ip; }
@Test public void testGetHeartbeatClientIp() { String clientIp = "10.10.10.10"; SentinelConfig.setConfig(TransportConfig.HEARTBEAT_CLIENT_IP, clientIp); // Set heartbeat client ip to system property. String ip = TransportConfig.getHeartbeatClientIp(); assertNotNull(ip); ...
public void addResources(ConcurrentMap<String, ? extends LocallyCachedBlob> blobs) { for (LocallyCachedBlob b : blobs.values()) { currentSize += b.getSizeOnDisk(); if (b.isUsed()) { LOG.debug("NOT going to clean up {}, {} depends on it", b.getKey(), b.getDependencies()); ...
@Test public void testAddResources() { PortAndAssignment pna1 = new PortAndAssignmentImpl(1, new LocalAssignment("topo1", Collections.emptyList())); PortAndAssignment pna2 = new PortAndAssignmentImpl(1, new LocalAssignment("topo2", Collections.emptyList())); String user = "user"; Map...
public OrderedProperties addStringPairs(String keyValuePairs) { PropertiesReader reader = new PropertiesReader(pairs); reader.read(keyValuePairs); return this; }
@Test public void addStringPairs() { OrderedProperties pairs = new OrderedProperties() .addStringPairs("first=1\nsecond=2\nthird=3\nFOURTH=4"); assertValueOrder(pairs, "1", "2", "3", "4"); }
@Override public WindowStoreIterator<V> backwardFetch(final K key, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { Objects.requireNonNull(key, "key can't be null"); final L...
@Test public void shouldThrowInvalidStateStoreExceptionOnRebalanceWhenBackwards() { final StateStoreProvider storeProvider = mock(StateStoreProvider.class); when(storeProvider.stores(anyString(), any())) .thenThrow(new InvalidStateStoreException("store is unavailable")); final C...
public static Validator parses(final Function<String, ?> parser) { return (name, val) -> { if (val != null && !(val instanceof String)) { throw new IllegalArgumentException("validator should only be used with STRING defs"); } try { parser.apply((String)val); } catch (final Ex...
@Test public void shouldPassNullsToParser() { // Given: final Validator validator = ConfigValidators.parses(parser); // When: validator.ensureValid("propName", null); // Then: verify(parser).apply(null); }
@Override public MetricType getType() { return MetricType.GAUGE_UNKNOWN; }
@Test public void getValue() { UnknownGauge gauge = new UnknownGauge("bar", URI.create("baz")); assertThat(gauge.getValue()).isEqualTo(URI.create("baz")); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_UNKNOWN); //Null initialize gauge = new UnknownGauge("bar"); ...
@NonNull public RouterFunction<ServerResponse> create() { var getHandler = new ExtensionGetHandler(scheme, client); var listHandler = new ExtensionListHandler(scheme, client); var createHandler = new ExtensionCreateHandler(scheme, client); var updateHandler = new ExtensionUpdateHandl...
@Test void shouldCreateSuccessfully() { var routerFunction = factory.create(); testCases().forEach(testCase -> { List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders(); var request = ServerRequest.create(testCase.webExch...
public static NamespaceName get(String tenant, String namespace) { validateNamespaceName(tenant, namespace); return get(tenant + '/' + namespace); }
@Test(expectedExceptions = IllegalArgumentException.class) public void namespace_emptyTenantElement() { NamespaceName.get("/cluster/namespace"); }
@Override public RemoteData.Builder serialize() { final RemoteData.Builder remoteBuilder = RemoteData.newBuilder(); remoteBuilder.addDataObjectStrings(total.toStorageData()); remoteBuilder.addDataLongs(getTimeBucket()); remoteBuilder.addDataStrings(getEntityId()); remoteBui...
@Test public void testSerialize() { function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), table1); SumPerMinLabeledFunction function2 = Mockito.spy(SumPerMinLabeledFunction.class); function2.deserialize(function.serialize().build()); assertThat(function2.getEntityId...
public Main() { addOption(new Option("h", "help", "Displays the help screen") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { showOptions(); // no need to process further if user just wants help System.exit(0); } ...
@Test public void testMainShowOptions() { assertDoesNotThrow(() -> Main.main(new String[] {})); }
public static <E> boolean addWithoutChecking(CheckedList<E> list, E element) { return list.addWithAssertChecking(element); }
@Test(expectedExceptions = AssertionError.class) public void testAddCycleWithAssertChecking() { final DataList list = new DataList(); CheckedUtil.addWithoutChecking(list, list); }
@Override public int permitMinimum() { return minConnections; }
@Test void permitMinimum() { builder.minConnections(2); Http2AllocationStrategy strategy = builder.build(); assertThat(strategy.maxConcurrentStreams()).isEqualTo(DEFAULT_MAX_CONCURRENT_STREAMS); assertThat(strategy.permitMaximum()).isEqualTo(DEFAULT_MAX_CONNECTIONS); assertThat(strategy.permitMinimum()).isEq...
public static List<String> getJavaOpts(Configuration conf) { String adminOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_KEY, YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_DEFAULT); String userOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_KEY, ...
@Test public void testDefaultJavaOptionsWhenExtraJDK17OptionsAreConfigured() throws Exception { ContainerLocalizerWrapper wrapper = new ContainerLocalizerWrapper(); ContainerLocalizer localizer = wrapper.setupContainerLocalizerForTest(); Configuration conf = new Configuration(); conf.setBoolean(YarnC...
public String defaultRemoteUrl() { final String sanitizedUrl = sanitizeUrl(); try { URI uri = new URI(sanitizedUrl); if (uri.getUserInfo() != null) { uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri...
@Test void shouldNotModifyFileURIS() { assertThat(new HgUrlArgument("file://junk").defaultRemoteUrl(), is("file://junk")); }
public static NodeList selectNodeList(Document document, String xPathExpression) throws TransformerException { XObject xObject = XPathAPI.eval(document, xPathExpression, getPrefixResolver(document)); return xObject.nodelist(); }
@Test public void testSelectNodeList() throws ParserConfigurationException, SAXException, IOException, TidyException, TransformerException { String responseData = "<book><page>one</page><page>two</page><empty></empty><a><b></b></a></book>"; Document testDoc = XPathUtil.makeDocument( ...
static Schema removeFields(Schema schema, String... fields) { List<String> exclude = Arrays.stream(fields).collect(Collectors.toList()); Schema.Builder builder = Schema.builder(); for (Field field : schema.getFields()) { if (exclude.contains(field.getName())) { continue; } builder....
@Test public void testPubsubRowToMessageParDo_attributesWithoutTimestamp() { Map<String, String> attributes = new HashMap<>(); attributes.put("a", "1"); attributes.put("b", "2"); attributes.put("c", "3"); Row withAttributes = Row.withSchema(NON_USER_WITH_BYTES_PAYLOAD) .addVal...
public Record convert(final AbstractWALEvent event) { if (filter(event)) { return createPlaceholderRecord(event); } if (!(event instanceof AbstractRowEvent)) { return createPlaceholderRecord(event); } PipelineTableMetaData tableMetaData = getPipelineTableM...
@Test void assertConvertFailure() { AbstractRowEvent event = new AbstractRowEvent() { }; event.setSchemaName(""); event.setTableName("t_order"); assertThrows(UnsupportedSQLOperationException.class, () -> walEventConverter.convert(event)); }
@Override public ShenyuContext build(final ServerWebExchange exchange) { Pair<String, MetaData> buildData = buildData(exchange); return decoratorMap.get(buildData.getLeft()).decorator(buildDefaultContext(exchange.getRequest()), buildData.getRight()); }
@Test public void testBuild() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost:8080/http") .remoteAddress(new InetSocketAddress(8092)) .header("MetaDataCache", "Hello") .build()); ShenyuContext s...
public static ConnAckBuilder connAck() { return new ConnAckBuilder(); }
@Test public void testConnAckWithProperties() { final MqttConnAckMessage ackMsg = MqttMessageBuilders.connAck() .properties(new PropertiesInitializer<MqttMessageBuilders.ConnAckPropertiesBuilder>() { @Override public void apply(MqttMessageBuilders.ConnAckPropertiesBui...
public static String toJsonStr(JSON json, int indentFactor) { if (null == json) { return null; } return json.toJSONString(indentFactor); }
@Test public void toJsonStrTest() { final UserA a1 = new UserA(); a1.setA("aaaa"); a1.setDate(DateUtil.date()); a1.setName("AAAAName"); final UserA a2 = new UserA(); a2.setA("aaaa222"); a2.setDate(DateUtil.date()); a2.setName("AAAA222Name"); final ArrayList<UserA> list = CollectionUtil.newArrayList(...
@VisibleForTesting Path getActualPath() throws IOException { Path path = localPath; FileStatus status = localFs.getFileStatus(path); if (status != null && status.isDirectory()) { // for certain types of resources that get unpacked, the original file may // be found under the directory with the...
@Test public void testGetActualPath() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(YarnConfiguration.SHARED_CACHE_ENABLED, true); LocalResource resource = mock(LocalResource.class); // give public visibility when(resource.getVisibility()).thenReturn(LocalResourceVis...
public URI buildEncodedUri(String endpointUrl) { if (endpointUrl == null) { throw new RuntimeException("Url string cannot be null!"); } if (endpointUrl.isEmpty()) { throw new RuntimeException("Url string cannot be empty!"); } URI uri = UriComponentsBuilde...
@Test public void testBuildSimpleUri() { Mockito.when(client.buildEncodedUri(any())).thenCallRealMethod(); String url = "http://localhost:8080/"; URI uri = client.buildEncodedUri(url); Assertions.assertEquals(url, uri.toString()); }
@Override public void serialize(Asn1OutputStream out, BigInteger obj) { out.write(BCD.encode(obj)); }
@Test public void shouldSerialize() { assertArrayEquals( new byte[] { 0x13, 0x37 }, serialize(new BcdConverter(), BigInteger.class, BigInteger.valueOf(1337)) ); }
@Produces @DefaultBean @Singleton JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration() { if (jobRunrBuildTimeConfiguration.dashboard().enabled()) { final JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration = usingStandardDashboardConfiguration(); ...
@Test void dashboardWebServerConfigurationIsSetupWhenConfigured() { when(dashboardBuildTimeConfiguration.enabled()).thenReturn(true); assertThat(jobRunrProducer.dashboardWebServerConfiguration()).isNotNull(); }
@Override public Long del(byte[]... keys) { if (isQueueing() || isPipelined()) { for (byte[] key: keys) { write(key, LongCodec.INSTANCE, RedisCommands.DEL, key); } return null; } CommandBatchService es = new CommandBatchService(executorSe...
@Test public void testDelPipeline() { byte[] k = "key".getBytes(); byte[] v = "val".getBytes(); connection.set(k, v); connection.openPipeline(); connection.get(k); connection.del(k); List<Object> results = connection.closePipeline(); byte[] val = (byt...
public static Optional<Expression> convert( org.apache.flink.table.expressions.Expression flinkExpression) { if (!(flinkExpression instanceof CallExpression)) { return Optional.empty(); } CallExpression call = (CallExpression) flinkExpression; Operation op = FILTERS.get(call.getFunctionDefi...
@Test public void testLike() { UnboundPredicate<?> expected = org.apache.iceberg.expressions.Expressions.startsWith("field5", "abc"); Expression expr = resolve( ApiExpressionUtils.unresolvedCall( BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions....
public static int toIntSize(long size) { assert size >= 0 : "Invalid size value: " + size; return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size; }
@Test public void toIntSize_whenLessThanIntMax() { long size = 123456789; assertEquals((int) size, toIntSize(size)); }
public boolean isAbilitySupportedByServer(AbilityKey abilityKey) { return rpcClient.getConnectionAbility(abilityKey) == AbilityStatus.SUPPORTED; }
@Test void testIsAbilitySupportedByServer3() { when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( AbilityStatus.UNKNOWN); assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); ...
public static FileMetaData readFileMetaData(InputStream from) throws IOException { return readFileMetaData(from, null, null); }
@Test public void testReadFileMetadata() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileMetaData md = new FileMetaData( 1, asList(new SchemaElement("foo")), 10, asList( new RowGroup(asList(new ColumnChunk(0), new ColumnChunk(1)), 10...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedWildCardInvalidTypes3() { String[] forwardedFields = {"*"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsSingleFromString( ...
@Override protected void runAfterCatalogReady() { try { process(); } catch (Throwable e) { LOG.warn("Failed to process one round of RoutineLoadScheduler", e); } }
@Test public void testEmptyTaskQueue(@Injectable RoutineLoadMgr routineLoadManager) { RoutineLoadTaskScheduler routineLoadTaskScheduler = new RoutineLoadTaskScheduler(routineLoadManager); new Expectations() { { routineLoadManager.getClusterIdleSlotNum(); r...
@VisibleForTesting static SingleSegmentAssignment getNextSingleSegmentAssignment(Map<String, String> currentInstanceStateMap, Map<String, String> targetInstanceStateMap, int minAvailableReplicas, boolean lowDiskMode, Map<String, Integer> numSegmentsToOffloadMap, Map<Pair<Set<String>, Set<String>>, Set<Str...
@Test public void testOneMinAvailableReplicasWithLowDiskMode() { // With 2 common instances, first assignment should keep the common instances and remove the not common instance Map<String, String> currentInstanceStateMap = SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "ho...
static Time toTime(final JsonNode object) { if (object instanceof NumericNode) { return returnTimeOrThrow(object.asLong()); } if (object instanceof TextNode) { try { return returnTimeOrThrow(Long.parseLong(object.textValue())); } catch (final NumberFormatException e) { thro...
@Test(expected = IllegalArgumentException.class) public void shouldFailWhenConvertingIncompatibleTime() { JsonSerdeUtils.toTime(JsonNodeFactory.instance.booleanNode(false)); }
public static boolean isChineseName(CharSequence value) { return isMatchRegex(PatternPool.CHINESE_NAME, value); }
@Test public void isChineseNameTest() { assertTrue(Validator.isChineseName("阿卜杜尼亚孜·毛力尼亚孜")); assertFalse(Validator.isChineseName("阿卜杜尼亚孜./毛力尼亚孜")); assertTrue(Validator.isChineseName("段正淳")); assertFalse(Validator.isChineseName("孟 伟")); assertFalse(Validator.isChineseName("李")); assertFalse(Validator.isCh...
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @PutMapping(IMAGE_URL + "/info") public TbResourceInfo updateImageInfo(@Parameter(description = IMAGE_TYPE_PARAM_DESCRIPTION, schema = @Schema(allowableValues = {"tenant", "system"}), required = true) @PathVa...
@Test public void testUpdateImageInfo() throws Exception { String filename = "my_png_image.png"; TbResourceInfo imageInfo = uploadImage(HttpMethod.POST, "/api/image", filename, "image/png", PNG_IMAGE); ImageDescriptor imageDescriptor = imageInfo.getDescriptor(ImageDescriptor.class); ...
public void cacheRuleData(final String path, final RuleData ruleData, final int initialCapacity, final long maximumSize) { MapUtils.computeIfAbsent(RULE_DATA_MAP, ruleData.getPluginName(), map -> new WindowTinyLFUMap<>(initialCapacity, maximumSize, Boolean.FALSE)).put(path, ruleData); }
@Test public void testCacheRuleData() throws NoSuchFieldException, IllegalAccessException { RuleData cacheRuleData = RuleData.builder().id("1").pluginName(mockPluginName1).sort(1).build(); MatchDataCache.getInstance().cacheRuleData(path1, cacheRuleData, 100, 100); ConcurrentHashMap<String, W...
public static String UU32(java.util.UUID uu) { StringBuilder sb = new StringBuilder(); long m = uu.getMostSignificantBits(); long l = uu.getLeastSignificantBits(); for (int i = 0; i < 13; i++) { sb.append(_UU32[(int) (m >> ((13 - i - 1) * 5)) & 31]); ...
@Test public void testUU32(){ String uu32 = UUID.UU32(); System.out.println(uu32); }
@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 failedWhenSettingsFrameOnNonZeroStream() throws Http2Exception { final ByteBuf input = Unpooled.buffer(); try { writeFrameHeader(input, 6, SETTINGS, new Http2Flags(), 1); input.writeShort(SETTINGS_MAX_HEADER_LIST_SIZE); input.writeInt(1024); ...
public Document process(Document input) throws TransformerException { Document doc = Xml.copyDocument(input); Document document = buildProperties(doc); applyProperties(document.getDocumentElement()); return document; }
@Test public void testWarnIfDuplicatePropertyForSameEnvironment() throws TransformerException { String input = """ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <services xmlns:deploy="vespa" xmlns:preprocess="properties" version="1.0"> ...
Converter<E> compile() { head = tail = null; for (Node n = top; n != null; n = n.next) { switch (n.type) { case Node.LITERAL: addToList(new LiteralConverter<E>((String) n.getValue())); break; case Node.COMPOSITE_KEYWORD: CompositeNode cn = (CompositeNode) n; ...
@Test public void testWithNopEscape() throws Exception { { Parser<Object> p = new Parser<Object>("xyz %hello\\_world"); p.setContext(context); Node t = p.parse(); Converter<Object> head = p.compile(t, converterMap); String result = write(head, new Object()); assertEquals("xyz H...
@Override public void onDraw(Canvas canvas) { final boolean keyboardChanged = mKeyboardChanged; super.onDraw(canvas); // switching animation if (mAnimationLevel != AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) { startAnimation(mInAnimation); mInAnimation = null; } ...
@Test public void testDoesNotAddExtraDrawIfAnimationsAreOff() { SharedPrefsHelper.setPrefsValue(R.string.settings_key_tweak_animations_level, "none"); ExtraDraw mockDraw1 = Mockito.mock(ExtraDraw.class); Mockito.doReturn(true).when(mockDraw1).onDraw(any(), any(), same(mViewUnderTest)); Robolectric.ge...
@Override public String toString() { return "MetadataVersionChange(" + "oldVersion=" + oldVersion + ", newVersion=" + newVersion + ")"; }
@Test public void testMetadataVersionChangeExceptionToString() { assertEquals("org.apache.kafka.image.MetadataVersionChangeException: The metadata.version " + "is changing from 3.0-IV1 to 3.3-IV0", new MetadataVersionChangeException(CHANGE_3_0_IV1_TO_3_3_IV0).toString()); ...
@Override public boolean onTouchEvent(@NonNull MotionEvent nativeMotionEvent) { if (mKeyboard == null) { // I mean, if there isn't any keyboard I'm handling, what's the point? return false; } final int action = nativeMotionEvent.getActionMasked(); final int pointerCount = nativeMotionEven...
@Test public void testRegularPressKeyPressState() { final Keyboard.Key key = findKey('f'); KeyDrawableStateProvider provider = new KeyDrawableStateProvider( R.attr.key_type_function, R.attr.key_type_action, R.attr.action_done, R.attr.action_search, ...
public boolean sendHeartbeatToBroker(long id, String brokerName, String addr) { if (this.lockHeartbeat.tryLock()) { final HeartbeatData heartbeatDataWithSub = this.prepareHeartbeatData(false); final boolean producerEmpty = heartbeatDataWithSub.getProducerDataSet().isEmpty(); ...
@Test public void testSendHeartbeatToBrokerV1() { consumerTable.put(group, createMQConsumerInner()); assertTrue(mqClientInstance.sendHeartbeatToBroker(0L, defaultBroker, defaultBrokerAddr)); }
public ColumnConstraints getConstraints() { return constraints; }
@Test public void shouldReturnKeyConstraint() { // Given: final TableElement valueElement = new TableElement(NAME, new Type(SqlTypes.STRING), KEY_CONSTRAINT); // Then: assertThat(valueElement.getConstraints(), is(KEY_CONSTRAINT)); }
public static Builder withSchema(Schema schema) { return new Builder(schema); }
@Test public void testCreateWithCollectionNames() { Schema type = Stream.of( Schema.Field.of("f_array", FieldType.array(FieldType.INT32)), Schema.Field.of("f_iterable", FieldType.iterable(FieldType.INT32)), Schema.Field.of("f_map", FieldType.map(FieldType.ST...
@Override public boolean postpone( String queueName, String messageId, int priority, long postponeDurationInSeconds) { remove(queueName, messageId); push(queueName, messageId, priority, postponeDurationInSeconds); return true; }
@Test public void testPostpone() { String queueName = "test-queue"; String id = "abcd-1234-defg-5678"; assertTrue(queueDao.postpone(queueName, id, 0, 0)); assertEquals(1, internalQueue.size()); assertEquals(1, internalQueue.get(queueName).size()); assertEquals(id, internalQueue.get(queueName)....
Single<Post> save(Post post) { Post saved = Post.builder().id(UUID.randomUUID()).title(post.getTitle()).content(post.getContent()).build(); DATA.add(saved); return Single.just(saved); }
@Test void save() { var testObserver = new TestObserver<Post>(); this.posts.save(Post.builder().title("test title").content("test content").build()) .subscribe(testObserver); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertVal...
@Override public void render(Node node, Appendable output) { RendererContext context = new RendererContext(new MarkdownWriter(output)); context.render(node); }
@Test public void testBulletListItemsFromAst() { var doc = new Document(); var list = new BulletList(); var item = new ListItem(); item.appendChild(new Text("Test")); list.appendChild(item); doc.appendChild(list); assertRendering("", "- Test\n", render(doc));...
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = trees.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = b; for (int i...
@Test public void testKin8nmHuber() { test(Loss.huber(0.9), "kin8nm", Kin8nm.formula, Kin8nm.data, 0.1795); }
public void resetOffsetsTo(final Consumer<byte[], byte[]> client, final Set<TopicPartition> inputTopicPartitions, final Long offset) { final Map<TopicPartition, Long> endOffsets = client.endOffsets(inputTopicPartitions); final Map<TopicPartit...
@Test public void testResetToSpecificOffsetWhenBeforeBeginningOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); ...
@Override public boolean needLoad() { try { Class.forName("com.alipay.lookout.spi.MetricsImporterLocator"); return true; } catch (Exception e) { return false; } }
@Test public void testNeedLoad() { LookoutModule lookoutModule = new LookoutModule(); Assert.assertEquals(true, lookoutModule.needLoad()); }
@Override public boolean match(final String rule) { return rule.matches("^phone$"); }
@Test void match() { assertTrue(generator.match("phone")); assertFalse(generator.match("mobile")); }
@Override @NonNull public Predicate<E> convert(SelectorCriteria criteria) { return ext -> { var labels = ext.getMetadata().getLabels(); switch (criteria.operator()) { case Equals -> { if (labels == null || !labels.containsKey(criteria.key())) {...
@Test void shouldConvertNotEqualsCorrectly() { var criteria = new SelectorCriteria("name", Operator.NotEquals, Set.of("value1", "value2")); var predicate = convert.convert(criteria); assertNotNull(predicate); var fakeExt = new FakeExtension(); var metadata = new Metadata(); ...
static long toLong(final JsonNode object) { if (object instanceof NumericNode) { return object.asLong(); } if (object instanceof TextNode) { try { return Long.parseLong(object.textValue()); } catch (final NumberFormatException e) { throw failedStringCoercionException(SqlBas...
@Test public void shouldConvertToLongCorrectly() { final Long l = JsonSerdeUtils.toLong(JsonNodeFactory.instance.numberNode(1L)); assertThat(l, equalTo(1L)); }
public static ExpressionTree parseFilterTree(String filter) throws MetaException { return PartFilterParser.parseFilter(filter); }
@Test public void testDateColumnNameKeyword() throws MetaException { MetaException exception = assertThrows(MetaException.class, () -> PartFilterExprUtil.parseFilterTree("date='1990-11-10'")); assertTrue(exception.getMessage().contains("Error parsing partition filter")); }
public static Number jsToNumber( Object value, String classType ) { if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) { return null; } else if ( classType.equalsIgnoreCase( JS_NATIVE_JAVA_OBJ ) ) { try { // Is it a java Value class ? Value v = (Value) Context.jsToJava( value, Value.c...
@Test public void jsToNumber_Undefined() throws Exception { assertNull( JavaScriptUtils.jsToNumber( null, UNDEFINED ) ); }
@Nullable public Supplier<? extends SocketAddress> bindAddressSupplier() { return bindAddressSupplier; }
@Test void bindAddressSupplier() { assertThat(builder.build().bindAddressSupplier()).isNull(); Supplier<SocketAddress> addressSupplier = () -> new InetSocketAddress("localhost", 9527); builder.bindAddressSupplier(addressSupplier); assertThat(builder.build().bindAddressSupplier()).isEqualTo(addressSupplier); }
public static String from(Query query) { if (query instanceof SqmInterpretationsKey.InterpretationsKeySource && query instanceof QueryImplementor && query instanceof QuerySqmImpl) { QueryInterpretationCache.Key cacheKey = SqmInterpretationsKey.createInterpretationsKey((SqmInt...
@Test public void testCriteriaAPI() { doInJPA(entityManager -> { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class); Root<PostComment> postComment = criteria.from(PostComment.class);...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { metadata.set(Metadata.CONTENT_TYPE, "application/rtf"); TaggedInputStream tagged = new TaggedInputStream(stream); try { ...
@Test public void testEmbeddedLinkedDocument() throws Exception { Set<MediaType> skipTypes = new HashSet<>(); skipTypes.add(MediaType.parse("image/emf")); skipTypes.add(MediaType.parse("image/wmf")); TrackingHandler tracker = new TrackingHandler(skipTypes); try (TikaInputStr...
public static ILogger noLogger() { return new NoLogFactory.NoLogger(); }
@Test public void noLogger() { assertInstanceOf(NoLogFactory.NoLogger.class, Logger.noLogger()); }
public int max() { return size > 0 ? data[size - 1] : 0; }
@Test public void max() { SortedIntList l = new SortedIntList(5); assertEquals(0, l.max()); l.add(1); assertEquals(1, l.max()); l.add(5); assertEquals(5, l.max()); l.add(10); assertEquals(10, l.max()); }
@Override public ProviderInfo doSelect(SofaRequest invocation, List<ProviderInfo> providerInfos) { String localhost = SystemInfo.getLocalHost(); if (StringUtils.isEmpty(localhost)) { return super.doSelect(invocation, providerInfos); } List<ProviderInfo> localProviderInfo ...
@Test public void doSelect() throws Exception { LocalPreferenceLoadBalancer loadBalancer = new LocalPreferenceLoadBalancer(null); Map<Integer, Integer> cnt = new HashMap<Integer, Integer>(); int size = 20; int total = 100000; SofaRequest request = new SofaRequest(); ...
public static String getKey(String dataId, String group) { StringBuilder sb = new StringBuilder(); GroupKey.urlEncode(dataId, sb); sb.append('+'); GroupKey.urlEncode(group, sb); return sb.toString(); }
@Test public void getKeyTenantIdentifyTest() { String key = Md5ConfigUtil.getKey("DataId", "Group", "Tenant", "Identify"); Assert.isTrue(Objects.equals("DataId+Group+Tenant+Identify", key)); }
public static void displayWelcomeMessage( final int consoleWidth, final PrintWriter writer ) { final String[] lines = { "", "===========================================", "= _ _ ____ ____ =", "= | | _____ __ _| | _ \\| __ ) =", ...
@Test public void shouldOutputShortWelcomeMessageIfConsoleNotWideEnough() { // When: WelcomeMsgUtils.displayWelcomeMessage(35, realPrintWriter); // Then: assertThat(stringWriter.toString(), is("ksqlDB, Copyright 2017-2022 Confluent Inc.\n\n")); }
@Path("/.well-known/openid-federation") @GET @Produces(MEDIA_TYPE_ENTITY_STATEMENT) public Response get() { var federationEntityJwks = federationConfig.entitySigningKeys().toPublicJWKSet(); var relyingPartyJwks = federationConfig.relyingPartyKeys().toPublicJWKSet(); var now = Instant.now(); var ...
@Test void get() { var res = given() .baseUri(server.configuration().baseUri().toString()) .get("/.well-known/openid-federation") .getBody(); var body = res.asString(); var es = EntityStatementJWS.parse(body); assertEquals(ISSUER.toString(), es.body().sub...
public List<ErasureCodingPolicy> loadPolicy(String policyFilePath) { try { File policyFile = getPolicyFile(policyFilePath); if (!policyFile.exists()) { LOG.warn("Not found any EC policy file"); return Collections.emptyList(); } return loadECPolicies(policyFile); } catch (...
@Test public void testBadECCellsize() throws Exception { PrintWriter out = new PrintWriter(new FileWriter(POLICY_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<configuration>"); out.println("<layoutversion>1</layoutversion>"); out.println("<schemas>"); out.println(" <schema id=...
public void logExecution(Execution execution, Logger logger, Level level, String message, Object... args) { String finalMsg = tenantEnabled ? EXECUTION_PREFIX_WITH_TENANT + message : EXECUTION_PREFIX_NO_TENANT + message; Object[] executionArgs = tenantEnabled ? new Object[] { execution.getTe...
@Test void logExecution() { var execution = Execution.builder().namespace("namespace").flowId("flow").id("execution").build(); logService.logExecution(execution, log, Level.INFO, "Some log"); logService.logExecution(execution, log, Level.INFO, "Some log with an {}", "attribute"); }
@Override public void invoke() throws Exception { // -------------------------------------------------------------------- // Initialize // -------------------------------------------------------------------- LOG.debug(getLogString("Start registering input and output")); // i...
@Test @SuppressWarnings("unchecked") void testSortingDataSinkTask() { int keyCnt = 100; int valCnt = 20; double memoryFraction = 1.0; super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE); super.addInput(new UniformRecordGenerator(keyCnt, valCnt, true), 0); ...
@Override public Object getInitialAggregatedValue(Object rawValue) { CpcUnion cpcUnion = new CpcUnion(_lgK); if (rawValue instanceof byte[]) { // Serialized Sketch byte[] bytes = (byte[]) rawValue; cpcUnion.update(deserializeAggregatedValue(bytes)); } else if (rawValue instanceof byte[][]) { /...
@Test public void getInitialValueShouldSupportMultiValueTypes() { DistinctCountCPCSketchValueAggregator agg = new DistinctCountCPCSketchValueAggregator(Collections.emptyList()); Integer[] ints = {12345}; assertEquals(toSketch(agg.getInitialAggregatedValue(ints)).getEstimate(), 1.0); Long[] longs = {12...