focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static IndexIterationPointer union(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) { assert left.isDescending() == right.isDescending(); assert left.getLastEntryKeyData() == null && right.lastEntryKeyData == null : "Can merge only initial pointers"; Tuple2<...
@Test void unionAdjacentSingletonRange() { assertThat(union(pointer(singleton(5)), pointer(singleton(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(singleton(5))); assertThat(union(pointer(singleton(5)), pointer(greaterThan(5)), OrderedIndexStore...
@Override public void reconcileExecutionDeployments( ResourceID taskExecutorHost, ExecutionDeploymentReport executionDeploymentReport, Map<ExecutionAttemptID, ExecutionDeploymentState> expectedDeployedExecutions) { final Set<ExecutionAttemptID> unknownExecutions = ...
@Test void testMatchingDeployments() { TestingExecutionDeploymentReconciliationHandler handler = new TestingExecutionDeploymentReconciliationHandler(); DefaultExecutionDeploymentReconciler reconciler = new DefaultExecutionDeploymentReconciler(handler); Resou...
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 testToApplicationsIfNotNullReturnApplicationsFromInstances() { InstanceInfo instanceInfo1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED).getByInstanceId("foo"); InstanceInfo instanceInfo2 = createSingleInstanceApp("bar", "bar", ...
@Override public List<Object> getParameters() { List<Object> result = new LinkedList<>(); for (int i = 0; i < parameterBuilders.size(); i++) { result.addAll(getParameters(i)); } result.addAll(genericParameterBuilder.getParameters()); return result; }
@Test void assertGetParametersWithGenericParameters() { GroupedParameterBuilder actual = new GroupedParameterBuilder(createGroupedParameters(), createGenericParameters()); assertThat(actual.getParameters(), is(Arrays.<Object>asList(3, 4, 5, 6, 7, 8))); assertThat(actual.getGenericParameterBu...
public Status listSnapshots(List<String> snapshotNames) { // list with prefix: // eg. __starrocks_repository_repo_name/__ss_* String listPath = Joiner.on(PATH_DELIMITER).join(location, joinPrefix(prefixRepo, name), PREFIX_SNAPSHOT_DIR) + "*"; List<RemoteFile> result = Lis...
@Test public void testListSnapshots() { new Expectations() { { storage.list(anyString, (List<RemoteFile>) any); minTimes = 0; result = new Delegate() { public Status list(String remotePath, List<RemoteFile> result) { ...
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull25() { // Arrange final int type = 25; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Delete_rows_v1", actual); }
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"}) public static boolean isScalablePushQuery( final Statement statement, final KsqlExecutionContext ksqlEngine, final KsqlConfig ksqlConfig, final Map<String, Object> overrides ) { if (!isPushV2Enabled(ksqlConfig, ov...
@Test public void isScalablePushQuery_false_hasHaving() { try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) { // When: expectIsSPQ(ColumnName.of("foo"), columnExtractor); when(query.getHaving()).thenReturn(Optional.of(new IntegerLiteral(1))); // Then: ...
public static void checkMapConfig(Config config, MapConfig mapConfig, SplitBrainMergePolicyProvider mergePolicyProvider) { checkNotNativeWhenOpenSource(mapConfig.getInMemoryFormat()); checkNotBitmapIndexWhenNativeMemory(mapConfig.getInMemoryFormat(), mapConfig.getI...
@Test public void checkMapConfig_OBJECT() { checkMapConfig(new Config(), getMapConfig(OBJECT), splitBrainMergePolicyProvider); }
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { try { final FilesApi files = new FilesApi(session.getClient()); status.setResponse(new StoregateAttributesFinderFeature(session, fileid).toAttributes(files.filesUpdateFile(fi...
@Test public void testSetTimestampDirectory() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(new Path( String.format("/My files/%s", new AlphanumericRandomStringService().rando...
public Metric(final MetricType type, final String name, final String document, final List<String> labels) { this.type = type; this.name = name; this.document = document; this.labels = labels; }
@Test public void testMetric() { labels = new ArrayList<>(); labels.add("shenyu_request_total"); metric = new Metric(MetricType.COUNTER, NAME, DOCUMENT, labels); Assertions.assertEquals(metric.getType(), MetricType.COUNTER); Assertions.assertEquals(metric.getName(), "testName...
@SuppressWarnings("UnstableApiUsage") @Override public Stream<ColumnName> resolveSelectStar( final Optional<SourceName> sourceName ) { final Stream<ColumnName> names = Stream.of(left, right) .flatMap(JoinNode::getPreJoinProjectDataSources) .filter(s -> !sourceName.isPresent() || sourceNa...
@Test public void shouldResolveUnaliasedSelectStarWithMultipleJoinsOnLeftSide() { // Given: final JoinNode inner = new JoinNode(new PlanNodeId("foo"), LEFT, joinKey, true, right, right2, empty(), "KAFKA"); final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, ...
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldLeaveListAndPrintStatementsAsTheyAre() { Assert.assertEquals("LIST PROPERTIES;", anon.anonymize("LIST PROPERTIES;")); Assert.assertEquals("SHOW PROPERTIES;", anon.anonymize("SHOW PROPERTIES;")); Assert.assertEquals("LIST TOPICS;", anon.anonymize("LIST TOPICS;")); Assert.assertE...
@Override public boolean test(Pickle pickle) { URI picklePath = pickle.getUri(); if (!lineFilters.containsKey(picklePath)) { return true; } for (Integer line : lineFilters.get(picklePath)) { if (Objects.equals(line, pickle.getLocation().getLine()) ...
@Test void matches_scenario() { LinePredicate predicate = new LinePredicate(singletonMap( featurePath, singletonList(3))); assertTrue(predicate.test(firstPickle)); assertTrue(predicate.test(secondPickle)); assertTrue(predicate.test(thirdPickle)); asser...
@Override public String telnet(Channel channel, String message) { if (StringUtils.isEmpty(message)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(mess...
@Test void testChangeCancel() throws RemotingException { String result = change.telnet(mockChannel, ".."); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); }
@Override public String pluginNamed() { return PluginEnum.KEY_AUTH.getName(); }
@Test public void testPluginNamed() { assertEquals(keyAuthPluginDataHandler.pluginNamed(), PluginEnum.KEY_AUTH.getName()); }
@NonNull public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) { Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi...
@Test public void testPermutorForRule_DURATION_ASC() { Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.DURATION_SHORT_LONG); List<FeedItem> itemList = getTestList(); assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting permutor.reorder(itemList); ...
@Override public void encode(Event event, OutputStream output) throws IOException { String outputString = (format == null ? JSON_MAPPER.writeValueAsString(event.getData()) : StringInterpolation.evaluate(event, format)) + delimiter; output.write(outputS...
@Test public void testEncodeWithUtf8() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String delimiter = "z"; String message = new String("München 安装中文输入法".getBytes(), Charset.forName("UTF-8")); Map<String, Object> config = new HashMap<>(); ...
public static Map<String, String> getSegmentSourcesMap(final SegmentCompilationDTO segmentCompilationDTO, final List<KiePMMLModel> nestedModels) { logger.debug(GET_SEGMENT, segmentCompilationDTO.getSegment()); final KiePMMLModel nestedModel = ...
@Test void getSegmentSourcesMap() { final Segment segment = MINING_MODEL.getSegmentation().getSegments().get(0); final List<KiePMMLModel> nestedModels = new ArrayList<>(); final CommonCompilationDTO<MiningModel> source = CommonCompilationDTO.fromGeneratedPackageNameAndFields(...
public ProtocolBuilder exchanger(String exchanger) { this.exchanger = exchanger; return getThis(); }
@Test void exchanger() { ProtocolBuilder builder = new ProtocolBuilder(); builder.exchanger("mockexchanger"); Assertions.assertEquals("mockexchanger", builder.build().getExchanger()); }
public <T extends ShardingSphereRule> Optional<T> findSingleRule(final Class<T> clazz) { Collection<T> foundRules = findRules(clazz); return foundRules.isEmpty() ? Optional.empty() : Optional.of(foundRules.iterator().next()); }
@Test void assertFindSingleRule() { assertTrue(ruleMetaData.findSingleRule(ShardingSphereRuleFixture.class).isPresent()); }
@Override public DefaultJwtRuleHandle parseHandleJson(final String handleJson) { try { return GsonUtils.getInstance().fromJson(handleJson, DefaultJwtRuleHandle.class); } catch (Exception exception) { LOG.error("Failed to parse json , please check json format", exception); ...
@Test public void testParseHandleJson() { String handleJson = "{\"converter\":[{\"jwtVal\":\"sub\",\"headerVal\":\"id\"}]}"; assertThat(defaultJwtConvertStrategy.parseHandleJson(handleJson), notNullValue(DefaultJwtRuleHandle.class)); assertThat(defaultJwtConvertStrategy.parseHandleJson(null)...
public SearchJob executeSync(String searchId, SearchUser searchUser, ExecutionState executionState) { return searchDomain.getForUser(searchId, searchUser) .map(s -> executeSync(s, searchUser, executionState)) .orElseThrow(() -> new NotFoundException("No search found with id <" + ...
@Test void appliesQueryStringDecorators() { final SearchUser searchUser = TestSearchUser.builder() .allowStream("foo") .build(); final Search search = Search.builder() .queries(ImmutableSet.of( Query.builder() ...
@Override public long extract(final ConsumerRecord<Object, Object> record, final long previousTimestamp) { try { return delegate.extract(record, previousTimestamp); } catch (final RuntimeException e) { return handleFailure(record.key(), record.value(), e); } }
@Test public void shouldLogExceptionsAndNotFailOnExtractFromRecord() { // Given: final KsqlException e = new KsqlException("foo"); final LoggingTimestampExtractor extractor = new LoggingTimestampExtractor( (k, v) -> { throw e; }, logger, false ); // When:...
@Override public Double getValue() { return getRatio().getValue(); }
@Test public void handlesDivideByZeroIssues() { final RatioGauge divByZero = new RatioGauge() { @Override protected Ratio getRatio() { return Ratio.of(100, 0); } }; assertThat(divByZero.getValue()) .isNaN(); }
@Override public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) { return null; }
@Test void assertGetProcedures() { assertNull(metaData.getProcedures("", "", "")); }
@Deprecated public void sendMessageBack(MessageExt msg, int delayLevel, final String brokerName) throws RemotingException, MQBrokerException, InterruptedException, MQClientException { sendMessageBack(msg, delayLevel, brokerName, null); }
@Test public void testSendMessageBack() throws InterruptedException, MQClientException, MQBrokerException, RemotingException { defaultMQPushConsumerImpl.sendMessageBack(createMessageExt(), 1, createMessageQueue()); verify(mqClientAPIImpl).consumerSendMessageBack( eq(defaultBrokerAddr...
public boolean addToken(Token<? extends TokenIdentifier> token) { return (token != null) ? addToken(token.getService(), token) : false; }
@SuppressWarnings("unchecked") // from Mockito mocks @Test (timeout = 30000) public <T extends TokenIdentifier> void testAddToken() throws Exception { UserGroupInformation ugi = UserGroupInformation.createRemoteUser("someone"); Token<T> t1 = mock(Token.class); Token<T> t2 = mock(Token.cla...
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) { HttpHeaders inHeaders = in.headers(); final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size()); if (in instanceof HttpRequest) { HttpRequest request = (HttpRequest) in; ...
@Test public void stripTEHeadersAccountsForValueSimilarToTrailers() { HttpHeaders inHeaders = new DefaultHttpHeaders(); inHeaders.add(TE, TRAILERS + "foo"); Http2Headers out = new DefaultHttp2Headers(); HttpConversionUtil.toHttp2Headers(inHeaders, out); assertFalse(out.contai...
@Udf public Long trunc(@UdfParameter final Long val) { return val; }
@Test public void shouldTruncateLong() { assertThat(udf.trunc(123L), is(123L)); }
void updateActivityState(DeviceId deviceId, DeviceStateData stateData, long lastReportedActivity) { log.trace("updateActivityState - fetched state {} for device {}, lastReportedActivity {}", stateData, deviceId, lastReportedActivity); if (stateData != null) { save(deviceId, LAST_ACTIVITY_TIM...
@Test public void givenStateDataIsNull_whenUpdateActivityState_thenShouldCleanupDevice() { // GIVEN service.deviceStates.put(deviceId, deviceStateDataMock); // WHEN service.updateActivityState(deviceId, null, System.currentTimeMillis()); // THEN assertThat(service.d...
public Optional<PluginMatchingResult<ServiceFingerprinter>> getServiceFingerprinter( NetworkService networkService) { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.SERVICE_FINGERPRINT)) .filter(entry -> hasMatchingServiceName(networkService,...
@Test public void getServiceFingerprinter_whenFingerprinterNotAnnotated_returnsEmpty() { NetworkService httpService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtocol.TCP) .setServi...
public static List<URL> parseConfigurators(String rawConfig) { // compatible url JsonArray, such as [ "override://xxx", "override://xxx" ] List<URL> compatibleUrls = parseJsonArray(rawConfig); if (CollectionUtils.isNotEmpty(compatibleUrls)) { return compatibleUrls; } ...
@Test void parseConfiguratorsServiceMultiAppsTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); ...
public void setWriteTimeout(int writeTimeout) { this.writeTimeout = writeTimeout; }
@Test public void testErrorCodeForbidden() throws IOException { MockLowLevelHttpResponse[] responses = createMockResponseWithStatusCode( 403, // Non-retryable error. 200); // Shouldn't happen. when(mockLowLevelRequest.execute()).thenReturn(responses[0], responses[1]); try...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STAT...
@Test public void testLiteralWithPercent() throws ScanException { { List<Token> tl = new TokenStream("hello\\%world").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(new Token(Token.LITERAL, "hello%world")); assertEquals(witness, tl); ...
@Override public List<MicroServiceInstance> getServerList(String serviceId) { if (!isRegistered.get()) { LOGGER.warning("Query instance must be at the stage that finish registry!"); return Collections.emptyList(); } if (serviceId == null) { // Unable to pe...
@Test public void getServerList() { Assert.assertTrue(registerCenterService.getServerList("test").isEmpty()); }
static File getFileFromResource(URL retrieved) throws IOException { logger.debug("getFileFromResource {}", retrieved); File toReturn = new MemoryFile(retrieved); logger.debug(TO_RETURN_TEMPLATE, toReturn); logger.debug(TO_RETURN_GETABSOLUTEPATH_TEMPLATE, toReturn.getAbsolutePath()); ...
@Test void getFileFromResource() throws IOException { URL resourceUrl = getResourceUrl(); File retrieved = MemoryFileUtils.getFileFromResource(resourceUrl); assertThat(retrieved).isNotNull(); assertThat(retrieved).isInstanceOf(MemoryFile.class); assertThat(retrieved).canRead(...
public Map<String, Object> sanitizeConnectorConfig(@Nullable Map<String, Object> original) { var result = new HashMap<String, Object>(); //null-values supporting map! if (original != null) { original.forEach((k, v) -> result.put(k, sanitize(k, v))); } return result; }
@Test void sanitizeConnectorConfigDoNotFailOnNullableValues() { Map<String, Object> originalConfig = new HashMap<>(); originalConfig.put("password", "secret"); originalConfig.put("asIs", "normal"); originalConfig.put("nullVal", null); var sanitizedConfig = new KafkaConfigSanitizer(true, List.of()...
protected UrlData extractUrlData(String nvdDataFeedUrl) { String url; String pattern = null; if (nvdDataFeedUrl.endsWith(".json.gz")) { final int lio = nvdDataFeedUrl.lastIndexOf("/"); pattern = nvdDataFeedUrl.substring(lio + 1); url = nvdDataFeedUrl.substring...
@Test public void testExtractUrlData() { String nvdDataFeedUrl = "https://internal.server/nist/nvdcve-{0}.json.gz"; NvdApiDataSource instance = new NvdApiDataSource(); String expectedUrl = "https://internal.server/nist/"; String expectedPattern = "nvdcve-{0}.json.gz"; NvdApiD...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void jvm32() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/jvm_32bit.txt")), CrashReportAnalyzer.Rule.JVM_32BIT); }
public DataCache<List<MavenArtifact>> getCentralCache() { try { final ICompositeCacheAttributes attr = new CompositeCacheAttributes(); attr.setUseDisk(true); attr.setUseLateral(false); attr.setUseRemote(false); final CacheAccess<String, List<MavenArtif...
@Test public void testGetCache() throws IOException { DataCacheFactory instance = new DataCacheFactory(getSettings()); DataCache<List<MavenArtifact>> result = instance.getCentralCache(); assertNotNull(result); File f = new File(getSettings().getDataDirectory(), "cache"); ass...
public ScalarFn loadScalarFunction(List<String> functionPath, String jarPath) { String functionFullName = String.join(".", functionPath); try { FunctionDefinitions functionDefinitions = loadJar(jarPath); if (!functionDefinitions.scalarFunctions().containsKey(functionPath)) { throw new Illega...
@Test public void testJarMissingUdfProviderThrowsProviderNotFoundException() { JavaUdfLoader udfLoader = new JavaUdfLoader(); thrown.expect(ProviderNotFoundException.class); thrown.expectMessage(String.format("No UdfProvider implementation found in %s.", emptyJarPath)); // Load from an inhabited jar f...
@SuppressWarnings("all") public <T> T searchStateValue(String stateName, T defaultValue) { T result = null; for (ModuleState each : getAllModuleStates()) { if (each.getStates().containsKey(stateName)) { result = (T) each.getStates().get(stateName); break; ...
@Test void testSearchStateValue() { assertEquals("test", ModuleStateHolder.getInstance().searchStateValue("test", "aaa")); assertEquals("aaa", ModuleStateHolder.getInstance().searchStateValue("non-exist", "aaa")); }
public static Schema inferSchema(Object value) { if (value instanceof String) { return Schema.STRING_SCHEMA; } else if (value instanceof Boolean) { return Schema.BOOLEAN_SCHEMA; } else if (value instanceof Byte) { return Schema.INT8_SCHEMA; } else if (...
@Test public void shouldInferStructSchema() { Struct struct = new Struct(SchemaBuilder.struct().build()); Schema structSchema = Values.inferSchema(struct); assertEquals(struct.schema(), structSchema); }
public BrokerStatsData viewBrokerStatsData(String brokerAddr, String statsName, String statsKey, long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException { ViewBrokerStatsDataRequestHeader requestHeader =...
@Test public void assertViewBrokerStatsData() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); BrokerStatsData responseBody = new BrokerStatsData(); responseBody.setStatsDay(new BrokerStatsItem()); setResponseBody(responseBody); BrokerStat...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testSlaughterActivate() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", ACTIVATE_BRACELET_OF_SLAUGHTER, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_SLAU...
protected static String buildRequestBody(String query, String operationName, JsonObject variables) { JsonObject jsonObject = new JsonObject(); jsonObject.put("query", query); jsonObject.put("operationName", operationName); jsonObject.put("variables", variables != null ? variables : new J...
@Test public void shouldBuildRequestBodyWithQueryOperationNameAndVariables() { String query = "queryText"; String operationName = "queryName"; JsonObject variables = new JsonObject(); variables.put("key1", "value1"); variables.put("key2", "value2"); String body = Gra...
private static void serializeProperties(CheckpointProperties properties, DataOutputStream dos) throws IOException { new ObjectOutputStream(dos).writeObject(properties); // closed outside }
@Test void testSerializeProperties() throws IOException { CheckpointMetadata metadata = new CheckpointMetadata( 1L, emptyList(), emptyList(), CheckpointProperties.forSavepoint(false, SavepointForm...
public static BytesInput fromZigZagVarInt(int intValue) { int zigZag = (intValue << 1) ^ (intValue >> 31); return new UnsignedVarIntBytesInput(zigZag); }
@Test public void testFromZigZagVarInt() throws IOException { int value = RANDOM.nextInt() % Short.MAX_VALUE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); BytesUtils.writeZigZagVarInt(value, baos); byte[] data = baos.toByteArray(); Supplier<BytesInput> factory = () -> BytesInput.fromZ...
public synchronized void addFunction(Function function) throws UserException { addFunction(function, false); }
@Test public void testAddFunction() throws UserException { // Add addIntInt function to database FunctionName name = new FunctionName(null, "addIntInt"); name.setDb(db.getCatalogName()); final Type[] argTypes = {Type.INT, Type.INT}; Function f = new Function(name, argTypes, T...
public void convertLambdas() { if (isParallel) { convertLambdasWithForkJoinPool(); } else { convertLambdasWithStream(); } }
@Test public void convertPatternLambda() throws Exception { CompilationUnit inputCU = parseResource("org/drools/model/codegen/execmodel/util/lambdareplace/PatternTestHarness.java"); CompilationUnit clone = inputCU.clone(); new ExecModelLambdaPostProcessor("mypackage", "rulename", new Array...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final Map<String, Object> event; try { event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT); } catch (IOException e) { ...
@Test public void decodeMessagesHandlesWinlogbeatMessages() throws Exception { final Message message = codec.decode(messageFromJson("winlogbeat.json")); assertThat(message).isNotNull(); assertThat(message.getSource()).isEqualTo("example.local"); assertThat(message.getTimestamp()).isE...
public void createMapping(Mapping mapping, boolean replace, boolean ifNotExists, SqlSecurityContext securityContext) { Mapping resolved = resolveMapping(mapping, securityContext); String name = resolved.name(); if (ifNotExists) { relationsStorage.putIfAbsent(name, resolved); ...
@Test public void when_createsDuplicateMapping_then_throws() { // given Mapping mapping = mapping(); given(connectorCache.forType(mapping.connectorType())).willReturn(connector); given(connector.resolveAndValidateFields(nodeEngine, new SqlExternalResource(mapping.ext...
private RemotingCommand getAllConsumerOffset(ChannelHandlerContext ctx, RemotingCommand request) { final RemotingCommand response = RemotingCommand.createResponseCommand(null); String content = this.brokerController.getConsumerOffsetManager().encode(); if (content != null && content.length() > ...
@Test public void testGetAllConsumerOffset() throws RemotingCommandException { consumerOffsetManager = mock(ConsumerOffsetManager.class); when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager); ConsumerOffsetManager consumerOffset = new ConsumerOffsetManager(); ...
@Nonnull @Override public Sketch getResult() { return unionAll(); }
@Test public void testUnionWithEmptyInput() { ThetaSketchAccumulator accumulator = new ThetaSketchAccumulator(_setOperationBuilder, 3); ThetaSketchAccumulator emptyAccumulator = new ThetaSketchAccumulator(_setOperationBuilder, 3); accumulator.merge(emptyAccumulator); Assert.assertTrue(accumulator.is...
public Set<Integer> toLines() { Set<Integer> lines = new LinkedHashSet<>(to - from + 1); for (int index = from; index <= to; index++) { lines.add(index); } return lines; }
@Test public void shouldConvertLineRangeToLines() { LineRange range = new LineRange(12, 15); assertThat(range.toLines()).containsOnly(12, 13, 14, 15); }
@Override public ConfigInfoBetaWrapper findConfigInfo4Beta(final String dataId, final String group, final String tenant) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSource...
@Test void testFindConfigInfo4Beta() { String dataId = "dataId456789"; String group = "group4567"; String tenant = "tenant56789o0"; //mock exist beta ConfigInfoBetaWrapper mockedConfigInfoStateWrapper = new ConfigInfoBetaWrapper(); mockedConfigInfoStateWrapper.setData...
@Override public List<Intent> compile(LinkCollectionIntent intent, List<Intent> installable) { SetMultimap<DeviceId, PortNumber> inputPorts = HashMultimap.create(); SetMultimap<DeviceId, PortNumber> outputPorts = HashMultimap.create(); Map<ConnectPoint, Identifier<?>> labels = ImmutableMap....
@Test public void testCompile() { sut.activate(); List<Intent> compiled = sut.compile(intent, Collections.emptyList()); assertThat(compiled, hasSize(1)); assertThat("key is inherited", compiled.stream().map(Intent::key).collect(Collectors.toList()), ...
public static String convertLikePatternToRegex(final String pattern) { String result = pattern; if (pattern.contains("_")) { result = SINGLE_CHARACTER_PATTERN.matcher(result).replaceAll("$1."); result = SINGLE_CHARACTER_ESCAPE_PATTERN.matcher(result).replaceAll("_"); } ...
@Test void assertConvertLikePatternToRegexWhenContainsPattern() { assertThat(RegexUtils.convertLikePatternToRegex("sharding_db"), is("sharding.db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding%db"), is("sharding.*db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding...
public static byte[] doubleToBytesBE(double d, byte[] bytes, int off) { return longToBytesBE(Double.doubleToLongBits(d), bytes, off); }
@Test public void testDoubleToBytesBE() { assertArrayEquals(DOUBLE_PI_BE , ByteUtils.doubleToBytesBE(Math.PI, new byte[8], 0)); }
public static IntArrayList reverse(IntArrayList list) { final int[] buffer = list.buffer; int tmp; for (int start = 0, end = list.size() - 1; start < end; start++, end--) { // swap the values tmp = buffer[start]; buffer[start] = buffer[end]; buffer...
@Test public void testReverse() { assertEquals(from(), ArrayUtil.reverse(from())); assertEquals(from(1), ArrayUtil.reverse(from(1))); assertEquals(from(9, 5), ArrayUtil.reverse(from(5, 9))); assertEquals(from(7, 1, 3), ArrayUtil.reverse(from(3, 1, 7))); assertEquals(from(4, 3...
public Map<MetricId, Number> metrics() { return metrics; }
@Test public void builder_can_retain_subset_of_metrics() { MetricsPacket packet = new MetricsPacket.Builder(toServiceId("foo")) .putMetrics(List.of( new Metric(toMetricId("remove"), 1), new Metric(toMetricId("keep"), 2))) .retai...
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; ...
@Test public void decodeFailsWithEmptyMessage() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"example.org\"," + "\"message\": \"\"" + "}"; final RawMessage rawMessage = new RawMessage(json.getBytes...
public static boolean deleteFile(String path, String fileName) { File file = Paths.get(path, fileName).toFile(); if (file.exists()) { return file.delete(); } return false; }
@Test void testDeleteFile() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); }
@Override public String toString() { return "PathSpecSet{" + (_allInclusive ? "all inclusive" : StringUtils.join(_pathSpecs, ',')) + "}"; }
@Test public void testToString() { Assert.assertEquals(PathSpecSet.of(THREE_FIELD_MODEL_FIELD1).toString(), "PathSpecSet{/field1}"); Assert.assertEquals(PathSpecSet.allInclusive().toString(), "PathSpecSet{all inclusive}"); }
public static S3SignResponse fromJson(String json) { return JsonUtil.parse(json, S3SignResponseParser::fromJson); }
@Test public void missingFields() { assertThatThrownBy(() -> S3SignResponseParser.fromJson("{}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing string: uri"); assertThatThrownBy( () -> S3SignResponseParser.fromJson( ...
public T findOne(Bson filter) throws MongoException { return delegate.findOne(filter); }
@Test void findOne() { final var collection = jacksonCollection("simple", Simple.class); final List<Simple> items = List.of( new Simple("000000000000000000000001", "foo"), new Simple("000000000000000000000002", "bar") ); collection.insert(items); ...
@Override public String select(List<String> columns, List<String> where) { StringBuilder sql = new StringBuilder(); String method = "SELECT "; sql.append(method); for (int i = 0; i < columns.size(); i++) { sql.append(columns.get(i)); if (i == columns.size() - ...
@Test void testSelect() { String sql = abstractMapper.select(Arrays.asList("id", "name"), Arrays.asList("id")); assertEquals("SELECT id,name FROM tenant_info WHERE id = ?", sql); }
@Override public SCMUploaderNotifyResponse notify(SCMUploaderNotifyRequest request) throws YarnException, IOException { SCMUploaderNotifyResponse response = recordFactory.newRecordInstance(SCMUploaderNotifyResponse.class); // TODO (YARN-2774): proper security/authorization needs to be implement...
@Test void testNotify_entryExists_differentName() throws Exception { long rejected = SharedCacheUploaderMetrics.getInstance().getRejectUploads(); store.addResource("key1", "foo.jar"); SCMUploaderNotifyRequest request = recordFactory.newRecordInstance(SCMUploaderNotifyRequest.class); ...
public List<String> toPrefix(String in) { List<String> tokens = buildTokens(alignINClause(in)); List<String> output = new ArrayList<>(); List<String> stack = new ArrayList<>(); for (String token : tokens) { if (isOperand(token)) { if (token.equals(")")) { ...
@Test public void testComplexStatement() { String query = "age > 5 AND ( ( ( active = true ) AND ( age = 23 ) ) OR age > 40 ) AND ( salary > 10 ) OR age = 10"; List<String> list = parser.toPrefix(query); assertEquals(Arrays.asList("age", "5", ">", "active", "true", "=", "age", "23", "=", "AN...
public static OffsetBasedPageRequest fromString(String offsetBasedPageRequestAsString) { if (isNullOrEmpty(offsetBasedPageRequestAsString)) return null; String order = lenientSubstringBetween(offsetBasedPageRequestAsString, "order=", "&"); String offset = lenientSubstringBetween(offsetBasedPage...
@Test void testOffsetBasedPageRequestWithEmptyString() { OffsetBasedPageRequest offsetBasedPageRequest = OffsetBasedPageRequest.fromString(""); assertThat(offsetBasedPageRequest).isNull(); }
@Override public Num getValue(int index) { return values.get(index); }
@Test public void cashFlowShortSellWith20PercentLoss() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 90, 100, 110, 120); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(1, sampleBarSeries), Trade.buyAt(3, sampleBarSeries)); CashFlow cashFlow =...
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData, TypeReference<T> responseFormat) { return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null); }
@Test public void testRuntimeExceptionCausesInternalServerError() { when(httpClient.newRequest(anyString())).thenThrow(new RuntimeException()); ConnectRestException e = assertThrows(ConnectRestException.class, () -> httpRequest( httpClient, MOCK_URL, TEST_METHOD, TEST_TYPE, TEST_SIG...
public PlanNodeStatsEstimate addStatsAndSumDistinctValues(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right) { return addStats(left, right, RangeAdditionStrategy.ADD_AND_SUM_DISTINCT); }
@Test public void testAddTotalSize() { PlanNodeStatsEstimate unknownStats = statistics(NaN, NaN, NaN, NaN, StatisticRange.empty()); PlanNodeStatsEstimate first = statistics(NaN, 10, NaN, NaN, StatisticRange.empty()); PlanNodeStatsEstimate second = statistics(NaN, 20, NaN, NaN, StatisticR...
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 testCannotUpgradeToLowerVersion() { FeatureControlManager manager = TEST_MANAGER_BUILDER1.build(); assertEquals(ControllerResult.of(Collections.emptyList(), singletonMap(MetadataVersion.FEATURE_NAME, new ApiError(Errors.INVALID_UPDATE_VERSION, "Invalid u...
public String getContractAddress() { return contractAddress; }
@Test public void testGetContractAddress() { assertEquals(ADDRESS, contract.getContractAddress()); }
@VisibleForTesting @Override public boolean allocateSlot( int index, JobID jobId, AllocationID allocationId, Duration slotTimeout) { return allocateSlot(index, jobId, allocationId, defaultSlotResourceProfile, slotTimeout); }
@Test void testAllocateSlot() throws Exception { final JobID jobId = new JobID(); final AllocationID allocationId = new AllocationID(); try (final TaskSlotTable<TaskSlotPayload> taskSlotTable = createTaskSlotTableWithAllocatedSlot( jobId, allocationId,...
public static JSONObject parseObj(String jsonStr) { return new JSONObject(jsonStr); }
@Test public void toJsonStrTest3() { // 验证某个字段为JSON字符串时转义是否规范 final JSONObject object = new JSONObject(true); object.set("name", "123123"); object.set("value", "\\"); object.set("value2", "</"); final HashMap<String, String> map = MapUtil.newHashMap(); map.put("user", object.toString()); final JSONOb...
public Set<String> getSources() { return Collections.unmodifiableSet(sources); }
@Test public void testIterationOrder() { String[] hosts = new String[]{"primary", "fallback", "last-resort"}; ConfigSourceSet css = new ConfigSourceSet(hosts); Set<String> sources = css.getSources(); assertEquals(hosts.length, sources.size()); int i = 0; for (String ...
public boolean hasAdminOrViewPermissions(final CaseInsensitiveString userName, List<Role> memberRoles) { return isUserAnAdmin(userName, memberRoles) || isViewUser(userName, memberRoles); }
@Test public void shouldReturnFalseForUserNotInAdminOrViewConfig() { CaseInsensitiveString viewUser = new CaseInsensitiveString("view"); Authorization authorization = new Authorization(); assertThat(authorization.hasAdminOrViewPermissions(viewUser, null), is(false)); }
public Map<String, Object> convertValue(final Object entity, final Class<?> entityClass) { if (entityClass.equals(String.class)) { return Collections.singletonMap("data", objectMapper.convertValue(entity, String.class)); } else if (!entityClass.equals(Void.class) && !entityClass.equals(void....
@Test public void returnsNullOnVoidEntityClass() { assertNull(toTest.convertValue(new Object(), Void.class)); assertNull(toTest.convertValue("Lalala", void.class)); }
public Ce.Task formatActivity(DbSession dbSession, CeActivityDto dto, @Nullable String scannerContext) { return formatActivity(dto, DtoCache.forActivityDtos(dbClient, dbSession, singletonList(dto)), scannerContext); }
@Test public void formatActivity_with_both_error_message_and_stacktrace() { CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null) .setErrorMessage("error msg") .setErrorStacktrace("error stacktrace") .setErrorType("anErrorType"); Ce.Task task = underTe...
@Override public void publish(ScannerReportWriter writer) { Optional<String> targetBranch = getTargetBranch(); if (targetBranch.isPresent()) { Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); int count = writeChangedLines(scmConfiguration.provider(), writer, targetBranch.get()); ...
@Test public void skip_if_scm_is_disabled() { when(scmConfiguration.isDisabled()).thenReturn(true); publisher.publish(writer); verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider); assertNotPublished(); }
@Override protected int command() { if (!validateConfigFilePresent()) { return 1; } final MigrationConfig config; try { config = MigrationConfig.load(getConfigFile()); } catch (KsqlException | MigrationException e) { LOGGER.error(e.getMessage()); return 1; } retur...
@Test public void shouldApplyUntilVersion() throws Exception { // Given: command = PARSER.parse("-u", "2"); createMigrationFile(1, NAME, migrationsDir, COMMAND); createMigrationFile(2, NAME, migrationsDir, COMMAND); // extra migration to ensure only the first two are applied createMigrationFil...
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testAnalysis() throws Exception { File f = BaseTest.getResourceAsFile(this, "log4net.dll"); Dependency d = new Dependency(f); analyzer.analyze(d, null); assertTrue(d.contains(EvidenceType.VERSION, new Evidence("PE Header", "FileVersion", "1.2.13.0", Confidence.HIGH...
public static Builder builder() { return new Builder(); }
@Test public void embeddedTcp() { final ByteBuf pcapBuffer = Unpooled.buffer(); final ByteBuf payload = Unpooled.wrappedBuffer("Meow".getBytes()); InetSocketAddress serverAddr = new InetSocketAddress("1.1.1.1", 1234); InetSocketAddress clientAddr = new InetSocketAddress("2.2.2.2", 3...
@ProcessElement public void processElement(ProcessContext c) throws IOException, InterruptedException { Instant firstInstant = c.sideInput(firstInstantSideInput); T element = c.element(); BackOff backoff = fluentBackoff.backoff(); while (true) { Instant instant = Instant.now(); int maxOps...
@Test public void testRampupThrottler() throws Exception { Map<Duration, Integer> rampupSchedule = ImmutableMap.<Duration, Integer>builder() .put(Duration.ZERO, 500) .put(Duration.millis(1), 0) .put(Duration.standardSeconds(1), 500) .put(Duration.standardSec...
@Override public ByteBuf copy() { return copy(readerIndex, readableBytes()); }
@Test public void testCopyAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().copy(); } }); }
@Override public String toString() { return "[" + from + "-" + to + "]"; }
@Test public void testToString() { assertThat(new LineRange(12, 15)).hasToString("[12-15]"); }
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_NativeJavaObject_Double() throws Exception { Scriptable value = getDoubleValue(); Number number = JavaScriptUtils.jsToNumber( value, JAVA_OBJECT ); assertEquals( DOUBLE_ONE, number ); }
@Override public int run(String[] args) throws Exception { try { webServiceClient = WebServiceClient.getWebServiceClient().createClient(); return runCommand(args); } finally { if (yarnClient != null) { yarnClient.close(); } if (webServiceClient != null) { webServi...
@Test (timeout = 5000) public void testWithExclusiveArguments() throws Exception { ApplicationId appId1 = ApplicationId.newInstance(0, 1); LogsCLI cli = createCli(); // Specify show_container_log_info and show_application_log_info // at the same time int exitCode = cli.run(new String[] {"-applica...
@Override public ExecutionMode getExecutionMode() { return jobType == JobType.STREAMING ? ExecutionMode.STREAMING : ExecutionMode.BATCH; }
@Test void testGetExecutionMode() { DefaultJobInfo batchJob = createDefaultJobInfo(JobType.BATCH); assertThat(batchJob.getExecutionMode()).isEqualTo(JobInfo.ExecutionMode.BATCH); DefaultJobInfo streamingJob = createDefaultJobInfo(JobType.STREAMING); assertThat(streamingJob.getExecut...
public long toLong(String name) { return toLong(name, 0); }
@Test public void testToLong_String() { System.out.println("toLong"); long expResult; long result; Properties props = new Properties(); props.put("value1", "12345678900"); props.put("value2", "-9000001"); props.put("empty", ""); props.put("str", "abc"...
public static String getMethodName(final String methodName) { return "promise_" + methodName; }
@Test public void testGetMethodName() { assertEquals("promise_methodName", PrxInfoUtil.getMethodName("methodName")); }
@POST @Path(RMWSConsts.SCHEDULER_CONF_VALIDATE) @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public synchronized Response validateAndGetSchedulerConfiguratio...
@Test public void testValidateAndGetSchedulerConfigurationValidScheduler() throws IOException { Configuration config = CapacitySchedulerConfigGeneratorForTest .createBasicCSConfiguration(); config.set("yarn.scheduler.capacity.root.test1.state", "STOPPED"); config.set("yarn.scheduler....
public String generateShortUuid() { return String.valueOf(ID_WORKER_UTILS.nextId()); }
@Test public void testGenerateShortUuid() { String shortUuid = UUIDUtils.getInstance().generateShortUuid(); assertTrue(StringUtils.isNotEmpty(shortUuid)); assertEquals(19, shortUuid.length()); }
@Override public ObjectName createName(String type, String domain, String name) { try { ObjectName objectName; Hashtable<String, String> properties = new Hashtable<>(); properties.put("name", name); properties.put("type", type); objectName = new O...
@Test public void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ObjectName on = f.createName("type", "com.domain", "something.with.quotes(\"ABcd\")"); assertThatCode(() -> new ObjectName(on.toString())).doesNotThrow...
static void validateConnectors(KafkaMirrorMaker2 kafkaMirrorMaker2) { if (kafkaMirrorMaker2.getSpec() == null) { throw new InvalidResourceException(".spec section is required for KafkaMirrorMaker2 resource"); } else { if (kafkaMirrorMaker2.getSpec().getClusters() == null ||...
@Test public void testMirrorTargetClusterNotSameAsConnectCluster() { // The most obvious error case, where connect cluster is set to the source cluster instead of target KafkaMirrorMaker2 kmm2 = new KafkaMirrorMaker2Builder(KMM2) .editSpec() .withConnectCluster("s...
public static ImmutableSet<HttpUrl> allSubPaths(String url) { return allSubPaths(HttpUrl.parse(url)); }
@Test public void allSubPaths_whenNoSubPathWithTrailingSlash_returnsSingleUrl() { assertThat(allSubPaths("http://localhost/")) .containsExactly(HttpUrl.parse("http://localhost/")); }
public Optional<String> findGenerateKeyColumnName(final String logicTableName) { return Optional.ofNullable(shardingTables.get(logicTableName)).filter(each -> each.getGenerateKeyColumn().isPresent()).flatMap(ShardingTable::getGenerateKeyColumn); }
@Test void assertFindGenerateKeyColumn() { assertTrue(createMaximumShardingRule().findGenerateKeyColumnName("logic_table").isPresent()); }
public static org.apache.avro.Schema.Field toAvroField(Field field, String namespace) { org.apache.avro.Schema fieldSchema = getFieldSchema(field.getType(), field.getName(), namespace); return new org.apache.avro.Schema.Field( field.getName(), fieldSchema, field.getDescription(), (Object) null);...
@Test public void testNullableBeamArrayFieldToAvroField() { Field beamField = Field.nullable("arrayField", FieldType.array(FieldType.INT32)); org.apache.avro.Schema.Field expectedAvroField = new org.apache.avro.Schema.Field( "arrayField", ReflectData.makeNullable( ...