focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public <T> T convert(String property, Class<T> targetClass) { final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass); if (converter == null) { throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalNa...
@Test void testConvertLong() { assertEquals(100L, (long) compositeConverter.convert("100", Long.class)); assertEquals(Long.MAX_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MAX_VALUE), Long.class)); assertEquals(Long.MIN_VALUE, (long) compositeConverter.convert(String.valueOf(...
static MinMax findMinMax(MinMax minMax, List<Statement> statements, EncodedValueLookup lookup) { List<List<Statement>> groups = CustomModelParser.splitIntoGroup(statements); for (List<Statement> group : groups) findMinMaxForGroup(minMax, group, lookup); return minMax; }
@Test public void testFindMaxPriority() { List<Statement> statements = new ArrayList<>(); statements.add(If("true", MULTIPLY, "2")); assertEquals(2, findMinMax(new MinMax(0, 1), statements, lookup).max); List<Statement> statements2 = new ArrayList<>(); statements2.add(If("tr...
public int getDepth(Throwable ex) { return getDepth(ex.getClass(), 0); }
@Test public void notFound() { RollbackRule rr = new RollbackRule(java.io.IOException.class.getName()); assertThat(rr.getDepth(new MyRuntimeException(""))).isEqualTo(-1); }
@Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals($ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) { return AsyncRpcResult.newDefaultAsyncResult(inv.getArguments()[0], inv); } return invo...
@SuppressWarnings("unchecked") @Test void testEcho() { Invocation invocation = createMockRpcInvocation(); Invoker<DemoService> invoker = createMockInvoker(invocation); given(invocation.getMethodName()).willReturn("$echo"); Result filterResult = echoFilter.invoke(invoker, invocat...
public CompletableFuture<Set<MessageQueue>> lockBatchMQ(ProxyContext ctx, Set<MessageQueue> mqSet, String consumerGroup, String clientId, long timeoutMillis) { CompletableFuture<Set<MessageQueue>> future = new CompletableFuture<>(); try { Set<MessageQueue> successSet = new CopyOnWrit...
@Test public void testLockBatch() throws Throwable { Set<MessageQueue> mqSet = new HashSet<>(); MessageQueue mq1 = new MessageQueue(TOPIC, "broker1", 0); AddressableMessageQueue addressableMessageQueue1 = new AddressableMessageQueue(mq1, "127.0.0.1"); MessageQueue mq2 = new MessageQu...
public static String getAddress(ECKeyPair ecKeyPair) { return getAddress(ecKeyPair.getPublicKey()); }
@Test public void testGetAddressBigInteger() { assertEquals(Keys.getAddress(SampleKeys.PUBLIC_KEY), (SampleKeys.ADDRESS_NO_PREFIX)); }
public static <T, K, U, M extends Map<K,U>> Collector<T, ?, M> toCustomMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, Supplier<M> mapSupplier) { return Collectors.toMap(keyMapper, valueMapper...
@Test public void custom_map_collector_throws_exception_upon_duplicate_keys() { List<String> duplicates = List.of("same", "same"); try { duplicates.stream().collect(toCustomMap(Function.identity(), Function.identity(), HashMap::new)); fail(); } catch (DuplicateKeyExc...
@ConstantFunction(name = "multiply", argTypes = {SMALLINT, SMALLINT}, returnType = SMALLINT) public static ConstantOperator multiplySmallInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createSmallInt((short) Math.multiplyExact(first.getSmallint(), second.getSmallint())); }
@Test public void multiplySmallInt() { assertEquals(100, ScalarOperatorFunctions.multiplySmallInt(O_SI_10, O_SI_10).getSmallint()); }
public static void printProgress(char showChar, int len) { print("{}{}", CharUtil.CR, StrUtil.repeat(showChar, len)); }
@Test @Disabled public void printProgressTest() { for(int i = 0; i < 100; i++) { Console.printProgress('#', 100, i / 100D); ThreadUtil.sleep(200); } }
@Override public boolean contains(long pTileIndex) { if (MapTileIndex.getZoom(pTileIndex) != mZoom) { return false; } if (!contains(MapTileIndex.getX(pTileIndex), mLeft, mWidth)) { return false; } return contains(MapTileIndex.getY(pTileIndex), mTop, mH...
@Test public void testCorners() { final MapTileArea area = new MapTileArea(); for (int zoom = 0; zoom <= TileSystem.getMaximumZoomLevel(); zoom++) { final int mapTileUpperBound = getMapTileUpperBound(zoom); final int max = mapTileUpperBound - 1; setNewWorld(area, ...
@Override public RecoverableFsDataOutputStream open(Path path) throws IOException { LOGGER.trace("Opening output stream for path {}", path); Preconditions.checkNotNull(path); GSBlobIdentifier finalBlobIdentifier = BlobUtils.parseUri(path.toUri()); return new GSRecoverableFsDataOutpu...
@Test(expected = IllegalArgumentException.class) public void testOpenWithEmptyBucketName() throws IOException { Path path = new Path("gs:///bar"); writer.open(path); }
protected AccessControlList toAcl(final Acl acl) { if(Acl.EMPTY.equals(acl)) { return null; } if(Acl.CANNED_PRIVATE.equals(acl)) { return AccessControlList.REST_CANNED_PRIVATE; } if(Acl.CANNED_BUCKET_OWNER_FULLCONTROL.equals(acl)) { return Acce...
@Test public void testInvalidOwnerFromServer() { final S3AccessControlListFeature f = new S3AccessControlListFeature(session); final AccessControlList list = new AccessControlList(); list.setOwner(new StorageOwner("", "")); assertEquals(Acl.EMPTY, f.toAcl(list)); }
HollowObjectTypeDataElements[] split(HollowObjectTypeDataElements from, int numSplits) { final int toMask = numSplits - 1; final int toOrdinalShift = 31 - Integer.numberOfLeadingZeros(numSplits); final long[][] currentWriteVarLengthDataPointers; if (numSplits<=0 || !((numSplits&(numSpli...
@Test public void testSplit() throws IOException { HollowObjectTypeDataElementsSplitter splitter = new HollowObjectTypeDataElementsSplitter(); HollowObjectTypeReadState typeReadState = populateTypeStateWith(5); assertEquals(1, typeReadState.numShards()); assertDataUnchanged(typeRead...
public SelectValueMapper<K> getMapper() { return mapper; }
@Test public void shouldBuildMapperWithCorrectExpressions() { // When: final SelectValueMapper<String> mapper = selection.getMapper(); // Then: final List<SelectInfo> selectInfos = mapper.getSelects(); assertThat( selectInfos.get(0).getEvaluator().getExpression(), equalTo(EXPRESSI...
@SuppressWarnings({"deprecation", "checkstyle:linelength"}) public void convertSiteProperties(Configuration conf, Configuration yarnSiteConfig, boolean drfUsed, boolean enableAsyncScheduler, boolean userPercentage, FSConfigToCSConfigConverterParams.PreemptionMode preemptionMode) { yarnSiteConfig...
@Test public void testSiteDisabledPreemptionWithNoPolicyConversion() { // Default mode is nopolicy yarnConfig.setBoolean(FairSchedulerConfiguration.PREEMPTION, false); converter.convertSiteProperties(yarnConfig, yarnConvertedConfig, false, false, false, null); assertFalse("Should not contain...
@Override public Object read(final PostgreSQLPacketPayload payload, final int parameterValueLength) { byte[] bytes = new byte[parameterValueLength]; payload.getByteBuf().readBytes(bytes); return ARRAY_PARAMETER_DECODER.decodeInt4Array(bytes, '{' != bytes[0]); }
@Test void assertRead() { String parameterValue = "{\"11\",\"12\"}"; int expectedLength = 4 + parameterValue.length(); ByteBuf byteBuf = ByteBufTestUtils.createByteBuf(expectedLength); byteBuf.writeInt(parameterValue.length()); byteBuf.writeCharSequence(parameterValue, Standa...
public Map<String, String> build() { Map<String, String> builder = new HashMap<>(); configureFileSystem(builder); configureNetwork(builder); configureCluster(builder); configureSecurity(builder); configureOthers(builder); LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]", ...
@Test @UseDataProvider("clusterEnabledOrNot") public void disable_mmap_if_configured_in_search_additional_props(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled); props.set("sonar.search.javaAdditionalOpts", "-Dnode.store.allow_mmap=false"); Map<String, String> settings =...
public ScanResults run(ScanTarget scanTarget) throws ExecutionException, InterruptedException { return runAsync(scanTarget).get(); }
@Test public void run_whenNoPortScannerInstalled_returnsFailedScanResult() throws ExecutionException, InterruptedException { Injector injector = Guice.createInjector( new FakeUtcClockModule(), new FakePluginExecutionModule(), new FakeServiceFingerprinterBootstrapM...
@Override public PageData<WidgetTypeInfo> findTenantWidgetTypesByTenantId(WidgetTypeFilter widgetTypeFilter, PageLink pageLink) { boolean deprecatedFilterEnabled = !DeprecatedFilter.ALL.equals(widgetTypeFilter.getDeprecatedFilter()); boolean deprecatedFilterBool = DeprecatedFilter.DEPRECATED.equals(...
@Test public void testFindTenantWidgetTypesByTenantId() { UUID tenantId = Uuids.timeBased(); for (int i = 0; i < WIDGET_TYPE_COUNT; i++) { var widgetType = createAndSaveWidgetType(new TenantId(tenantId), i); widgetTypeList.add(widgetType); } PageData<WidgetTyp...
public static Impl join(By clause) { return new Impl(new JoinArguments(clause)); }
@Test @Category(NeedsRunner.class) public void testPojo() { List<CgPojo> pc1Rows = Lists.newArrayList( new CgPojo("user1", 1, "us"), new CgPojo("user1", 2, "us"), new CgPojo("user1", 3, "il"), new CgPojo("user1", 4, "il")); List<CgPojo> pc2Rows = ...
public List<String> toList() { List<String> list = new ArrayList<>(header.size() * 2); Iterator<Map.Entry<String, String>> iterator = iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); list.add(entry.getKey()); list.add...
@Test void testToList() { Header header = Header.newInstance(); List<String> list = header.toList(); assertTrue(list.contains(HttpHeaderConsts.CONTENT_TYPE)); assertTrue(list.contains(MediaType.APPLICATION_JSON)); assertEquals(1, list.indexOf(MediaType.APPLICATION_JSON) - lis...
public static void isGreaterThanOrEqualTo(int value, int minimumValue) { isGreaterThanOrEqualTo( value, minimumValue, String.format("value [%s] is less than minimum value [%s]", value, minimumValue)); }
@Test public void testIsGreaterThanOrEqualTo3() { assertThrows( IllegalArgumentException.class, () -> Precondition.isGreaterThanOrEqualTo(0, 1)); }
public void apply() { if (applied) { throw new IllegalStateException("can't apply twice"); } applied = true; PluginFileWriteRule writeRule = new PluginFileWriteRule( props.nonNullValueAsFile(ProcessProperties.Property.PATH_HOME.getKey()).toPath(), props.nonNullValueAsFile(ProcessPrope...
@Test public void fail_if_runs_twice() { Properties properties = new Properties(); properties.setProperty(PATH_HOME.getKey(), "home"); properties.setProperty(PATH_TEMP.getKey(), "temp"); Props props = new Props(properties); WebSecurityManager securityManager = new WebSecurityManager(pluginSecurity...
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception { return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM); }
@Test public void testExhaustingRetries() throws Exception { Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception")); ConnectException e = assertThrows(ConnectException.class, () -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(50...
public ZookeeperDataSource(final String serverAddr, final String path, Converter<String, T> parser) { super(parser); if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(path)) { throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], path=[%s]", serverAddr, path...
@Test public void testZooKeeperDataSource() throws Exception { TestingServer server = new TestingServer(21812); server.start(); final String remoteAddress = server.getConnectString(); final String path = "/sentinel-zk-ds-demo/flow-HK"; ReadableDataSource<String, List<FlowRu...
@Override public String getRuleKey() { return RULE_KEY; }
@Test public void getRuleKey_returnsTheKey() { assertThat(new MultilineHotspotSensor().getRuleKey()).isEqualTo(MultilineHotspotSensor.RULE_KEY); }
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_attachNonexistentFileWithFile_then_throwsException() { // Given String path = Paths.get("/i/do/not/exist").toString(); File file = new File(path); // Then expectedException.expect(JetException.class); expectedException.expectMessage("Not an exi...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldThrowOnRowTimeValueColumn() { // Given: final CreateStream statement = new CreateStream( SOME_NAME, TableElements.of(tableElement(ROWTIME_NAME.text(), new Type(BIGINT))), false, true, withProperties, false ); // When: final E...
@Override public Void call() { RemoteLogReadResult result; try { LOGGER.debug("Reading records from remote storage for topic partition {}", fetchInfo.topicPartition); FetchDataInfo fetchDataInfo = remoteReadTimer.time(() -> rlm.read(fetchInfo)); brokerTopicStats.t...
@Test public void testRemoteLogReaderWithoutError() throws RemoteStorageException, IOException { FetchDataInfo fetchDataInfo = new FetchDataInfo(logOffsetMetadata, records); when(records.sizeInBytes()).thenReturn(100); when(mockRLM.read(any(RemoteStorageFetchInfo.class))).thenReturn(fetchDat...
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI. public long parse(final String text) { final String date; final String time; final String timezone; if (text.contains("T")) { date = text.substring(0, text.indexOf('T')); final String withTimezone = text.substring(text.i...
@Test public void shouldParseDateTimeWithPositiveTimezones() { assertThat(parser.parse("2017-11-13T23:59:58.999+0100"), is(1510613998999L)); }
public synchronized NumaResourceAllocation allocateNumaNodes( Container container) throws ResourceHandlerException { NumaResourceAllocation allocation = allocate(container.getContainerId(), container.getResource()); if (allocation != null) { try { // Update state store. conte...
@Test public void testAllocateNumaNode() throws Exception { NumaResourceAllocation nodeInfo = numaResourceAllocator .allocateNumaNodes(getContainer( ContainerId.fromString("container_1481156246874_0001_01_000001"), Resource.newInstance(2048, 2))); Assert.assertEquals("0", Strin...
@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 testMinException() { String inputCommand = ListCommand.LIST_MIN_SUB_COMMAND_NAME + "\n" + target2 + "\ne\n"; try { command.execute("l", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!x\n", sWriter.toString()); } catch (Exception e) { e.printStackTrace(); ...
public static void addMetricsContextProperties(Map<String, Object> prop, WorkerConfig config, String clusterId) { //add all properties predefined with "metrics.context." prop.putAll(config.originalsWithPrefix(CommonClientConfigs.METRICS_CONTEXT_PREFIX, false)); //add connect properties p...
@Test public void testAddMetricsContextPropertiesDistributed() { Map<String, String> props = new HashMap<>(); props.put(DistributedConfig.GROUP_ID_CONFIG, "connect-cluster"); props.put(DistributedConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(DistributedConfig.CONFIG_T...
@Override public void transform(Message message, DataType fromType, DataType toType) { final Optional<ValueRange> valueRange = getValueRangeBody(message); String range = message.getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A:A").toString(); String majorDimension = message ...
@Test public void testTransformToValueRangeMultipleRows() throws Exception { Exchange inbound = new DefaultExchange(camelContext); inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A1:B2"); List<String> model = Arrays.asList("{" + ...
public RingbufferStoreConfig getRingbufferStoreConfig() { return ringbufferStoreConfig; }
@Test public void getRingbufferStoreConfig() { final RingbufferConfig config = new RingbufferConfig(NAME); final RingbufferStoreConfig ringbufferConfig = config.getRingbufferStoreConfig(); assertNotNull(ringbufferConfig); assertFalse(ringbufferConfig.isEnabled()); }
public int termLength() { return termLength; }
@Test void throwsIllegalStateExceptionIfLogFileSizeIsLessThanLogMetaDataLength(@TempDir final Path dir) throws IOException { final Path logFile = dir.resolve("test.log"); assertNotNull(Files.createFile(logFile)); final int fileLength = LOG_META_DATA_LENGTH - 5; final byte...
public double calculateDensity(Graph graph, boolean isGraphDirected) { double result; double edgesCount = graph.getEdgeCount(); double nodesCount = graph.getNodeCount(); double multiplier = 1; if (!isGraphDirected) { multiplier = 2; } result = (multi...
@Test public void testTwoCompleteGraphsDensity() { GraphModel graphModel = GraphGenerator.generateCompleteUndirectedGraph(4); UndirectedGraph undirectedGraph = graphModel.getUndirectedGraph(); Node[] nodes = new Node[4]; for (int i = 0; i < 4; i++) { Node currentNode = gr...
public boolean isAttached(Appender<E> appender) { if (appender == null) { return false; } for (Appender<E> a : appenderList) { if (a == appender) return true; } return false; }
@Test public void testIsAttached() throws Exception { NOPAppender<TestEvent> ta = new NOPAppender<TestEvent>(); ta.start(); aai.addAppender(ta); NOPAppender<TestEvent> tab = new NOPAppender<TestEvent>(); tab.setName("test"); tab.start(); aai.addAppender(tab); ...
@Override public ProjectRepositories load(String projectKey, @Nullable String branchBase) { GetRequest request = new GetRequest(getUrl(projectKey, branchBase)); try (WsResponse response = wsClient.call(request)) { try (InputStream is = response.contentStream()) { return processStream(is); ...
@Test public void continueOnHttp404Exception() { when(wsClient.call(any())).thenThrow(new HttpException("/batch/project.protobuf?key=foo%3F", HttpURLConnection.HTTP_NOT_FOUND, "")); ProjectRepositories proj = loader.load(PROJECT_KEY, null); assertThat(proj.exists()).isFalse(); }
@Override public Changeset getChangesetForLine(int lineNumber) { if (!hasChangesetForLine(lineNumber)) { throw new IllegalArgumentException("There's no changeset on line " + lineNumber); } return lineChangesets[lineNumber - 1]; }
@Test public void get_changeset_for_given_line() { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); assertThat(scmInfo.getChangesetForLine(1)).isEqualTo(CHANGESET_1); assertThat(scmInfo.getChangesetForLine(2)).isEqualTo(CHANGESET_2); assertThat(scmInfo.getChangesetForLine(3)).isEqualTo(CH...
@Benchmark @Threads(1) public void testCounterCellReset(CounterCellState counterState) throws Exception { counterState.counterCell.inc(); counterState.counterCell.reset(); counterState.counterCell.inc(); }
@Test public void testCounterCellReset() throws Exception { CounterCellState state = new CounterCellState(); new MetricsBenchmark().testCounterCellReset(state); state.check(); }
@Override public KTable<K, V> toTable() { return toTable(NamedInternal.empty(), Materialized.with(keySerde, valueSerde)); }
@Test public void shouldNotAllowNullMaterializedOnToTableWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.toTable(Named.as("name"), null)); assertThat(exception.getMessage(), equalTo("materialized can't be null"))...
@VisibleForTesting List<MappingRule> getMappingRules(MappingRulesDescription rules) { List<MappingRule> mappingRules = new ArrayList<>(); for (Rule rule : rules.getRules()) { checkMandatoryParameters(rule); MappingRuleMatcher matcher = createMatcher(rule); MappingRuleAction action = create...
@Test public void testFallbackResultUnset() { rule.setFallbackResult(null); List<MappingRule> rules = ruleCreator.getMappingRules(description); MappingRule mpr = rules.get(0); assertEquals("Fallback result", MappingRuleResultType.SKIP, mpr.getFallback().getResult()); }
protected abstract void doBuildListing(Path pathToListFile, DistCpContext distCpContext) throws IOException;
@Test public void testFailOnCloseError() throws IOException { File inFile = File.createTempFile("TestCopyListingIn", null); inFile.deleteOnExit(); File outFile = File.createTempFile("TestCopyListingOut", null); outFile.deleteOnExit(); List<Path> srcs = new ArrayList<Path>(); srcs.add(new Path(...
@Description("Gamma cdf given the shape and scale parameter and value") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double gammaCdf( @SqlType(StandardTypes.DOUBLE) double shape, @SqlType(StandardTypes.DOUBLE) double scale, @SqlType(StandardTypes.DOUBLE) d...
@Test public void testGammaCdf() { assertFunction("round(gamma_cdf(3.0, 4.0, 0.0), 10)", DOUBLE, 0.0); assertFunction("round(gamma_cdf(3.0, 4.0, 1.0), 3)", DOUBLE, 0.002); assertFunction("round(gamma_cdf(3.0, 4.0, 5.0), 3)", DOUBLE, 0.132); assertFunction("round(gamma_cdf(3.0, 4....
public void visit(Entry entry) { final AFreeplaneAction action = new EntryAccessor().getAction(entry); if (action != null) { final EntryAccessor entryAccessor = new EntryAccessor(); String accelerator = entryAccessor.getAccelerator(entry); if(accelerator != null) { map.setDefaultAccelerator(action, acc...
@Test public void registersEntryWithAction() { Entry actionEntry = new Entry(); final AFreeplaneAction action = mock(AFreeplaneAction.class); new EntryAccessor().setAction(actionEntry, action); IAcceleratorMap map = mock(IAcceleratorMap.class); EntriesForAction entries = mock(EntriesForAction.class); fina...
public static Message toProto(final Map<?, ?> inputData, final Message defaultInstance) { ObjectHelper.notNull(inputData, "inputData"); ObjectHelper.notNull(defaultInstance, "defaultInstance"); final Descriptor descriptor = defaultInstance.getDescriptorForType(); final Builder target = ...
@Test public void testIfThrowsErrorInCaseRepeatedFieldIsNotList() { final Map<String, Object> input = new HashMap<>(); input.put("name", "Martin"); input.put("id", 1234); input.put("nicknames", "wrong nickname"); final AddressBookProtos.Person defaultInstance = AddressBookP...
static Entry<String, String> splitTrimmedConfigStringComponent(String input) { int i; for (i = 0; i < input.length(); i++) { if (input.charAt(i) == '=') { break; } } if (i == input.length()) { throw new FormatterException("No equals sig...
@Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); }
static final String addFunctionParameter(ParameterDescriptor descriptor, RuleBuilderStep step) { final String parameterName = descriptor.name(); // parameter name needed by function final Map<String, Object> parameters = step.parameters(); if (Objects.isNull(parameters)) { return nul...
@Test public void addFunctionParameterSyntaxOk_WhenStringParameterValueIsSet() { String parameterName = "foo"; var parameterValue = "bar"; RuleBuilderStep step = mock(RuleBuilderStep.class); Map<String, Object> params = Map.of(parameterName, parameterValue); when(step.paramet...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testSetNonDefaultSlotSharingInHybridMode() { Configuration configuration = new Configuration(); // set all edge to HYBRID_FULL result partition type. configuration.set( ExecutionOptions.BATCH_SHUFFLE_MODE, BatchShuffleMode.ALL_EXCHANGES_HYBRID_FULL); final...
@Override public void close() { _zkClient.close(); }
@Test public void testCloseZkClient() { _dynamicBrokerSelectorUnderTest.close(); Mockito.verify(_mockZkClient, times(1)).close(); }
@Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long endTimeNanos = System.nanoTime() + unit.toNanos(timeout); ArrayList<ManagedChannel> channels = new ArrayList<>(); synchronized (this) { if (!shutdownStarted) { return false; } ...
@Test public void testAwaitTermination() throws Exception { ManagedChannel mockChannel = mock(ManagedChannel.class); when(channelSupplier.get()).thenReturn(mockChannel); IsolationChannel isolationChannel = IsolationChannel.create(channelSupplier); assertFalse(isolationChannel.awaitTermination(1, Tim...
@VisibleForTesting protected void handleException( String message, Exception exception, StringBuilder text, StringBuilder details ) { if ( exception instanceof KettleException ) { // Normal error KettleException ke = (KettleException) exception; Throwable cause = ke.getCause(); if ( cause ...
@Test public void setErrorTextWithCauseExceptionWithoutCauseMessage() { //cause without message ClientProtocolException cpe = new ClientProtocolException( ); Exception e = new KettleException( "kettleMessage", cpe ); StringBuilder text = new StringBuilder(); StringBuilder details = new StringBu...
public boolean evaluate( RowMetaInterface rowMeta, Object[] r ) { // Start of evaluate boolean retval = false; // If we have 0 items in the list, evaluate the current condition // Otherwise, evaluate all sub-conditions // try { if ( isAtomic() ) { if ( function == FUNC_TRUE ) { ...
@Test public void testNullLargerOrEqualsThanZero() { String left = "left"; String right = "right"; Long leftValue = null; Long rightValue = 0L; RowMetaInterface rowMeta = new RowMeta(); rowMeta.addValueMeta( new ValueMetaInteger( left ) ); rowMeta.addValueMeta( new ValueMetaInteger( righ...
protected void validateMessageType(Type expected) { if (expected != messageType) { throw new IllegalArgumentException("Message type is expected to be " + expected + " but got " + messageType); } }
@Test public void testValidateMessage() { RpcMessage msg = getRpcMessage(0, RpcMessage.Type.RPC_CALL); msg.validateMessageType(RpcMessage.Type.RPC_CALL); }
public static int parseIntAscii(final CharSequence cs, final int index, final int length) { if (length <= 0) { throw new AsciiNumberFormatException("empty string: index=" + index + " length=" + length); } final boolean negative = MINUS_SIGN == cs.charAt(index); i...
@Test void parseIntAsciiRoundTrip() { final String prefix = "testInt"; final StringBuilder buffer = new StringBuilder(24); buffer.append(prefix); for (int i = 0; i < ITERATIONS; i++) { final int value = ThreadLocalRandom.current().nextInt(); buffe...
public void registerUrl( String urlString ) { if ( urlString == null || addedAllClusters == true ) { return; //We got no url or already added all clusters so nothing to do. } if ( urlString.startsWith( VARIABLE_START ) ) { addAllClusters(); } Pattern r = Pattern.compile( URL_PATTERN ); ...
@Test public void testRegisterUrlFullVariable() throws Exception { when( mockNamedClusterService.listNames( mockMeta.getMetaStore() ) ) .thenReturn( Arrays.asList( CLUSTER1_NAME, CLUSTER2_NAME ) ); namedClusterEmbedManager.registerUrl( "${variable)" ); verify( mockMetaStoreFactory ).saveElement( mo...
@VisibleForTesting void readCacheAt(long offset) throws IOException { DiskRange newCacheRange = regionFinder.getRangeFor(offset); cachePosition = newCacheRange.getOffset(); cacheLength = newCacheRange.getLength(); if (cache.length < cacheLength) { cache = ...
@Test public void testTinyStripesReadCacheAt() throws IOException { DataSize maxMergeDistance = new DataSize(1, Unit.MEGABYTE); DataSize tinyStripeThreshold = new DataSize(8, Unit.MEGABYTE); OrcAggregatedMemoryContext systemMemoryContext = new TestingHiveOrcAggregatedMemoryC...
static void addClusterToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) { config.put(configPrefix + "alias", cluster.getAlias()); config.put(configPrefix + AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers()); ...
@Test public void testAddClusterToMirrorMaker2ConnectorConfigWithScramAndTlsEncryption() { Map<String, Object> config = new HashMap<>(); KafkaMirrorMaker2ClusterSpec cluster = new KafkaMirrorMaker2ClusterSpecBuilder() .withAlias("sourceClusterAlias") .withBootstrapSer...
@Override public DataType getType() { return DataType.META_DATA; }
@Test public void testGetType() { Assertions.assertEquals(DataType.META_DATA, metadataExecutorSubscriber.getType()); }
public static String getFormat(final String originalFilename) { final List<String> fileNameSplit = Splitter.on(".").splitToList(originalFilename); if (fileNameSplit.size() <= 1) { throw new BadRequestException("The file format is invalid."); } return fileNameSplit.get(fileNameSplit.size() - 1); ...
@Test public void getFormat() { final String properties = ConfigFileUtils.getFormat("application+default+application.properties"); assertEquals("properties", properties); final String yml = ConfigFileUtils.getFormat("application+default+application.yml"); assertEquals("yml", yml); }
@Override public ExecuteContext before(ExecuteContext context) { Object argument = context.getArguments()[0]; if (argument instanceof InstanceInfo) { InstanceInfo instanceInfo = (InstanceInfo) argument; AppCache.INSTANCE.setAppName(instanceInfo.getAppName()); Spri...
@Test public void testBefore() { interceptor.before(context); // ek will capitalize the service name, so the expected value here is also capitalized Assert.assertEquals("FOO", AppCache.INSTANCE.getAppName()); InstanceInfo instanceInfo = (InstanceInfo) context.getArguments()[0]; ...
@Override public final byte readByte() throws EOFException { final int ch = read(); if (ch < 0) { throw new EOFException(); } return (byte) (ch); }
@Test(expected = EOFException.class) public void testReadBytePosition_EOF() throws Exception { in.readByte(INIT_DATA.length + 1); }
public int getTimeToLiveSeconds() { return timeToLiveSeconds; }
@Test public void testGetTimeToLiveSeconds() { assertEquals(MapConfig.DEFAULT_TTL_SECONDS, new MapConfig().getTimeToLiveSeconds()); }
@Nonnull public static <T> Traverser<T> traverseStream(@Nonnull Stream<T> stream) { return traverseSpliterator(stream.spliterator()).onFirstNull(stream::close); }
@Test public void when_traverseStream_then_seeAllItems() { validateTraversal(traverseStream(of(1, 2))); }
@Override public PostDO getPost(Long id) { return postMapper.selectById(id); }
@Test public void testGetPost() { // mock 数据 PostDO dbPostDO = randomPostDO(); postMapper.insert(dbPostDO); // 准备参数 Long id = dbPostDO.getId(); // 调用 PostDO post = postService.getPost(id); // 断言 assertNotNull(post); assertPojoEquals(dbP...
public Set<Device> getDevicesFromPath(String path) throws IOException { MutableInt counter = new MutableInt(0); try (Stream<Path> stream = Files.walk(Paths.get(path), 1)) { return stream.filter(p -> p.toFile().getName().startsWith("veslot")) .map(p -> toDevice(p, counter)) .collect...
@Test public void testDetectMultipleOnlineDevices() throws IOException { createVeSlotFile(0); createVeSlotFile(1); createVeSlotFile(2); createOsStateFile(0); when(mockCommandExecutor.getOutput()).thenReturn( "8:1:character special file", "9:1:character special file", "a:1:c...
public void changeNumber(final Account account, final String number, final UUID phoneNumberIdentifier, final Optional<UUID> maybeDisplacedAccountIdentifier, final Collection<TransactWriteItem> additionalWriteItems) { CHANGE_NUMBER_TIMER.record(() -> { final String originalNumber = acc...
@Test public void testChangeNumberConflict() { final String originalNumber = "+14151112222"; final String targetNumber = "+14151113333"; final UUID originalPni = UUID.randomUUID(); final UUID targetPni = UUID.randomUUID(); final Device existingDevice = generateDevice(DEVICE_ID_1); final Acco...
public static <T> Object create(Class<T> iface, T implementation, RetryPolicy retryPolicy) { return RetryProxy.create(iface, new DefaultFailoverProxyProvider<T>(iface, implementation), retryPolicy); }
@Test public void testTryOnceThenFail() throws Exception { RetryPolicy policy = mock(TryOnceThenFail.class); RetryPolicy realPolicy = TRY_ONCE_THEN_FAIL; setupMockPolicy(policy, realPolicy); UnreliableInterface unreliable = (UnreliableInterface) RetryProxy.create(UnreliableInterface.class, unre...
@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 testValidateAndGetSchedulerConfigurationInvalidConfig() throws IOException { Configuration config = CapacitySchedulerConfigGeneratorForTest .createBasicCSConfiguration(); ResourceScheduler scheduler = prepareCSForValidation(config); SchedConfUpdateInfo mutationInfo...
public Future<KafkaVersionChange> reconcile() { return getPods() .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testDowngradeWithAllVersionAndMixedPods(VertxTestContext context) { VersionChangeCreator vcc = mockVersionChangeCreator( mockKafka(VERSIONS.version(KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION).version(), VERSIONS.version(KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION).metada...
public static String readClasspathResource(Class<?> relativeTo, String resourcePath) { try { InputStream resourceStream = relativeTo.getResourceAsStream(resourcePath); if (resourceStream == null) { throw new IllegalStateException(getErrorMessage(relativeTo, resourcePath)); } return I...
@Test public void whenReadValidClasspathResource_thenReadIt() { String result = ResourceUtils.readClasspathResource(ResourceUtilsTest.class, "classpath_resource.txt"); assertThat(result) .isEqualTo("OK\n"); }
public static Timestamp next(Timestamp timestamp) { if (timestamp.equals(Timestamp.MAX_VALUE)) { return timestamp; } final int nanos = timestamp.getNanos(); final long seconds = timestamp.getSeconds(); if (nanos + 1 >= NANOS_PER_SECOND) { return Timestamp.ofTimeSecondsAndNanos(seconds +...
@Test public void testNextIncrementsNanosWhenPossible() { assertEquals( Timestamp.ofTimeSecondsAndNanos(10L, 999999999), TimestampUtils.next(Timestamp.ofTimeSecondsAndNanos(10L, 999999998))); }
@Override public boolean isValid(ParameterValue value) { return choices.contains(((StringParameterValue) value).getValue()); }
@Test @Issue("JENKINS-62889") public void checkValue_Invalid() { String stringValue = "single"; String[] choices = new String[]{stringValue}; ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition("name", choices, "description"); StringParameterValue parame...
public long getNumBlocksFailedToCache() { return numBlocksFailedToCache.longValue(); }
@Test(timeout=600000) public void testFilesExceedMaxLockedMemory() throws Exception { LOG.info("beginning testFilesExceedMaxLockedMemory"); // Create some test files that will exceed total cache capacity final int numFiles = 5; final long fileSize = CACHE_CAPACITY / (numFiles-1); final Path[] te...
@Override public RecoverableWriter.ResumeRecoverable persist() throws IOException { LOGGER.trace("Persisting write channel for blob {}", finalBlobIdentifier); closeWriteChannelIfExists(); return createResumeRecoverable(); }
@Test public void shouldPersist() throws IOException { if (!closed) { GSResumeRecoverable recoverable = (GSResumeRecoverable) fsDataOutputStream.persist(); assertEquals(blobIdentifier, recoverable.finalBlobIdentifier); if (empty) { assertEquals(0, recovera...
@Override public ProducerConnection examineProducerConnectionInfo(String producerGroup, final String topic) throws RemotingException, MQClientException, InterruptedException, MQBrokerException { return defaultMQAdminExtImpl.examineProducerConnectionInfo(producerGroup, topic); }
@Test public void testExamineProducerConnectionInfo() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { ProducerConnection producerConnection = defaultMQAdminExt.examineProducerConnectionInfo("default-producer-group", "unit-test"); assertThat(producerConnection.g...
protected static void configureMulticastSocket(MulticastSocket multicastSocket, Address bindAddress, HazelcastProperties hzProperties, MulticastConfig multicastConfig, ILogger logger) throws SocketException, IOException, UnknownHostException { multicastSocket.setReuseAddress(true); ...
@Test public void testSetInterfaceDefaultWhenNonLoopbackAddrAndNoLoopbackMode() throws Exception { Config config = createConfig(null); MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig(); multicastConfig.setLoopbackModeEnabled(false); MulticastS...
public static Optional<Object> invokeMethod(Object target, String methodName, Class<?>[] paramsType, Object[] params) { if (methodName == null || target == null) { return Optional.empty(); } final Optional<Method> method = findMethod(target.getClass(), methodName, paramsT...
@Test public void testInvokeMethod1() { int params = 88; final Optional<Object> staticMethod = ReflectUtils .invokeMethod(TestReflect.class, "staticMethod", new Class[]{int.class}, new Object[]{params}); Assert.assertTrue(staticMethod.isPresent() && st...
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testPerms() throws Exception { createHttpFSServer(false, false); FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf()); fs.mkdirs(new Path("/perm")); createWithHttp("/perm/none", null); String statusJson = getStatus("/perm/none", "GETF...
@Nonnull public static <T> FunctionEx<T, T> wholeItem() { return FunctionEx.identity(); }
@Test public void when_wholeItem() { Object o = new Object(); assertSame(o, wholeItem().apply(o)); }
public static final StartTime absolute(Instant absoluteStart) { return new StartTime(StartTimeOption.ABSOLUTE, null, absoluteStart); }
@Test public void testStartAbsolute() { StartTime st = StartTime.absolute(OffsetDateTime .of(2017, 3, 20, 11, 43, 11, 0, ZoneOffset.ofHours(-7)) .toInstant()); assertEquals(StartTimeOption.ABSOLUTE, st.option()); assertNull(st.relativeTime()); assertEq...
public static void install() { installBasic(); installLight(); installSemiBold(); }
@Test void testFont() { FlatRobotoFont.install(); testFont( FlatRobotoFont.FAMILY, Font.PLAIN, 13 ); testFont( FlatRobotoFont.FAMILY, Font.ITALIC, 13 ); testFont( FlatRobotoFont.FAMILY, Font.BOLD, 13 ); testFont( FlatRobotoFont.FAMILY, Font.BOLD | Font.ITALIC, 13 ); testFont( FlatRobotoFont.FAMILY_LIGHT,...
public String process(final Expression expression) { return formatExpression(expression); }
@Test public void shouldEscapeQuotesInStringLiteral() { // Given: final Expression expression = new StringLiteral("\"foo\""); // When: final String javaExpression = sqlToJavaVisitor.process(expression); // Then: assertThat(javaExpression, equalTo("\"\\\"foo\\\"\"")); }
public static CheckpointedInputGate[] createCheckpointedMultipleInputGate( MailboxExecutor mailboxExecutor, List<IndexedInputGate>[] inputGates, TaskIOMetricGroup taskIOMetricGroup, CheckpointBarrierHandler barrierHandler, StreamConfig config) { regis...
@Test void testCreateCheckpointedMultipleInputGate() throws Exception { try (CloseableRegistry registry = new CloseableRegistry()) { MockEnvironment environment = new MockEnvironmentBuilder().build(); MockStreamTask streamTask = new MockStreamTaskBuilder(environment).build(); ...
@Override public List<UsbSerialPort> getPorts() { return mPorts; }
@Test public void compositeDevice() throws Exception { UsbDeviceConnection usbDeviceConnection = mock(UsbDeviceConnection.class); UsbDevice usbDevice = mock(UsbDevice.class); UsbInterface massStorageInterface = mock(UsbInterface.class); UsbInterface controlInterface = mock(UsbInterfa...
@Deprecated public RegistryBuilder transport(String transport) { this.transporter = transport; return getThis(); }
@Test void transport() { RegistryBuilder builder = new RegistryBuilder(); builder.transport("transport"); Assertions.assertEquals("transport", builder.build().getTransport()); }
private boolean autoscale(ApplicationId applicationId, ClusterSpec.Id clusterId) { boolean redeploy = false; boolean enabled = enabledFlag.with(Dimension.INSTANCE_ID, applicationId.serializedForm()).value(); boolean logDetails = enableDetailedLoggingFlag.with(Dimension.INSTANCE_ID, applicationId...
@Test public void test_autoscaling_window() { ApplicationId app1 = AutoscalingMaintainerTester.makeApplicationId("app1"); ClusterSpec cluster1 = AutoscalingMaintainerTester.containerClusterSpec(); NodeResources lowResources = new NodeResources(4, 4, 10, 0.1); NodeResources highResour...
@Override public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return join(otherStream, toValueJoinerWithKey(joiner), w...
@Test public void shouldNotAllowNullTableOnJoinWithGlobalTableWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join( null, MockMapper.selectValueMapper(), MockValueJoiner.TO...
static void readFullyDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException { int nextReadLength = Math.min(buf.remaining(), temp.length); int bytesRead = 0; while (nextReadLength > 0 && (bytesRead = f.read(temp, 0, nextReadLength)) >= 0) { buf.put(temp, 0, bytesRead); next...
@Test public void testDirectReadFullySmallReads() throws Exception { final ByteBuffer readBuffer = ByteBuffer.allocateDirect(10); MockInputStream stream = new MockInputStream(2, 3, 3); DelegatingSeekableInputStream.readFullyDirectBuffer(stream, readBuffer, TEMP.get()); Assert.assertEquals(10, readBu...
public static byte[] nextBytes(final byte[] bytes) { Requires.requireNonNull(bytes, "bytes"); final int len = bytes.length; if (len == 0) { // fast path return new byte[] { 0 }; } final byte[] nextBytes = new byte[len + 1]; System.arraycopy(bytes, 0, nextBytes...
@Test public void testNextBytes() { Assert.assertArrayEquals(new byte[] { 0 }, BytesUtil.nextBytes(new byte[] {})); Assert.assertArrayEquals(new byte[] { 1, 2, 0 }, BytesUtil.nextBytes(new byte[] { 1, 2 })); }
public void set(Writable obj) { instance = obj; Class<? extends Writable> instanceClazz = instance.getClass(); Class<? extends Writable>[] clazzes = getTypes(); for (int i = 0; i < clazzes.length; i++) { Class<? extends Writable> clazz = clazzes[i]; if (clazz.equals(instanceClazz)) { ...
@Test public void testSet() throws Exception { Foo foo = new Foo(); FooGenericWritable generic = new FooGenericWritable(); //exception should not occur generic.set(foo); try { //exception should occur, since IntWritable is not registered generic = new FooGenericWritable(); gener...
public SQLTranslatorContext translate(final String sql, final List<Object> parameters, final QueryContext queryContext, final DatabaseType storageType, final ShardingSphereDatabase database, final RuleMetaData globalRuleMetaData) { DatabaseType sqlParserType = queryCont...
@Test void assertUseOriginalSQLWhenTranslatingFailed() { String expected = "ERROR: select 1"; DatabaseType sqlParserType = TypedSPILoader.getService(DatabaseType.class, "PostgreSQL"); QueryContext queryContext = mock(QueryContext.class, RETURNS_DEEP_STUBS); when(queryContext.getSqlSt...
@Override public void onError(Throwable e) { // individual callbacks are notified first for (Callback<RestResponse> callback : _callbacks.values()) { callback.onError(e); } // aggregated callback is guaranteed to be called after all individual callbacks _aggregatedCallback.onError(e); ...
@Test public void testError() throws Exception { FutureCallback<RestResponse> callback1 = new FutureCallback<>(); FutureCallback<RestResponse> callback2 = new FutureCallback<>(); ImmutableMap<Integer, Callback<RestResponse>> individualCallbacks = ImmutableMap.<Integer, Callback<RestResponse>>of(ID1, ca...
public static Map<String, DataSource> create(final Map<String, DataSourcePoolProperties> propsMap, final boolean cacheEnabled) { Map<String, DataSource> result = new LinkedHashMap<>(propsMap.size(), 1F); for (Entry<String, DataSourcePoolProperties> entry : propsMap.entrySet()) { result.put(e...
@Test void assertCreateMap() { Map<String, DataSource> actual = DataSourcePoolCreator.create(Collections.singletonMap("foo_ds", new DataSourcePoolProperties(MockedDataSource.class.getName(), createProperties())), true); assertThat(actual.size(), is(1)); assertDataSource((MockedDataSource) ac...
public int getTailMatchLength(ElementPath p) { if (p == null) { return 0; } int lSize = this.partList.size(); int rSize = p.partList.size(); // no match possible for empty sets if ((lSize == 0) || (rSize == 0)) { return 0; } int ...
@Test public void testTailMatch() { { ElementPath p = new ElementPath("/a/b"); ElementSelector ruleElementSelector = new ElementSelector("*"); assertEquals(0, ruleElementSelector.getTailMatchLength(p)); } { ElementPath p = new ElementPath("/a"...
@Deactivate public void deactivate() { sessionMap.clear(); snmpDeviceMap.clear(); log.info("Stopped"); }
@Test public void testDeactivate() { snmpController.deactivate(); assertEquals("Device map should be clear", 0, snmpController.getDevices().size()); assertEquals("Session map should be clear", 0, snmpController.sessionMap.size()); }
@Override public Optional<Rule> findByKey(RuleKey key) { verifyKeyArgument(key); ensureInitialized(); return Optional.ofNullable(rulesByKey.get(key)); }
@Test public void findByKey_returns_empty_if_argument_is_deprecated_key_in_DB_of_rule_in_DB() { Optional<Rule> rule = underTest.findByKey(DEPRECATED_KEY_OF_NON_EXITING_RULE); assertThat(rule).isEmpty(); }
public static <T> ListCoder<T> of(Coder<T> elemCoder) { return new ListCoder<>(elemCoder); }
@Test public void testListWithNullsAndVarIntCoderThrowsException() throws Exception { thrown.expect(CoderException.class); thrown.expectMessage("cannot encode a null Integer"); List<Integer> list = Arrays.asList(1, 2, 3, null, 4); Coder<List<Integer>> coder = ListCoder.of(VarIntCoder.of()); Coder...
@Override public void applyToConfiguration(Configuration configuration) { super.applyToConfiguration(configuration); merge(configuration, pythonConfiguration); }
@Test void testCreateProgramOptionsWithLongOptions() throws CliArgsException { String[] args = { "--python", "xxx.py", "--pyModule", "xxx", "--pyFiles", "/absolute/a.py,relative/b.py,relative/c.py", "--pyRequirements", ...