focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Map<String, String> zip(String keys, String values, String delimiter, boolean isOrder) { return ArrayUtil.zip(StrUtil.splitToArray(keys, delimiter), StrUtil.splitToArray(values, delimiter), isOrder); }
@Test public void zipTest() { final Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d"); final Collection<Integer> values = CollUtil.newArrayList(1, 2, 3, 4); final Map<String, Integer> map = CollUtil.zip(keys, values); assertEquals(4, Objects.requireNonNull(map).size()); assertEquals(1, m...
@Override public int publish(TopicPath topic, List<OutgoingMessage> outgoingMessages) throws IOException { PublishRequest.Builder request = PublishRequest.newBuilder().setTopic(topic.getPath()); for (OutgoingMessage outgoingMessage : outgoingMessages) { PubsubMessage.Builder message = outgoing...
@Test public void publishOneMessage() throws IOException { initializeClient(TIMESTAMP_ATTRIBUTE, ID_ATTRIBUTE); String expectedTopic = TOPIC.getPath(); PubsubMessage expectedPubsubMessage = PubsubMessage.newBuilder() .setData(ByteString.copyFrom(DATA.getBytes(StandardCharsets.UTF_8))) ...
public final void sort(long startIndex, long length) { quickSort(startIndex, length - 1); }
@Test public void testQuickSortLong() { final long[] array = longArrayWithRandomElements(); final long baseAddr = memMgr.getAllocator().allocate(ARRAY_LENGTH * LONG_SIZE_IN_BYTES); final MemoryAccessor mem = memMgr.getAccessor(); for (int i = 0; i < ARRAY_LENGTH; i++) { m...
@Override public Entry next(Entry reuse) throws IOException { // Ignore reuse, because each HeadStream has its own reuse BinaryRowData. return next(); }
@Test public void testMergeOfTwoStreams() throws Exception { List<MutableObjectIterator<BinaryRowData>> iterators = new ArrayList<>(); iterators.add( newIterator(new int[] {1, 2, 4, 5, 10}, new String[] {"1", "2", "4", "5", "10"})); iterators.add( newIterator(...
@Override public void cancel() { context.goToCanceling( getExecutionGraph(), getExecutionGraphHandler(), getOperatorCoordinatorHandler(), getFailures()); }
@Test void testCancelTransitionsToCancellingState() throws Exception { try (MockExecutingContext ctx = new MockExecutingContext()) { Executing exec = new ExecutingStateBuilder().build(ctx); ctx.setExpectCancelling(assertNonNull()); exec.cancel(); } }
@Udf public <T> String join( @UdfParameter(description = "the array to join using the default delimiter '" + DEFAULT_DELIMITER + "'") final List<T> array ) { return join(array, DEFAULT_DELIMITER); }
@Test public void shouldThrowExceptionForExamplesOfUnsupportedElementTypes() { assertThrows(KsqlFunctionException.class, () -> arrayJoinUDF.join(Arrays.asList('a','b'))); assertThrows(KsqlFunctionException.class, () -> arrayJoinUDF.join(Arrays.asList(BigInteger.ONE,BigInteger.ZERO))); asse...
public Result fetchArtifacts(String[] uris) { checkArgument(uris != null && uris.length > 0, "At least one URI is required."); ArtifactUtils.createMissingParents(baseDir); List<File> artifacts = Arrays.stream(uris) .map(FunctionUtils.uncheckedFunction(thi...
@Test void testFileSystemFetchWithoutAdditionalUri() throws Exception { File sourceFile = TestingUtils.getClassFile(getClass()); String uriStr = "file://" + sourceFile.toURI().getPath(); ArtifactFetchManager fetchMgr = new ArtifactFetchManager(configuration); ArtifactFetchManager.Re...
@Override public String toString() { StringBuilder sb = new StringBuilder("{"); addField(sb, "\"userUuid\": ", this.userUuid, true); addField(sb, "\"userLogin\": ", this.userLogin, true); addField(sb, "\"name\": ", this.name, true); addField(sb, "\"email\": ", this.email, true); addField(sb, "...
@Test void toString_givenEmptyScmAccount_returnValidJSON() { UserDto userDto = createUserDto(); userDto.setScmAccounts(emptyList()); UserNewValue userNewValue = new UserNewValue(userDto); String jsonString = userNewValue.toString(); assertValidJSON(jsonString); }
protected void commonDeclareThen(final KiePMMLDroolsRule rule, final StringJoiner joiner) { if (rule.getFocusedAgendaGroup() != null) { joiner.add(String.format(FOCUS_AGENDA_GROUP, rule.getFocusedAgendaGroup())); } if (rule.getToAccumulate() != null) { joiner.add(String.f...
@Test void commonDeclareThen() { String ruleName = "RULENAME"; String statusToSet = "STATUSTOSET"; String outputFieldName = "OUTPUTFIELDNAME"; Object result = "RESULT"; OutputField outputField = new OutputField(); outputField.setName(outputFieldName); outputFi...
public CoordinatorResult<TxnOffsetCommitResponseData, CoordinatorRecord> commitTransactionalOffset( RequestContext context, TxnOffsetCommitRequestData request ) throws ApiException { validateTransactionalOffsetCommit(context, request); final TxnOffsetCommitResponseData response = ne...
@Test public void testConsumerGroupTransactionalOffsetCommitWithStaleMemberEpoch() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); // Create an empty group. ConsumerGroup group = context.groupMetadataManager.getOrMaybeCreatePersistedConsu...
public URI qualifiedURI(String filename) throws IOException { try { URI fileURI = new URI(filename); if (RESOURCE_URI_SCHEME.equals(fileURI.getScheme())) { return fileURI; } } catch (URISyntaxException ignore) { } return qualifiedPath(filename).toUri(); }
@Test public void qualifiedURITestForWindows() throws IOException { Assume.assumeTrue(System.getProperty("os.name").toLowerCase().startsWith("win")); URI uri = this.command.qualifiedURI(WIN_FILE_PATH); Assert.assertEquals("/C:/Test/Downloads/test.parquet", uri.getPath()); }
public HttpHeaders preflightResponseHeaders() { if (preflightHeaders.isEmpty()) { return EmptyHttpHeaders.INSTANCE; } final HttpHeaders preflightHeaders = new DefaultHttpHeaders(); for (Entry<CharSequence, Callable<?>> entry : this.preflightHeaders.entrySet()) { f...
@Test public void preflightResponseHeadersMultipleValues() { final CorsConfig cors = forAnyOrigin().preflightResponseHeader("MultipleValues", "value1", "value2").build(); assertThat(cors.preflightResponseHeaders().getAll(of("MultipleValues")), hasItems("value1", "value2")); }
@VisibleForTesting StandardContext addStaticDir(Tomcat tomcat, String contextPath, File dir) { try { fs.createOrCleanupDir(dir); } catch (IOException e) { throw new IllegalStateException(format("Fail to create or clean-up directory %s", dir.getAbsolutePath()), e); } return addContext(tomc...
@Test public void fail_if_static_directory_can_not_be_initialized() throws Exception { File dir = temp.newFolder(); TomcatContexts.Fs fs = mock(TomcatContexts.Fs.class); doThrow(new IOException()).when(fs).createOrCleanupDir(any(File.class)); assertThatThrownBy(() -> new TomcatContexts(fs).addStatic...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testInverseUdp() throws Exception { InInt32UDP droppable = new InInt32UDP(ImmutableSet.of(42)); InInt32UDP undroppable = new InInt32UDP(ImmutableSet.of(205)); Set<Integer> allValues = ImmutableSet.copyOf(Ints.asList(intValues)); InInt32UDP completeMatch = new InInt32UDP(allValues); ...
@Override public String getDescription() { return "field: " + field + ", value: " + value + ", grace: " + grace + ", repeat notifications: " + repeatNotifications; }
@Test public void testConstructor() throws Exception { final Map<String, Object> parameters = getParametersMap(0, "field", "value"); final FieldContentValueAlertCondition condition = getCondition(parameters, alertConditionTitle); assertNotNull(condition); assertNotNull(condition.ge...
@Override public boolean test(Pair<Point, Point> pair) { return testVertical(pair) && testHorizontal(pair); }
@Test public void testHorizontalSeparation() { Point p1 = (new PointBuilder()).time(EPOCH).latLong(0.0, 0.0).altitude(Distance.ofFeet(1000.0)).build(); Point p2 = (new PointBuilder()).time(EPOCH).latLong(0.0, 0.0).altitude(Distance.ofFeet(1000.0)).build(); Point p3 = (new PointBuilder()).ti...
@Override public MapperResult findConfigInfoByAppFetchRows(MapperContext context) { final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); String sql = "SELECT id,data_id,group_id...
@Test void testFindConfigInfoByAppFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppFetchRows(context); assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE ? AND app_name= ...
public static String canonicalizeUrl(String url, String refer) { URL base; try { try { base = new URL(refer); } catch (MalformedURLException e) { // the base is unsuitable, but the attribute may be abs on its own, so try that URL ab...
@Test public void testFixRelativeUrl() { String absoluteUrl = UrlUtils.canonicalizeUrl("aa", "http://www.dianping.com/sh/ss/com"); assertThat(absoluteUrl).isEqualTo("http://www.dianping.com/sh/ss/aa"); absoluteUrl = UrlUtils.canonicalizeUrl("../aa", "http://www.dianping.com/sh/ss/com"); ...
public static List<ParameterMarkerExpressionSegment> getParameterMarkerExpressions(final Collection<ExpressionSegment> expressions) { List<ParameterMarkerExpressionSegment> result = new ArrayList<>(); extractParameterMarkerExpressions(result, expressions); return result; }
@Test void assertGetParameterMarkerExpressionsFromInExpression() { ListExpression listExpression = new ListExpression(0, 0); listExpression.getItems().add(new ParameterMarkerExpressionSegment(0, 0, 1, ParameterMarkerType.QUESTION)); listExpression.getItems().add(new ParameterMarkerExpression...
boolean hasEnoughResource(ContinuousResource request) { double allocated = allocations.stream() .filter(x -> x.resource() instanceof ContinuousResource) .map(x -> (ContinuousResource) x.resource()) .mapToDouble(ContinuousResource::value) .sum(); ...
@Test public void testHasEnoughResourceWhenExactResourceIsRequested() { ContinuousResource original = Resources.continuous(DID, PN1, Bandwidth.class).resource(Bandwidth.gbps(1).bps()); ContinuousResource allocated = Resources.continuous(DID, PN1, Bandwidth.class).reso...
@SuppressWarnings("WEAK_MESSAGE_DIGEST_MD5") @Override public Object convert(String value) { if (value == null || value.isEmpty()) { return value; } // MessageDigest is not threadsafe. #neverForget return DigestUtils.md5Hex(value); }
@Test public void testConvert() throws Exception { Converter hc = new HashConverter(new HashMap<String, Object>()); assertNull(hc.convert(null)); assertEquals("", hc.convert("")); assertEquals("c029b5a72ae255853d7151a9e28c6260", hc.convert("graylog2")); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testInvalidNumPercentage() throws Exception { expectInvalidResourcePercentage("cpu"); parseResourceConfigValue("95A% cpu, 50% memory"); }
@Override public void onQueuesUpdate(List<Queue> queues) { List<QueueUpdateMsg> queueUpdateMsgs = queues.stream() .map(queue -> QueueUpdateMsg.newBuilder() .setTenantIdMSB(queue.getTenantId().getId().getMostSignificantBits()) .setTenantIdLSB(qu...
@Test public void testOnQueueChangeSingleMonolith() { when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(MONOLITH)); when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(MONOLITH)); when(partitionService.getAllSer...
public boolean isCacheSecurityCredentials() { return cacheSecurityCredentials; }
@Test void testIsCacheSecurityCredentials() { assertTrue(StsConfig.getInstance().isCacheSecurityCredentials()); StsConfig.getInstance().setCacheSecurityCredentials(false); assertFalse(StsConfig.getInstance().isCacheSecurityCredentials()); }
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeMapDefinedBySEL() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomerge': {'type': 'MAP','expression': 'data = new HashMap(); data.put(\\'foo\\', 123); return data;'}}"); Map<String, ParamDefinition> paramsToMerge ...
public static void run(Options options) { Pipeline p = Pipeline.create(options); double samplingThreshold = 0.1; p.apply(TextIO.read().from(options.getWikiInput())) .apply(MapElements.via(new ParseTableRowJson())) .apply(new ComputeTopSessions(samplingThreshold)) .apply("Write", Te...
@Test @Category(ValidatesRunner.class) public void testComputeTopUsers() { PCollection<String> output = p.apply( Create.of( Arrays.asList( new TableRow().set("timestamp", 0).set("contributor_username", "user1"), new Tab...
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 forgeFoundDuplicateMods() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/forge_found_duplicate_mods.txt")), CrashReportAnalyzer.Rule.FORGE_FOUND_DUPLICATE_MODS); assertEquals(("\t...
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { ResourceConverter converter = new ResourceConverter(dataFormatTypeClasses); byte[] objectAsBytes = converter.writeDocument(new JSONAPIDocument<>(graph)); stream.write(objectAsBytes); }
@Test public void testJsonApiMarshalNoAnnotationOnType() { Class<?>[] formats = { MyBook.class, MyAuthor.class }; JsonApiDataFormat jsonApiDataFormat = new JsonApiDataFormat(formats); Exchange exchange = new DefaultExchange(context); ByteArrayOutputStream baos = new ByteArrayOutputS...
public boolean initAndAddIssue(Issue issue) { DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent(); if (noSonar(inputComponent, issue)) { return false; } ActiveRule activeRule = activeRules.find(issue.ruleKey()); if (activeRule == null) { ...
@Test public void should_ignore_lines_commented_with_nosonar() { initModuleIssues(); DefaultIssue issue = new DefaultIssue(project) .at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("")) .forRule(JAVA_RULE_KEY); file.noSonarAt(new HashSet<>(Collections.singletonList(3)))...
@JsonProperty public DeltaTable getDeltaTable() { return deltaTable; }
@Test public void testJsonRoundTrip() { List<DeltaColumn> columns = ImmutableList.of( new DeltaColumn("c1", parseTypeSignature(StandardTypes.REAL), true, true), new DeltaColumn("c2", parseTypeSignature(INTEGER), false, true), new DeltaColumn("c3", parseTyp...
public <V> Future<Iterable<Map.Entry<ByteString, V>>> valuePrefixFuture( ByteString prefix, String stateFamily, Coder<V> valueCoder) { // First request has no continuation position. StateTag<ByteString> stateTag = StateTag.<ByteString>of(Kind.VALUE_PREFIX, prefix, stateFamily).toBuilder().build();...
@Test public void testReadTagValuePrefixWithContinuations() throws Exception { Future<Iterable<Map.Entry<ByteString, Integer>>> future = underTest.valuePrefixFuture(STATE_KEY_PREFIX, STATE_FAMILY, INT_CODER); Mockito.verifyNoMoreInteractions(mockWindmill); Windmill.KeyedGetDataRequest.Builder exp...
@Override public String get(String key) { return variables.get(key); }
@Test public void testGet() { assertThat(unmodifiables.get(MY_KEY), CoreMatchers.is(vars.get(MY_KEY))); }
public synchronized Topology addSource(final String name, final String... topics) { internalTopologyBuilder.addSource(null, name, null, null, null, topics); return this; }
@Test public void testNamedTopicMatchesAlreadyProvidedPattern() { topology.addSource("source-1", Pattern.compile("f.*")); try { topology.addSource("source-2", "foo"); fail("Should have thrown TopologyException for overlapping topic with already registered pattern"); }...
@Override public RelativeRange apply(final Period period) { if (period != null) { return RelativeRange.Builder.builder() .from(period.withYears(0).withMonths(0).plusDays(period.getYears() * 365).plusDays(period.getMonths() * 30).toStandardSeconds().getSeconds()) ...
@Test void testReturnsNullOnNullInput() { assertNull(converter.apply(null)); }
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) { List<Object> valuesInOrder = schema.getFields().stream() .map( field -> { try { org.apache.avro.Schema.Field avroField = rec...
@Test public void testToBeamRow_arrayNulls() { Row beamRow = BigQueryUtils.toBeamRow(ARRAY_TYPE_NULLS, BQ_ARRAY_ROW_NULLS); assertEquals(ARRAY_ROW_NULLS, beamRow); }
@Override public Collection<Event> filter(Collection<Event> events, final FilterMatchListener filterMatchListener) { for (Event e : events) { if (overwrite || e.getField(target) == null) { e.setField(target, UUID.randomUUID().toString()); } filterMatchList...
@Test public void testUuidWithoutOverwrite() { String targetField = "target_field"; String originalValue = "originalValue"; Map<String, Object> rawConfig = new HashMap<>(); rawConfig.put(Uuid.TARGET_CONFIG.name(), targetField); Configuration config = new ConfigurationImpl(raw...
@Override public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) { short versionId = version(); short errorCode = Errors.forException(e).code(); List<ListOffsetsTopicResponse> responses = new ArrayList<>(); for (ListOffsetsTopic topic : data.topics()) { ...
@Test public void testGetErrorResponse() { for (short version = 1; version <= ApiKeys.LIST_OFFSETS.latestVersion(); version++) { List<ListOffsetsTopic> topics = Collections.singletonList( new ListOffsetsTopic() .setName("topic") ...
@Override public double getDouble(int index) { return Double.longBitsToDouble(getLong(index)); }
@Test public void testGetDoubleAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getDouble(0); } }); }
@Override public final Object getValue(final int columnIndex, final Class<?> type) throws SQLException { ShardingSpherePreconditions.checkNotContains(INVALID_MEMORY_TYPES, type, () -> new SQLFeatureNotSupportedException(String.format("Get value from `%s`", type.getName()))); Object result = currentR...
@Test void assertGetValueForSQLXML() { assertThrows(SQLFeatureNotSupportedException.class, () -> memoryMergedResult.getValue(1, SQLXML.class)); }
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("start position") Number start) { return invoke(string, start, null); }
@Test void invokeStartOutOfListBounds() { FunctionTestUtil.assertResultError(substringFunction.invoke("test", 10), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(substringFunction.invoke("test", 10, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(s...
void closeAllStreams() { // Supplier<Stream>.get() starts the stream which is an expensive operation as it initiates the // streaming RPCs by possibly making calls over the network. Do not close the streams unless // they have already been started. if (started.get()) { getWorkStream.get().shutdown...
@Test public void testCloseAllStreams_doesNotCloseUnstartedStreams() { WindmillStreamSender windmillStreamSender = newWindmillStreamSender(GetWorkBudget.builder().setBytes(1L).setItems(1L).build()); windmillStreamSender.closeAllStreams(); verifyNoInteractions(streamFactory); }
@Override public Class<? extends AvgHistogramFunctionBuilder> builder() { return AvgHistogramFunctionBuilder.class; }
@Test public void testBuilder() throws IllegalAccessException, InstantiationException { HistogramFunctionInst inst = new HistogramFunctionInst(); inst.accept( MeterEntity.newService("service-test", Layer.GENERAL), new BucketedValues( BUCKETS, new long[] { ...
@Restricted(NoExternalUse.class) public static Icon tryGetIcon(String iconGuess) { // Jenkins Symbols don't have metadata so return null if (iconGuess == null || iconGuess.startsWith("symbol-")) { return null; } Icon iconMetadata = IconSet.icons.getIconByClassSpec(iconGu...
@Test public void tryGetIcon_shouldReturnMetadataForExtraSpec() throws Exception { assertThat(Functions.tryGetIcon("icon-help icon-sm extra-class"), is(not(nullValue()))); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == LIST_SLICE_SUB_COMMAND_NAME) { returnCommand = slice_list(reader); } else if...
@Test public void testSort() { String inputCommand = ListCommand.LIST_SORT_SUB_COMMAND_NAME + "\n" + target + "\ne\n"; try { command.execute("l", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); assertEquals(list.get(0), "1"); assertEquals(list.get...
@Override protected JobExceptionsInfoWithHistory handleRequest( HandlerRequest<EmptyRequestBody> request, ExecutionGraphInfo executionGraph) { final List<Integer> exceptionToReportMaxSizes = request.getQueryParameter(UpperLimitExceptionParameter.class); final int exceptio...
@Test void testOnlyExceptionHistoryWithNoMatchingFailureLabel() throws HandlerRequestException { final RuntimeException rootThrowable = new RuntimeException("exception #0"); final long rootTimestamp = System.currentTimeMillis(); final RootExceptionHistoryEntry rootEntry = fromGlobalFailure(r...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PCollectionsImmutableNavigableSet<?> that = (PCollectionsImmutableNavigableSet<?>) o; return Objects.equals(underlying(), that.underlying()); }
@Test public void testEquals() { final TreePSet<Object> mock = mock(TreePSet.class); assertEquals(new PCollectionsImmutableNavigableSet<>(mock), new PCollectionsImmutableNavigableSet<>(mock)); final TreePSet<Object> someOtherMock = mock(TreePSet.class); assertNotEquals(new PCollectio...
@Override public IQ handleIQ(IQ packet) { IQ response = IQ.createResultIQ(packet); Element timeElement = DocumentHelper.createElement(QName.get(info.getName(), info.getNamespace())); timeElement.addElement("tzo").setText(formatsTimeZone(TimeZone.getDefault())); timeElement.addElement...
@Test public void testIQ() { IQEntityTimeHandler iqEntityTimeHandler = new IQEntityTimeHandler(); IQ input = new IQ(IQ.Type.get, "1"); IQ result = iqEntityTimeHandler.handleIQ(input); assertEquals(result.getChildElement().getName(), "time"); assertEquals(result.getChildElemen...
public BitSet toBitSet() { BitSet resultSet = new BitSet(); int ordinal = this.nextSetBit(0); while(ordinal!=-1) { resultSet.set(ordinal); ordinal = this.nextSetBit(ordinal + 1); } return resultSet; }
@Test public void testToBitSet() { BitSet bSet = new BitSet(); ThreadSafeBitSet tsbSet = new ThreadSafeBitSet(); int[] ordinals = new int[] { 1, 5, 10 }; // init for (int ordinal : ordinals) { bSet.set(ordinal); tsbSet.set(ordinal); } ...
@Override public String toString() { return String.format(TO_STRING_FORMAT, getClass().getSimpleName(), maskKeyData(defaultPublicKey), maskKeyData(defaultPrivateKey), maskKeyData(publicKeys), maskKeyData(privateKeys)); }
@Test public void testToString() { DefaultCryptoKeyReaderConfigurationData conf = new DefaultCryptoKeyReaderConfigurationData(); assertEquals(conf.toString(), "DefaultCryptoKeyReaderConfigurationData(defaultPublicKey=null, defaultPrivateKey=null, publicKeys={}, privateKeys={})"); ...
private static String getProperty(String name, Configuration configuration) { return Optional.of(configuration.getStringArray(relaxPropertyName(name))) .filter(values -> values.length > 0) .map(Arrays::stream) .map(stream -> stream.collect(Collectors.joining(","))) .orElse(null);...
@Test public void assertDynamicEnvConfig() throws IOException { Map<String, Object> baseProperties = new HashMap<>(); Map<String, String> mockedEnvironmentVariables = new HashMap<>(); String configFile = File.createTempFile("pinot-configuration-test-4", ".properties").getAbsolutePath(); basePr...
public FEELFnResult<BigDecimal> invoke(@ParameterName("string") String string) { if ( string == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null")); } else { return FEELFnResult.ofResult(NumberEvalHelper.getBigDecimalOrNull...
@Test void invoke() { FunctionTestUtil.assertResult(stringLengthFunction.invoke("testString"), BigDecimal.TEN); }
@SuppressWarnings("unchecked") public static <T> Class<T> compile(ClassLoader cl, String name, String code) { try { // The class name is part of the "code" and makes the string unique, // to prevent class leaks we don't cache the class loader directly // but only its hash...
@Test public void testWrongCode() { String code = "public class111 Main {\n" + " int i;\n" + " int j;\n" + "}"; assertThatThrownBy( () -> CompileUtils.compile(this.getClass().getClassLoader(), "Main", code)) .isInstanceOf(FlinkRuntimeException.class) ...
public static boolean isUnanimousCandidate( final ClusterMember[] clusterMembers, final ClusterMember candidate, final int gracefulClosedLeaderId) { int possibleVotes = 0; for (final ClusterMember member : clusterMembers) { if (member.id == gracefulClosedLeaderId) ...
@Test void isUnanimousCandidateReturnFalseIfThereIsAMemberWithMoreUpToDateLog() { final int gracefulClosedLeaderId = Aeron.NULL_VALUE; final ClusterMember candidate = newMember(4, 10, 800); final ClusterMember[] members = new ClusterMember[] { newMember(1, 2, 100), ...
@SuppressWarnings("deprecation") public static <K> KStreamHolder<K> build( final KStreamHolder<K> left, final KStreamHolder<K> right, final StreamStreamJoin<K> join, final RuntimeBuildContext buildContext, final StreamJoinedFactory streamJoinedFactory) { final QueryContext queryConte...
@Test public void shouldDoLeftJoin() { // Given: givenLeftJoin(L_KEY); // When: final KStreamHolder<Struct> result = join.build(planBuilder, planInfo); // Then: verify(leftKStream).leftJoin( same(rightKStream), eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.v...
@Restricted(NoExternalUse.class) public static Icon tryGetIcon(String iconGuess) { // Jenkins Symbols don't have metadata so return null if (iconGuess == null || iconGuess.startsWith("symbol-")) { return null; } Icon iconMetadata = IconSet.icons.getIconByClassSpec(iconGu...
@Test public void tryGetIcon_shouldReturnNullForSymbol() throws Exception { assertThat(Functions.tryGetIcon("symbol-search"), is(nullValue())); }
@Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof ChangesOnMyIssuesNotification)) { return null; } ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif; if (notification.getChange() instanceof AnalysisChange) { ...
@Test public void format_set_html_message_with_header_dealing_with_plural_when_change_from_Analysis() { Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4)) .mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i))...
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception { return newGetter(object, parent, modifier, field.getType(), field::get, (t, et) -> new FieldGetter(parent, field, modifier, t, et)); }
@Test public void newFieldGetter_whenExtractingFromNonEmpty_Array_FieldAndParentIsNonEmptyMultiResult_nullFirstValue_thenInferReturnType() throws Exception { OuterObject object = new OuterObject("name", new InnerObject("inner", null, 0, 1, 2, 3)); Getter parentGetter = GetterFactory.new...
public boolean releaseTrigger(JobTriggerDto trigger, JobTriggerUpdate triggerUpdate) { requireNonNull(trigger, "trigger cannot be null"); requireNonNull(triggerUpdate, "triggerUpdate cannot be null"); final var filter = and( // Make sure that the owner still owns the trigger ...
@Test public void releaseTrigger() { final JobTriggerDto trigger1 = dbJobTriggerService.create(JobTriggerDto.Builder.create(clock) .jobDefinitionId("abc-123") .jobDefinitionType("event-processor-execution-v1") .concurrencyRescheduleCount(42) .s...
@Override public void close() { if (input != null) { try { input.close(); } catch (IOException e) { LOG.warn("failed to close stream", e); } } }
@Test public void close() throws IOException { ss.open(); ss.close(); int n = -1; try { byte[] buff = new byte[1]; n = ss.read(buff); } catch (IOException ignored) { } assertEquals(-1, n); }
@SuppressWarnings("deprecation") public void runLocalization(final InetSocketAddress nmAddr) throws IOException, InterruptedException { // load credentials initDirs(conf, user, appId, lfs, localDirs); final Credentials creds = new Credentials(); DataInputStream credFile = null; try { /...
@Test public void testMultipleLocalizers() throws Exception { FakeContainerLocalizerWrapper testA = new FakeContainerLocalizerWrapper(); FakeContainerLocalizerWrapper testB = new FakeContainerLocalizerWrapper(); FakeContainerLocalizer localizerA = testA.init(); FakeContainerLocalizer localizerB = tes...
public abstract FetchedAppReport getApplicationReport(ApplicationId appId) throws YarnException, IOException;
@Test void testFetchReportAHSEnabled() throws YarnException, IOException { testHelper(true); Mockito.verify(historyManager, Mockito.times(1)) .getApplicationReport(Mockito.any(GetApplicationReportRequest.class)); Mockito.verify(appManager, Mockito.times(1)) .getApplicationReport(Mockito.an...
static ZipFileRO open(final String zipFileName) { final Ref<ZipArchiveHandle> handle = new Ref<>(null); final int error = OpenArchive(zipFileName, handle); if (isTruthy(error)) { ALOGW("Error opening archive %s: %s", zipFileName, ErrorCodeString(error)); CloseArchive(); return null; } ...
@Test public void open_emptyZip() throws Exception { // ensure ZipFileRO cam handle an empty zip file with no central directory File blob = File.createTempFile("prefix", "zip"); try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(blob))) {} ZipFileRO zipFile = ZipFileRO.open(blob.toSt...
@Subscribe public void onChatMessage(ChatMessage event) { final String message = event.getMessage(); if (event.getType() != ChatMessageType.SPAM && event.getType() != ChatMessageType.GAMEMESSAGE) { return; } if (message.contains(DODGY_NECKLACE_PROTECTION_MESSAGE) || message.contains(SHADOW_VEIL_PROTECTI...
@Test public void testThrall() { when(timersAndBuffsConfig.showArceuus()).thenReturn(true); when(client.getBoostedSkillLevel(Skill.MAGIC)).thenReturn(60); ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", "<col=ef0083>You resurrect a greater zombified thrall.</col>", "", 0); ti...
@Override public AuditReplayCommand parse(Text inputLine, Function<Long, Long> relativeToAbsolute) throws IOException { Matcher m = logLineParseRegex.matcher(inputLine.toString()); if (!m.find()) { throw new IOException( "Unable to find valid message pattern from audit log line: `" ...
@Test public void testSimpleInput() throws Exception { Text in = getAuditString("1970-01-01 00:00:11,000", "fakeUser", "listStatus", "sourcePath", "null"); AuditReplayCommand expected = new AuditReplayCommand(1000, "fakeUser", "listStatus", "sourcePath", "null", "0.0.0.0"); assertEquals(ex...
@Operation(summary = "Start Bvd session") @GetMapping(value = "/frontchannel/saml/v4/entrance/start_bvd_session") public RedirectView startBvdSession(@RequestParam(value = "SAMLart") String artifact) throws SamlSessionException, AdException, BvdException, UnsupportedEncodingException { SamlSession samlS...
@Test public void startBvdSession() throws BvdException, SamlSessionException, AdException, UnsupportedEncodingException { SamlSession samlSession = new SamlSession(1L); samlSession.setHttpSessionId("httpSessionId"); samlSession.setServiceEntityId("serviceEntityId"); samlSession.setS...
@Override public String authenticate(AuthenticationDataSource authData) throws AuthenticationException { SocketAddress clientAddress; String roleToken; ErrorCode errorCode = ErrorCode.UNKNOWN; try { if (authData.hasDataFromPeer()) { clientAddress = authDa...
@Test public void testAuthenticateUnsignedToken() throws Exception { List<String> roles = new ArrayList<String>() { { add("test_role"); } }; RoleToken token = new RoleToken.Builder("Z1", "test_provider", roles).principal("test_app").build(); A...
@Override public Response toResponse(Throwable exception) { debugLog(exception); if (exception instanceof WebApplicationException w) { var res = w.getResponse(); if (res.getStatus() >= 500) { log(w); } return res; } if (exception instanceof AuthenticationException) {...
@Test void toResponse_withBody() { when(uriInfo.getRequestUri()).thenReturn(REQUEST_URI); when(headers.getAcceptableMediaTypes()).thenReturn(List.of(MediaType.WILDCARD_TYPE)); mockHeaders("de-DE"); // when var res = mapper.toResponse(new IllegalArgumentException()); // then assertEquals...
public static String convertToHtml(String input) { return new Markdown().convert(StringEscapeUtils.escapeHtml4(input)); }
@Test public void shouldDecorateRelativeUrl() { assertThat(Markdown.convertToHtml("[Google](/google/com)")) .isEqualTo("<a href=\"/google/com\">Google</a>"); }
@Description("Returns a Geometry type Polygon object from Well-Known Text representation (WKT)") @ScalarFunction("ST_Polygon") @SqlType(GEOMETRY_TYPE_NAME) public static Slice stPolygon(@SqlType(VARCHAR) Slice input) { Geometry geometry = jtsGeometryFromWkt(input.toStringUtf8()); validat...
@Test public void testSTPolygon() { assertFunction("ST_AsText(ST_Polygon('POLYGON EMPTY'))", VARCHAR, "POLYGON EMPTY"); assertFunction("ST_AsText(ST_Polygon('POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1))'))", VARCHAR, "POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1))"); assertInvalidFunction("ST_AsText(ST_Poly...
@Override public int hashCode() { return Objects.hash(taskId, topicPartitions); }
@Test public void shouldBeEqualsIfOnlyDifferInCommittedOffsets() { final TaskMetadataImpl stillSameDifferCommittedOffsets = new TaskMetadataImpl( TASK_ID, TOPIC_PARTITIONS, mkMap(mkEntry(TP_1, 1000000L), mkEntry(TP_1, 2L)), END_OFFSETS, TIME_CURREN...
public static <T extends Collection<E>, E> T removeNull(T collection) { return filter(collection, Objects::nonNull); }
@Test public void removeNullTest() { final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", null, "", " "); final ArrayList<String> filtered = CollUtil.removeNull(list); // 原地过滤 assertSame(list, filtered); assertEquals(CollUtil.newArrayList("a", "b", "c", "", " "), filtered); }
private static SnapshotDiffReport getSnapshotDiffReport( final FileSystem fs, final Path snapshotDir, final String fromSnapshot, final String toSnapshot) throws IOException { try { return (SnapshotDiffReport) getSnapshotDiffReportMethod(fs).invoke( fs, snapshotDir, fromSnapsh...
@Test public void testSync4() throws Exception { initData4(source); initData4(target); enableAndCreateFirstSnapshot(); // make changes under source changeData4(source); dfs.createSnapshot(source, "s2"); SnapshotDiffReport report = dfs.getSnapshotDiffReport(source, "s1", "s2"); System...
public void updateInstanceStatus(String status) { if (!STATUS_UP.equalsIgnoreCase(status) && !STATUS_DOWN.equalsIgnoreCase(status)) { LOGGER.warning(String.format(Locale.ENGLISH,"can't support status={%s}," + "please choose UP or DOWN", status)); return; } ...
@Test public void testUpdateInstanceStatus() throws NacosException { mockNamingService(); nacosClient.updateInstanceStatus(STATUS_DOWN); Assert.assertNotNull(ReflectUtils.getFieldValue(nacosClient, "instance")); }
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { return delegated.create(sqlStatementContext); }
@Test void assertCreateExecutorForSelectDatabase() { SelectStatementContext selectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS); when(selectStatementContext.getTablesContext().getTableNames()).thenReturn(Collections.singletonList("pg_database")); Optional<Database...
@Override public void set(K key, V value) { cache.put(key, value); }
@Test public void testSet() { adapter.set(23, "test"); assertEquals("test", cache.get(23)); }
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { int type = columnDef.getColumnMeta() >> 8; int length = columnDef.getColumnMeta() & 0xff; // unpack type & length, see https://bugs.mysql.com/bug.php?id=37426. if (0x30 != (ty...
@Test void assertReadSetValue() { columnDef.setColumnMeta(MySQLBinaryColumnType.SET.getValue() << 8); when(payload.getByteBuf()).thenReturn(byteBuf); when(byteBuf.readByte()).thenReturn((byte) 0xff); assertThat(new MySQLStringBinlogProtocolValue().read(columnDef, payload), is((byte) ...
@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 testDel() { List<byte[]> keys = new ArrayList<>(); for (int i = 0; i < 10; i++) { byte[] key = ("test" + i).getBytes(); keys.add(key); connection.set(key, ("test" + i).getBytes()); } assertThat(connection.del(keys.toArray(new byte...
@VisibleForTesting static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) { return createStreamExecutionEnvironment( options, MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()), options.getFlinkConfDir()); }
@Test public void shouldCreateRocksDbStateBackend() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setStreaming(true); options.setStateBackend("rocksDB"); options.setStateBackendStoragePath(temporaryFolder.getRoot().toURI().toString()); StreamExecutionEnvironment sev = ...
public String render(File templateFile) throws IOException { String template = FileUtils.readFileToString(templateFile, Charset.defaultCharset()); return render(template); }
@Test void testIterate() { // given K8sSpecTemplate template = new K8sSpecTemplate(); template.put("dict", ImmutableMap.of( "k1", "v1", "k2", "v2" )); // when String spec = template.render( "{% for key, value in dict.items() %}" + "key = {{key}}, value = {{...
@Override public List<EDGE> getEdges() { return path.getEdges(); }
@Test public void minimal_nontrivial_cycle() { String nodeA = "Node-A"; String nodeB = "Node-B"; CycleInternal<Edge<String>> cycle = new CycleInternal<>(asList(stringEdge(nodeA, nodeB), stringEdge(nodeB, nodeA))); assertThat(cycle.getEdges()).hasSize(2); }
public static NamespaceName get(String tenant, String namespace) { validateNamespaceName(tenant, namespace); return get(tenant + '/' + namespace); }
@Test(expectedExceptions = IllegalArgumentException.class) public void namespace_propertyClusterNamespaceTopic() { NamespaceName.get("property/cluster/namespace/topic"); }
@Override public void writeShort(final int v) throws IOException { ensureAvailable(SHORT_SIZE_IN_BYTES); Bits.writeShort(buffer, pos, (short) v, isBigEndian); pos += SHORT_SIZE_IN_BYTES; }
@Test public void testWriteShortForVByteOrder() throws Exception { short expected = 100; out.writeShort(2, expected, LITTLE_ENDIAN); short actual = Bits.readShortL(out.buffer, 2); assertEquals(expected, actual); }
protected AbstractNamedContainerCollector(NodeEngine nodeEngine, ConcurrentMap<String, C> containers) { super(nodeEngine); this.containers = containers; this.partitionService = nodeEngine.getPartitionService(); }
@Test public void testAbstractNamedContainerCollector() { TestNamedContainerCollector collector = new TestNamedContainerCollector(nodeEngine, true, true); assertEqualsStringFormat("Expected the to have %d containers, but found %d", 1, collector.containers.size()); collector.run(); ...
public static byte[] decodeChecked(CharSequence encoded) throws ValidateException { try { return decodeChecked(encoded, true); } catch (ValidateException ignore) { return decodeChecked(encoded, false); } }
@Test public void decodeCheckedTest() { String a = "3vQB7B6MrGQZaxCuFg4oh"; byte[] decode = Base58.decodeChecked(1 + a); assertArrayEquals("hello world".getBytes(StandardCharsets.UTF_8),decode); decode = Base58.decodeChecked(a); assertArrayEquals("hello world".getBytes(StandardCharsets.UTF_8),decode); }
@Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream inputStream = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return input...
@Test void testGetInputStream() throws IOException { ServletInputStream inputStream = reuseHttpServletRequest.getInputStream(); assertNotNull(inputStream); int read = inputStream.read(); while (read != -1) { read = inputStream.read(); } }
@VisibleForTesting public void loadDataFromRemote(String filePath, long offset, long lengthToLoad, PositionReader reader, int chunkSize) throws IOException { ByteBuffer buf = ByteBuffer.allocateDirect(chunkSize); String fileId = new AlluxioURI(filePath).hash(); while (lengthToLoad > 0) { long ...
@Test public void testLoadFromReader() throws IOException { String ufsPath = "testLoadRemote"; mWorker.loadDataFromRemote(ufsPath, 0, 10, new TestDataReader(100), (int) mPageSize); byte[] buffer = new byte[10]; String fileId = new AlluxioURI(ufsPath).hash(); List<PageId> cachedPages = mCacheManage...
@CheckForNull @Override public Instant forkDate(String referenceBranch, Path rootBaseDir) { return null; }
@Test public void forkDate_returns_null() throws SVNException { SvnScmProvider provider = new SvnScmProvider(config, new SvnBlameCommand(config)); assertThat(provider.forkDate("", Paths.get(""))).isNull(); }
public static FilesApplicationPackage fromFile(File appDir) { return fromFile(appDir, false); }
@Test public void testLegacyOverrides() { File appDir = new File("src/test/resources/app-legacy-overrides"); ApplicationPackage app = FilesApplicationPackage.fromFile(appDir); var overrides = app.legacyOverrides(); assertEquals(2, overrides.size()); assertEquals("something he...
public void updateCheckboxes( EnumSet<RepositoryFilePermission> permissionEnumSet ) { updateCheckboxes( false, permissionEnumSet ); }
@Test public void testUpdateCheckboxesNoPermissionsAppropriateTrue() { permissionsCheckboxHandler.updateCheckboxes( true, EnumSet.noneOf( RepositoryFilePermission.class ) ); verify( readCheckbox, times( 1 ) ).setChecked( false ); verify( writeCheckbox, times( 1 ) ).setChecked( false ); verify( deleteC...
@VisibleForTesting void startKsql(final KsqlConfig ksqlConfigWithPort) { cleanupOldState(); initialize(ksqlConfigWithPort); }
@Test public void shouldConfigureRocksDBConfigSetter() { // When: app.startKsql(ksqlConfig); // Then: verify(rocksDBConfigSetterHandler).accept(ksqlConfig); }
public void validate(AlmSettingDto almSettingDto) { String bitbucketUrl = almSettingDto.getUrl(); String bitbucketToken = almSettingDto.getDecryptedPersonalAccessToken(encryption); if (bitbucketUrl == null || bitbucketToken == null) { throw new IllegalArgumentException("Your global Bitbucket Server co...
@Test public void validate_success() { AlmSettingDto almSettingDto = createNewBitbucketDto("http://abc.com", "abc"); when(encryption.isEncrypted(any())).thenReturn(false); underTest.validate(almSettingDto); verify(bitbucketServerRestClient, times(1)).validateUrl("http://abc.com"); verify(bitbuck...
@Override public URL getResource(String name) { for (ClassLoader pluginClassloader : pluginClassloaders) { URL url = pluginClassloader.getResource(name); if (url != null) { return url; } } return getClass().getClassLoader().getResource(name); }
@Test public void aggregate_plugin_classloaders() { URLClassLoader checkstyle = newCheckstyleClassloader(); I18nClassloader i18nClassloader = new I18nClassloader(Lists.newArrayList(checkstyle)); assertThat(i18nClassloader.getResource("org/sonar/l10n/checkstyle.properties")).isNotNull(); assertThat(i1...
@Override public void run() throws Exception { // Get list of files to process. List<String> filteredFiles = SegmentGenerationUtils.listMatchedFilesWithRecursiveOption(_inputDirFS, _inputDirURI, _spec.getIncludeFileNamePattern(), _spec.getExcludeFileNamePattern(), _spec.isSearchRecursively()); ...
@Test public void testFailureHandling() throws Exception { File testDir = makeTestDir(); File inputDir = new File(testDir, "input"); inputDir.mkdirs(); File inputFile1 = new File(inputDir, "input1.csv"); FileUtils.writeLines(inputFile1, Lists.newArrayList("col1,col2", "value11,11", "value12...
public static void ensureCorrectArgs( final FunctionName functionName, final Object[] args, final Class<?>... argTypes ) { if (args == null) { throw new KsqlFunctionException("Null argument list for " + functionName.text() + "."); } if (args.length != argTypes.length) { throw new KsqlFu...
@Test public void shouldHandleSubTypes() { final Object[] args = new Object[]{1.345, 55}; UdfUtil.ensureCorrectArgs(FUNCTION_NAME, args, Number.class, Number.class); }
public static UUID fromString(String src) { return UUID.fromString(src.substring(7, 15) + "-" + src.substring(3, 7) + "-1" + src.substring(0, 3) + "-" + src.substring(15, 19) + "-" + src.substring(19)); }
@Test public void basicUuid() { System.out.println(UUIDConverter.fromString("1e746126eaaefa6a91992ebcb67fe33")); }
abstract boolean isHandlerMethod(Object handler);
@Test void WebMvc25_isHandlerMethod_isFalse() { HandlerMethod handlerMethod = mock(HandlerMethod.class); assertThat(new WebMvc25().isHandlerMethod(handlerMethod)) .isFalse(); }
public List<String> split(String in) { final StringBuilder result = new StringBuilder(); final char[] chars = in.toCharArray(); for (int i = 0; i < chars.length; i++) { final char c = chars[i]; if (CHAR_OPERATORS.contains(String.valueOf(c))) { if (i < char...
@Test public void split2() { List<String> tokens = parser.split("(a and b)"); assertEquals(Arrays.asList("(", "a", "and", "b", ")"), tokens); }
@Udf(description = "Returns Euler's number e raised to the power of an INT value.") public Double exp( @UdfParameter( value = "exponent", description = "the exponent to raise e to." ) final Integer exponent ) { return exp(exponent == null ? null : exponent.doubleValue()); }
@Test public void shouldHandleZero() { assertThat(udf.exp(0), is(1.0)); assertThat(udf.exp(0L), is(1.0)); assertThat(udf.exp(0.0), is(1.0)); }
public static Set<Class<? extends PipelineOptions>> getRegisteredOptions() { return Collections.unmodifiableSet(CACHE.get().registeredOptions); }
@Test public void testAutomaticRegistrationOfPipelineOptions() { assertTrue(PipelineOptionsFactory.getRegisteredOptions().contains(RegisteredTestOptions.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(expected = NullPointerException.class) public void parserShouldNotAcceptNull() { parser.toPrefix(null); fail(); }