focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public SerializableFunction<Row, T> getFromRowFunction() { return fromRowFunction; }
@Test public void testEnumRowToProto() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(EnumMessage.getDescriptor()); SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction(); assertEquals(ENUM_PROTO.toString(), fromRow.apply(ENUM_ROW).toString()); }
@Override public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) { //This code path cannot accept content types or accept types that contain //multipart/related. This is because these types of requests will usually have very large payloads and therefor...
@SuppressWarnings({"unchecked"}) @Test(dataProvider = "restOrStream") public void testAsyncServer(final RestOrStream restOrStream) throws Exception { final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class); statusResource.get(eq(1L), EasyMock.<Callback<St...
public FieldType calcFieldType( String content ) { final SnippetBuilder.SnippetType snippetType = SnippetBuilder.getType( content ); if ( snippetType == SnippetBuilder.SnippetType.FORALL ) { return FieldType.FORALL_FIELD; } else if ( snippetType != SnippetBuilder.SnippetType.SINGLE )...
@Test public void testIdentifyFieldTypes() { builder = new LhsBuilder(9, 1, ""); assertThat(builder.calcFieldType("age")).isEqualTo(SINGLE_FIELD); assertThat(builder.calcFieldType("age <")).isEqualTo(OPERATOR_FIELD); assertThat(builder.calcFieldType("age < $param")).isEqualT...
public <T extends AbstractMessageListenerContainer> T decorateMessageListenerContainer(T container) { Advice[] advice = prependTracingMessageContainerAdvice(container); if (advice != null) { container.setAdviceChain(advice); } return container; }
@Test void decorateDirectMessageListenerContainer_prepends_as_first_when_absent() { DirectMessageListenerContainer listenerContainer = new DirectMessageListenerContainer(); listenerContainer.setAdviceChain(new CacheInterceptor()); assertThat(rabbitTracing.decorateMessageListenerContainer(listenerContainer)...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 2) { onInvalidDataReceived(device, data); return; } final int interval = data.getIntValue(Data.FORMAT_UINT16_LE, 0); onMeasurementIntervalRece...
@Test public void onMeasurementIntervalReceived() { final ProfileReadResponse response = new MeasurementIntervalDataCallback() { @Override public void onMeasurementIntervalReceived(@NonNull final BluetoothDevice device, final int interval) { called = true; assertEquals("Interval", 60, interval); } ...
@Override public String toString() { return topicId + ":" + topic() + "-" + partition(); }
@Test public void testToString() { assertEquals("vDiRhkpVQgmtSLnsAZx7lA:a_topic_name-1", topicIdPartition0.toString()); assertEquals("vDiRhkpVQgmtSLnsAZx7lA:null-1", topicIdPartitionWithNullTopic0.toString()); }
@Override public Flux<ReactiveRedisConnection.BooleanResponse<RenameCommand>> renameNX(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null...
@Test public void testRenameNX() { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyFo...
@Override public CompletableFuture<Boolean> triggerCheckpointAsync( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) { if (!externallyInducedCheckpoints) { if (isSynchronousSavepoint(checkpointOptions.getCheckpointType())) { return triggerSt...
@Test void testTriggeringStopWithSavepointWithDrain() throws Exception { SourceFunction<String> testSource = new EmptySource(); CompletableFuture<Boolean> checkpointCompleted = new CompletableFuture<>(); CheckpointResponder checkpointResponder = new TestCheckpointResponder()...
public static <T> Global<T> globally() { return new Global<>(); }
@Test @Category(NeedsRunner.class) public void testGloballyWithSchemaAggregateFn() { Collection<Aggregate> elements = ImmutableList.of( Aggregate.of(1, 1, 2), Aggregate.of(2, 1, 3), Aggregate.of(3, 2, 4), Aggregate.of(4, 2, 5)); PCollection<Row> aggre...
static final String generateForFragment(RuleBuilderStep step, Configuration configuration) { final String fragmentName = step.function(); try { Template template = configuration.getTemplate(fragmentName); StringWriter writer = new StringWriter(); Map<String, Object> f...
@Test public void generateForFragmentConvertsFreemarkerTemplate() { RuleBuilderStep step = mock(RuleBuilderStep.class); when(step.function()).thenReturn("test_fragment1"); Map<String, Object> params = Map.of("field", "my_field"); when(step.parameters()).thenReturn(params); as...
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) { CsvIOParseHelpers.validateCsvFormat(csvFormat); CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema); RowCoder coder = RowCoder.of(schema); CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.bui...
@Test public void givenStringToRecordError_RecordToObjectError_emits() { Pipeline pipeline = Pipeline.create(); PCollection<String> input = pipeline.apply( Create.of("true,\"1.1,3.141592,1,5,foo", "true,1.1,3.141592,this_is_an_error,5,foo")); Schema schema = Schema.builder() ...
public boolean verifyTopicCleanupPolicyOnlyCompact(String topic, String workerTopicConfig, String topicPurpose) { Set<String> cleanupPolicies = topicCleanupPolicy(topic); if (cleanupPolicies.isEmpty()) { log.info("Unable to use admin client to verify the cleanup policy of '{}' " ...
@Test public void verifyingTopicCleanupPolicyShouldFailWhenTopicHasDeleteAndCompactPolicy() { String topicName = "myTopic"; Map<String, String> topicConfigs = Collections.singletonMap("cleanup.policy", "delete,compact"); Cluster cluster = createCluster(1); try (MockAdminClient mockAd...
public static String extractMulti(Pattern pattern, CharSequence content, String template) { if (null == content || null == pattern || null == template) { return null; } //提取模板中的编号 final TreeSet<Integer> varNums = new TreeSet<>((o1, o2) -> ObjectUtil.compare(o2, o1)); final Matcher matcherForTemplate = Pat...
@Test public void extractMultiTest() { // 抽取多个分组然后把它们拼接起来 final String resultExtractMulti = ReUtil.extractMulti("(\\w)aa(\\w)", content, "$1-$2"); assertEquals("Z-a", resultExtractMulti); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testUnpartitionedHours() throws Exception { createUnpartitionedTable(spark, tableName); SparkScanBuilder builder = scanBuilder(); HoursFunction.TimestampToHoursFunction function = new HoursFunction.TimestampToHoursFunction(); UserDefinedScalarFunc udf = toUDF(function, expr...
public SerializableFunction<Row, T> getFromRowFunction() { return fromRowFunction; }
@Test public void testOneOfRowToProto() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(OneOf.getDescriptor()); SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction(); assertEquals(ONEOF_PROTO_INT32.toString(), fromRow.apply(ONEOF_ROW_INT32).toString()); ...
@Override public void unregister(final Collection<TopicPartition> revokedChangelogs) { // Only changelogs that are initialized have been added to the restore consumer's assignment final List<TopicPartition> revokedInitializedChangelogs = new ArrayList<>(); for (final TopicPartition partitio...
@Test public void shouldNotThrowOnUnknownRevokedPartition() { try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister(StoreChangelogReader.class)) { appender.setClassLogger(StoreChangelogReader.class, Level.DEBUG); changelogReader.unregister(Collections.singleto...
@Override public ServletRequest getRequest(javax.servlet.ServletRequest servletRequest) { return new JettyRequest(servletRequest); }
@Test public void shouldGetJettyRequest() { ServletRequest request = new JettyServletHelper().getRequest(mock(Request.class)); assertThat(request instanceof JettyRequest, is(true)); }
public static boolean isNotBlank(String str) { return !isBlank(str); }
@Test public void testIsNotBlank() { Assert.assertFalse(EagleEyeCoreUtils.isNotBlank("")); Assert.assertFalse(EagleEyeCoreUtils.isNotBlank(" ")); Assert.assertFalse(EagleEyeCoreUtils.isNotBlank(null)); Assert.assertTrue(EagleEyeCoreUtils.isNotBlank("foo")); }
public static int toInt(final String str, final int defaultValue) { if (str == null) { return defaultValue; } try { return Integer.parseInt(str); } catch (NumberFormatException nfe) { return defaultValue; } }
@Test public void testToInReturnDefaultValueWithFormatIsInvalid() { Assertions.assertEquals(10, NumberUtils.toInt("nine", 10)); }
public static void main(String[] args) { try { FSConfigToCSConfigArgumentHandler fsConfigConversionArgumentHandler = new FSConfigToCSConfigArgumentHandler(); int exitCode = fsConfigConversionArgumentHandler.parseAndConvert(args); if (exitCode != 0) { LOG.error(FATAL, ...
@Test public void testConvertFSConfigurationWithConsoleParam() throws Exception { setupFSConfigConversionFiles(); FSConfigToCSConfigConverterMain.main(new String[] { "-p", "-e", "-y", YARN_SITE_XML, "-f", FS_ALLOC_FILE, "-r", CONVERSION_RULES_FILE}); String ...
public synchronized long nextId() { long timestamp = genTime(); if (timestamp < this.lastTimestamp) { if (this.lastTimestamp - timestamp < timeOffset) { // 容忍指定的回拨,避免NTP校时造成的异常 timestamp = lastTimestamp; } else { // 如果服务器时间有问题(时钟后退) 报错。 throw new IllegalStateException(StrUtil.format("Clock mov...
@Test public void snowflakeTest1(){ //构建Snowflake,提供终端ID和数据中心ID final Snowflake idWorker = new Snowflake(0, 0); final long nextId = idWorker.nextId(); assertTrue(nextId > 0); }
@Override public double getWeight(int source, int target) { if (digraph) { for (Edge edge : graph[source]) { if (edge.v2 == target) { return edge.weight; } } } else { for (Edge edge : graph[source]) { ...
@Test public void testGetWeight() { System.out.println("getWeight"); assertEquals(0.0, g1.getWeight(1, 2), 1E-10); assertEquals(0.0, g1.getWeight(1, 1), 1E-10); assertEquals(1.0, g2.getWeight(1, 2), 1E-10); assertEquals(1.0, g2.getWeight(2, 1), 1E-10); assertEquals(...
public Object stringToKey(String s) { char type = s.charAt(0); switch (type) { case 'S': // this is a String, NOT a Short. For Short see case 'X'. return s.substring(2); case 'I': // This is an Integer return Integer.valueOf(s.substring(2)); ...
@Test(expectedExceptions = CacheException.class) public void testStringToKeyWithInvalidTransformer() { keyTransformationHandler.stringToKey("T:org.infinispan.InexistentTransformer:key1"); }
public void transmit(final int msgTypeId, final DirectBuffer srcBuffer, final int srcIndex, final int length) { checkTypeId(msgTypeId); checkMessageLength(length); final AtomicBuffer buffer = this.buffer; long currentTail = buffer.getLong(tailCounterIndex); int recordOffset ...
@Test void shouldThrowExceptionWhenMessageTypeIdInvalid() { final int invalidMsgId = -1; final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]); assertThrows(IllegalArgumentException.class, () -> broadcastTransmitter.transmit(invalidMsgId, srcBuffer, 0, 32)); }
@Override public Collection<PluginInfo> getPluginInfos() { checkState(started.get(), NOT_STARTED_YET); return Set.copyOf(pluginInfosByKeys.values()); }
@Test public void getPluginInfos_throws_ISE_if_repo_is_not_started() { assertThatThrownBy(() -> underTest.getPluginInfos()) .isInstanceOf(IllegalStateException.class) .hasMessage("not started yet"); }
public void contains(@Nullable Object rowKey, @Nullable Object columnKey) { if (!checkNotNull(actual).contains(rowKey, columnKey)) { /* * TODO(cpovirk): Consider including information about whether any cell with the given row * *or* column was present. */ failWithActual( s...
@Test public void contains() { ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val"); assertThat(table).contains("row", "col"); }
@Override public int chown(String path, long uid, long gid) { return AlluxioFuseUtils.call(LOG, () -> chownInternal(path, uid, gid), FuseConstants.FUSE_CHOWN, "path=%s,uid=%d,gid=%d", path, uid, gid); }
@Test @DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu", comment = "waiting on security metadata to be implemented in Dora") @Ignore public void chown() throws Exception { Optional<Long> uid = AlluxioFuseUtils.getUid(System.getProperty("user.name")); // avoid using the launch ...
public static Slime jsonToSlimeOrThrow(String json) { return jsonToSlimeOrThrow(json.getBytes(StandardCharsets.UTF_8)); }
@Test public void test_json_to_slime_or_throw() { Slime slime = SlimeUtils.jsonToSlimeOrThrow("{\"foo\":\"foobie\",\"bar\":{}}"); assertEquals("foobie", slime.get().field("foo").asString()); assertTrue(slime.get().field("bar").valid()); }
@Udf public String concatWS( @UdfParameter(description = "Separator string and values to join") final String... inputs) { if (inputs == null || inputs.length < 2) { throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments."); } final String separator = inputs[0...
@Test public void shouldFailIfOnlySeparatorStringInput() { // When: final KsqlException e = assertThrows(KsqlFunctionException.class, () -> udf.concatWS("SEP")); // Then: assertThat(e.getMessage(), containsString("expects at least two input arguments")); }
@ApiOperation(value = "List engine properties", tags = { "Engine" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the properties are returned."), }) @GetMapping(value = "/management/properties", produces = "application/json") public Map<String, String> getProperties(...
@Test public void testGetProperties() throws Exception { CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROPERTIES_COLLECTION)), HttpStatus.SC_OK); Map<String, String> properties = managementService.get...
@ApiOperation(value = "Assign dashboard to edge (assignDashboardToEdge)", notes = "Creates assignment of an existing dashboard to an instance of The Edge. " + EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION + "Second, remote edge service will receive a copy of assignment das...
@Test public void testAssignDashboardToEdge() throws Exception { Edge edge = constructEdge("My edge", "default"); Edge savedEdge = doPost("/api/edge", edge, Edge.class); Dashboard dashboard = new Dashboard(); dashboard.setTitle("My dashboard"); Dashboard savedDashboard = doP...
@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 shouldNotAllowNullValueJoinerOnJoinWithGlobalTableWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join( testGlobalTable, MockMapper.selectValueMapper(), (...
public synchronized @Nullable WorkItemServiceState reportSuccess() throws IOException { checkState(!finalStateSent, "cannot reportSuccess after sending a final state"); checkState(worker != null, "setWorker should be called before reportSuccess"); if (wasAskedToAbort) { LOG.info("Service already asked...
@Test public void reportSuccessBeforeSetWorker() throws IOException { thrown.expect(IllegalStateException.class); thrown.expectMessage("setWorker"); thrown.expectMessage("reportSuccess"); statusClient.reportSuccess(); }
@Override public ScannerReport.Metadata readMetadata() { ensureInitialized(); if (this.metadata == null) { this.metadata = delegate.readMetadata(); } return this.metadata; }
@Test public void readMetadata_throws_ISE_if_no_metadata() { assertThatThrownBy(() -> underTest.readMetadata()) .isInstanceOf(IllegalStateException.class); }
public Column getColumn(String value) { Matcher m = PATTERN.matcher(value); if (!m.matches()) { throw new IllegalArgumentException("value " + value + " is not a valid column definition"); } String name = m.group(1); String type = m.group(6); type = type == nu...
@Test public void testGetDollarColumn() { ColumnFactory f = new ColumnFactory(); Column column = f.getColumn("$column"); assertThat(column instanceof StringColumn).isTrue(); assertThat(column.getName()).isEqualTo("$column"); assertThat(column.getCellType()).isEqualTo("StringC...
@Override public ListConsumerGroupOffsetsResult listConsumerGroupOffsets(Map<String, ListConsumerGroupOffsetsSpec> groupSpecs, ListConsumerGroupOffsetsOptions options) { SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, OffsetAndMetad...
@Test public void testBatchedListConsumerGroupOffsetsWithNoFindCoordinatorBatching() throws Exception { Cluster cluster = mockCluster(1, 0); Time time = new MockTime(); Map<String, ListConsumerGroupOffsetsSpec> groupSpecs = batchedListConsumerGroupOffsetsSpec(); ApiVersion findCoord...
boolean isCausedBySecurity(Throwable e) { if (e == null) { return false; } return (e instanceof GeneralSecurityException) || isCausedBySecurity(e.getCause()); }
@Test void shouldReturnFalseIfNotCausedBySecurity() { Exception exception = new Exception(new IOException()); assertThat(agentController.isCausedBySecurity(exception)).isFalse(); }
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) { carMaxSpeedEnc.setDecimal(false, edgeId, edgeIntAccess, getMaxSpeed(way, false)); carMaxSpeedEnc.setDecimal(true, edgeId, edgeIntAccess, getMaxSpeed(way, true)); }
@Test void countryRule() { DecimalEncodedValue maxSpeedEnc = MaxSpeed.create(); maxSpeedEnc.init(new EncodedValue.InitializerConfig()); OSMMaxSpeedParser parser = new OSMMaxSpeedParser(maxSpeedEnc); IntsRef relFlags = new IntsRef(2); ReaderWay way = new ReaderWay(29L); ...
public DdlCommandResult execute( final String sql, final DdlCommand ddlCommand, final boolean withQuery, final Set<SourceName> withQuerySources ) { return execute(sql, ddlCommand, withQuery, withQuerySources, false); }
@Test public void shouldWarnAddDuplicateTableWithoutReplace() { // Given: givenCreateTable(); cmdExec.execute(SQL_TEXT, createTable, false, NO_QUERY_SOURCES); // When: givenCreateTable(); final DdlCommandResult result =cmdExec.execute(SQL_TEXT, createTable, false, NO_QUERY_SOURCES); ...
public boolean createTable(CreateTableStmt stmt, List<Column> partitionColumns) throws DdlException { String dbName = stmt.getDbName(); String tableName = stmt.getTableName(); Map<String, String> properties = stmt.getProperties() != null ? stmt.getProperties() : new HashMap<>(); Path tab...
@Test public void testCreateTableWithLocation() throws DdlException { new MockUp<HiveWriteUtils>() { @Mock public void createDirectory(Path path, Configuration conf) { } @Mock public boolean pathExists(Path path, Configuration conf) { ...
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.0"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName();...
@Test public void testImportBlacklistedSites() throws IOException { BlacklistedSite site1 = new BlacklistedSite(); site1.setId(1L); site1.setUri("http://foo.com"); BlacklistedSite site2 = new BlacklistedSite(); site2.setId(2L); site2.setUri("http://bar.com"); BlacklistedSite site3 = new BlacklistedSite...
@Override public void resolveArtifacts( ArtifactApi.ResolveArtifactsRequest request, StreamObserver<ArtifactApi.ResolveArtifactsResponse> responseObserver) { // Trying out artifact services in order till one succeeds. // If all services fail, re-raises the last error. // TODO: when all service...
@Test public void testArtifactResolveFirstEndpoint() { Path path = Paths.get("dummypath"); RunnerApi.ArtifactInformation fileArtifact = RunnerApi.ArtifactInformation.newBuilder() .setTypeUrn(ArtifactRetrievalService.FILE_ARTIFACT_URN) .setTypePayload( RunnerApi...
public CapacityScheduler() { super(CapacityScheduler.class.getName()); this.maxRunningEnforcer = new CSMaxRunningAppsEnforcer(this); }
@Test public void testCapacityScheduler() throws Exception { LOG.info("--- START: testCapacityScheduler ---"); NodeStatus mockNodeStatus = createMockNodeStatus(); // Register node1 String host_0 = "host_0"; NodeManager nm_0 = registerNode(resourceManager, host_0, 1234, 2345, NetworkTopo...
@Override public boolean isInputConsumable( SchedulingExecutionVertex executionVertex, Set<ExecutionVertexID> verticesToDeploy, Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) { for (ConsumedPartitionGroup consumedPartitionGroup : executionVert...
@Test void testNotFinishedBlockingInput() { final TestingSchedulingTopology topology = new TestingSchedulingTopology(); final List<TestingSchedulingExecutionVertex> producers = topology.addExecutionVertices().withParallelism(2).finish(); final List<TestingSchedulingExecutio...
public static String parentOf(String path) throws PathNotFoundException { List<String> elements = split(path); int size = elements.size(); if (size == 0) { throw new PathNotFoundException("No parent of " + path); } if (size == 1) { return "/"; } elements.remove(size - 1); St...
@Test public void testParentOf() throws Throwable { assertEquals("/", parentOf("/a")); assertEquals("/", parentOf("/a/")); assertEquals("/a", parentOf("/a/b")); assertEquals("/a/b", parentOf("/a/b/c")); }
@Override public @Nullable State waitUntilFinish() { return waitUntilFinish(Duration.millis(-1)); }
@Test public void testCumulativeTimeOverflow() throws Exception { Dataflow.Projects.Locations.Jobs.Get statusRequest = mock(Dataflow.Projects.Locations.Jobs.Get.class); Job statusResponse = new Job(); statusResponse.setCurrentState("JOB_STATE_RUNNING"); when(mockJobs.get(eq(PROJECT_ID), eq(RE...
@PutMapping() @TpsControl(pointName = "NamingServiceUpdate", name = "HttpNamingServiceUpdate") @Secured(action = ActionTypes.WRITE) public Result<String> update(ServiceForm serviceForm) throws Exception { serviceForm.validate(); Map<String, String> metadata = UtilsAndCommons.parseMetadata(se...
@Test void testUpdate() throws Exception { ServiceForm serviceForm = new ServiceForm(); serviceForm.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID); serviceForm.setGroupName(Constants.DEFAULT_GROUP); serviceForm.setServiceName("service"); serviceForm.setProtectThreshold(0.0f);...
@Override public int publish(TopicPath topic, List<OutgoingMessage> outgoingMessages) throws IOException { List<PubsubMessage> pubsubMessages = new ArrayList<>(outgoingMessages.size()); for (OutgoingMessage outgoingMessage : outgoingMessages) { PubsubMessage pubsubMessage = new PubsubMessage()...
@Test public void publishOneMessageWithOnlyTimestampAndIdAttributes() throws IOException { String expectedTopic = TOPIC.getPath(); PubsubMessage expectedPubsubMessage = new PubsubMessage() .encodeData(DATA.getBytes(StandardCharsets.UTF_8)) .setAttributes( Immuta...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseCorrectlyInComplicatedTopology() { // Given: givenFunctions( function(EXPECTED, -1, STRING, INT, STRING, INT), function(OTHER, 0, STRING_VARARGS), function("two", 1, STRING, STRING_VARARGS), function("three", 2, STRING, INT, STRING_VARARGS), functi...
@Deprecated public static void addFileToClassPath(Path file, Configuration conf) throws IOException { Job.addFileToClassPath(file, conf, file.getFileSystem(conf)); }
@Test public void testAddFileToClassPath() throws Exception { Configuration conf = new Configuration(false); // Test first with 2 args try { DistributedCache.addFileToClassPath(null, conf); fail("Accepted null archives argument"); } catch (NullPointerException ex) { // Expected ...
public static String initEndpoint(final NacosClientProperties properties) { if (properties == null) { return ""; } // Whether to enable domain name resolution rules String isUseEndpointRuleParsing = properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, ...
@Test void testInitEndpointFromDefaultWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initEndpoint(properties); assertEqu...
public boolean isFound() { return found; }
@Test public void testCalcInstructionsForSlightTurnWithOtherSlightTurn() { // Test for a fork with two slight turns. Since there are two slight turns, show the turn instruction Weighting weighting = new SpeedWeighting(mixedCarSpeedEnc); Path p = new Dijkstra(roundaboutGraph.g, weighting, Tra...
public static String simpleClassName(Object o) { if (o == null) { return "null_object"; } else { return simpleClassName(o.getClass()); } }
@Test public void testSimpleClassName() throws Exception { testSimpleClassName(String.class); }
public void executor(final ConfigGroupEnum type, final String json, final String eventType) { ENUM_MAP.get(type).handle(json, eventType); }
@Test public void testPluginRefreshExecutor() { String json = getJson(); websocketDataHandler.executor(ConfigGroupEnum.PLUGIN, json, DataEventTypeEnum.REFRESH.name()); List<PluginData> pluginDataList = new PluginDataHandler(pluginDataSubscriber).convert(json); Mockito.verify(pluginDa...
@Override protected double maintain() { if ( ! nodeRepository().nodes().isWorking()) return 0.0; // Don't need to maintain spare capacity in dynamically provisioned zones; can provision more on demand. if (nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0; NodeList ...
@Test public void testTooManyIterationsAreNeeded() { // 6 nodes must move to the next host, which is more than the max limit var tester = new SpareCapacityMaintainerTester(5); tester.addHosts(2, new NodeResources(10, 100, 1000, 1)); tester.addHosts(1, new NodeResources(9, 90, 900, 0...
public static List<SQLRecognizer> get(String sql, String dbType) { return SQL_RECOGNIZER_FACTORY.create(sql, dbType); }
@Test public void testSqlRecognizerLoading() { List<SQLRecognizer> recognizers = SQLVisitorFactory.get("update t1 set name = 'test' where id = '1'", JdbcConstants.MYSQL); Assertions.assertNotNull(recognizers); Assertions.assertEquals(recognizers.size(), 1); SQLRecognizer recognizer =...
public String delayedServiceResponse() { try { return this.delayedService.attemptRequest(); } catch (RemoteServiceException e) { return e.getMessage(); } }
@Test void testDelayedRemoteResponseFailure() { var delayedService = new DelayedRemoteService(System.nanoTime(), 2); var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); var monitoringService = new MonitoringService(delayedServiceCi...
private static void addQueue( QueueConfigInfo addInfo, CapacitySchedulerConfiguration proposedConf, Map<String, String> confUpdate) throws IOException { if (addInfo == null) { return; } QueuePath queuePath = new QueuePath(addInfo.getQueue()); String queueName = queuePath.getLea...
@Test public void testAddQueue() throws Exception { SchedConfUpdateInfo updateInfo = new SchedConfUpdateInfo(); Map<String, String> updateMap = new HashMap<>(); updateMap.put(CONFIG_NAME, C_CONFIG_VALUE); QueueConfigInfo queueConfigInfo = new QueueConfigInfo(C_PATH, updateMap); updateInfo.getAddQu...
public static <K> KStreamHolder<K> build( final KStreamHolder<K> stream, final StreamSelectKey<K> selectKey, final RuntimeBuildContext buildContext ) { return build(stream, selectKey, buildContext, PartitionByParamsFactory::build); }
@Test public void shouldReturnCorrectSerdeFactory() { // When: final KStreamHolder<GenericKey> result = StreamSelectKeyBuilder .build(stream, selectKey, buildContext, paramBuilder); // Then: result.getExecutionKeyFactory().buildKeySerde( FormatInfo.of(FormatFactory.JSON.name()), ...
public static JobConsoleLogger getConsoleLogger() { if (context == null) throw new RuntimeException("context is null"); return new JobConsoleLogger(); }
@Test public void shouldFailGetLoggerIfContextIsNotSet() { ReflectionUtil.setStaticField(JobConsoleLogger.class, "context", null); try { JobConsoleLogger.getConsoleLogger(); fail("expected this to fail"); } catch (Exception e) { assertThat(e.getMessage(), ...
public Class<?>[] getClasses(String name, Class<?> ... defaultValue) { String valueString = getRaw(name); if (null == valueString) { return defaultValue; } String[] classnames = getTrimmedStrings(name); try { Class<?>[] classes = new Class<?>[classnames.length]; for(int i = 0; i < ...
@Test public void testGetClasses() throws IOException { out=new BufferedWriter(new FileWriter(CONFIG)); startConfig(); appendProperty("test.classes1", "java.lang.Integer,java.lang.String"); appendProperty("test.classes2", " java.lang.Integer , java.lang.String "); endConfig(); Path fileResourc...
@Override public void executeUpdate(final RegisterStorageUnitStatement sqlStatement, final ContextManager contextManager) { checkDataSource(sqlStatement, contextManager); Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.get...
@Test void assertExecuteUpdateWithDuplicateStorageUnitNamesInStatement() { assertThrows(DuplicateStorageUnitException.class, () -> executor.executeUpdate(createRegisterStorageUnitStatementWithDuplicateStorageUnitNames(), mock(ContextManager.class))); }
public boolean write(final int msgTypeId, final DirectBuffer srcBuffer, final int offset, final int length) { checkTypeId(msgTypeId); checkMsgLength(length); final AtomicBuffer buffer = this.buffer; final int recordLength = length + HEADER_LENGTH; final int recordIndex = cla...
@Test void shouldInsertPaddingRecordPlusMessageOnBufferWrap() { final int length = 200; final int recordLength = length + HEADER_LENGTH; final int alignedRecordLength = align(recordLength, ALIGNMENT); final long tail = CAPACITY - HEADER_LENGTH; final long head = tail - (A...
public static boolean toBoolean(String val, boolean defaultValue) { if (StringUtils.isBlank(val)) { return defaultValue; } return Boolean.parseBoolean(val); }
@Test void testToBoolean() { // ConvertUtils.toBoolean(String) assertTrue(ConvertUtils.toBoolean("true")); assertTrue(ConvertUtils.toBoolean("True")); assertTrue(ConvertUtils.toBoolean("TRUE")); assertFalse(ConvertUtils.toBoolean("false")); assertFalse(ConvertUtils.to...
@GET @TreeResponse public ExportedToolDescriptor[] doToolMetadata() { List<ExportedToolDescriptor> models = new ArrayList<>(); for (ToolDescriptor<? extends ToolInstallation> d : ToolInstallation.all()) { ExportedToolDescriptor descriptor = new ExportedToolDescriptor(d.getDisplayName...
@Test public void toolMetadata() throws Exception { PipelineMetadataService svc = new PipelineMetadataService(); List<ExportedToolDescriptor> tools = new ArrayList<>(Arrays.asList(svc.doToolMetadata())); assertFalse(tools.isEmpty()); ExportedToolDescriptor t = null; for (...
@Override public Optional<EncryptColumnExistedReviser> getColumnExistedReviser(final EncryptRule rule, final String tableName) { return rule.findEncryptTable(tableName).map(EncryptColumnExistedReviser::new); }
@Test void assertGetColumnExistedReviser() { Optional<EncryptColumnExistedReviser> columnExistedReviser = new EncryptMetaDataReviseEntry().getColumnExistedReviser(createEncryptRule(), TABLE_NAME); assertTrue(columnExistedReviser.isPresent()); assertThat(columnExistedReviser.get().getClass(),...
Record deserialize(Object data) { return (Record) fieldDeserializer.value(data); }
@Test public void testSchemaDeserialize() { StandardStructObjectInspector schemaObjectInspector = ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("0:col1", "1:col2"), Arrays.asList( PrimitiveObjectInspectorFactory.writableLongObjectInspector, ...
@Override public SpanCustomizer tag(String key, String value) { return tracer.currentSpanCustomizer().tag(key, value); }
@Test void tag_when_no_current_span() { spanCustomizer.tag("foo", "bar"); }
public static byte[] extractHashFromP2SH(Script script) { return script.chunks().get(1).data; }
@Test public void p2shScriptHashFromKeys() { // import some keys from this example: https://gist.github.com/gavinandresen/3966071 ECKey key1 = DumpedPrivateKey.fromBase58(MAINNET, "5JaTXbAUmfPYZFRwrYaALK48fN6sFJp4rHqq2QSXs8ucfpE4yQU").getKey(); key1 = ECKey.fromPrivate(key1.getPrivKeyBytes()...
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test(description = "it should filter any Pet Ref in Schemas") public void filterAwayPetRefInSchemas() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH); final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoPetRefSchemaFilter(), null, null, null); validateSche...
@VisibleForTesting public Set<NodeAttribute> parseAttributes(String config) throws IOException { if (Strings.isNullOrEmpty(config)) { return ImmutableSet.of(); } Set<NodeAttribute> attributeSet = new HashSet<>(); // Configuration value should be in one line, format: // "ATTRIBUTE_NAME,...
@Test(timeout=30000L) public void testNodeAttributesFetchInterval() throws IOException, InterruptedException { Set<NodeAttribute> expectedAttributes1 = new HashSet<>(); expectedAttributes1.add(NodeAttribute .newInstance("test.io", "host", NodeAttributeType.STRING, "host1")); Con...
@Override public void createService(Service service, AbstractSelector selector) throws NacosException { NAMING_LOGGER.info("[CREATE-SERVICE] {} creating service : {}", namespaceId, service); final Map<String, String> params = new HashMap<>(16); params.put(CommonParams.NAMES...
@Test void testCreateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult<Object> a = new HttpRestResult<Object>(); a.setData(""); a.setCode(200); when(nacosRestTemplate.exchangeForm(any(), any(), any...
public LockResource lockExclusive(StateLockOptions lockOptions) throws TimeoutException, InterruptedException, IOException { return lockExclusive(lockOptions, null); }
@Test public void testGraceMode_Forced() throws Throwable { // Enable interrupt-cycle with 100ms interval. configureInterruptCycle(true, 100); // The state-lock instance. StateLockManager stateLockManager = new StateLockManager(); // Start a thread that owns the state-lock in shared mode. Stat...
@Nullable public Object sanitize(String key, @Nullable Object value) { for (Pattern pattern : sanitizeKeysPatterns) { if (pattern.matcher(key).matches()) { return SANITIZED_VALUE; } } return value; }
@Test void notObfuscateNormalConfigs() { final var sanitizer = new KafkaConfigSanitizer(true, List.of()); assertThat(sanitizer.sanitize("security.protocol", "SASL_SSL")).isEqualTo("SASL_SSL"); final String[] bootstrapServer = new String[] {"test1:9092", "test2:9092"}; assertThat(sanitizer.sanitize("bo...
@Override public String getConfig(String dataId, String group, long timeoutMs) throws NacosException { return getConfigInner(namespace, dataId, group, timeoutMs); }
@Test void testGetConfigFromLocalCache() throws NacosException { final String dataId = "1localcache"; final String group = "2"; final String tenant = ""; MockedStatic<LocalConfigInfoProcessor> localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor...
@Override public boolean isReadable(Class<?> type, @Nullable Type genericType, @Nullable Annotation[] annotations, @Nullable MediaType mediaType) { return isProvidable(type) && super.isReadable(type, genericType, annot...
@Test void doesNotReadIgnoredTypes() { assertThat(provider.isReadable(Ignorable.class, null, null, null)) .isFalse(); }
@Override public Collection<RedisServer> masters() { List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS); return toRedisServersList(masters); }
@Test public void testMasters() { Collection<RedisServer> masters = connection.masters(); assertThat(masters).hasSize(1); }
@Override public ByteBuf duplicate() { return newSharedLeakAwareByteBuf(super.duplicate()); }
@Test public void testWrapDuplicate() { assertWrapped(newBuffer(8).duplicate()); }
public DurationConfParser durationConf() { return new DurationConfParser(); }
@Test public void testDurationConf() { Map<String, String> writeOptions = ImmutableMap.of("write-prop", "111s"); ConfigOption<Duration> configOption = ConfigOptions.key("conf-prop").durationType().noDefaultValue(); Configuration flinkConf = new Configuration(); flinkConf.setString(configOptio...
static boolean apply(@Nullable HttpStatus httpStatus) { if (Objects.isNull(httpStatus)) { return false; } RpcEnhancementReporterProperties reportProperties; try { reportProperties = ApplicationContextAwareUtils.getApplicationContext() .getBean(RpcEnhancementReporterProperties.class); } catch (Bea...
@Test public void testApplyWithoutSeries() { RpcEnhancementReporterProperties properties = new RpcEnhancementReporterProperties(); // Mock Condition properties.getStatuses().clear(); properties.getSeries().clear(); ApplicationContext applicationContext = mock(ApplicationContext.class); doReturn(properties...
public RoleDO getRole() { return (RoleDO) getSource(); }
@Test public void testGetRole() { assertEquals(roleDO, roleUpdatedEvent.getRole()); }
public static String getDescWithoutMethodName(Method m) { StringBuilder ret = new StringBuilder(); ret.append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } r...
@Test void testGetDescWithoutMethodName() throws Exception { assertThat( ReflectUtils.getDescWithoutMethodName(Foo2.class.getDeclaredMethod("hello", int[].class)), equalTo("([I)Ljava/util/List;")); }
public static ResourceId matchNewResource(String singleResourceSpec, boolean isDirectory) { return getFileSystemInternal(parseScheme(singleResourceSpec)) .matchNewResource(singleResourceSpec, isDirectory); }
@Test public void testValidMatchNewResourceForLocalFileSystem() { assertEquals("file", FileSystems.matchNewResource("/tmp/f1", false).getScheme()); assertEquals("file", FileSystems.matchNewResource("tmp/f1", false).getScheme()); assertEquals("file", FileSystems.matchNewResource("c:\\tmp\\f1", false).getSc...
public RandomForest merge(RandomForest other) { if (!formula.equals(other.formula)) { throw new IllegalArgumentException("RandomForest have different model formula"); } Model[] forest = new Model[models.length + other.models.length]; System.arraycopy(models, 0, forest, 0, mo...
@Test public void testMerge() { System.out.println("merge"); RandomForest forest1 = RandomForest.fit(Abalone.formula, Abalone.train, 50, 3, 20, 100, 5, 1.0, Arrays.stream(seeds)); RandomForest forest2 = RandomForest.fit(Abalone.formula, Abalone.train, 50, 3, 20, 100, 5, 1.0, Arrays.stream(s...
public void onClose() { if (asyncTaskExecutor instanceof ExecutorService) { try { final ExecutorService executor = (ExecutorService)asyncTaskExecutor; executor.shutdownNow(); if (!executor.awaitTermination(EXECUTOR_SHUTDOWN_TIME...
@Test void onCloseHandlesExceptionFromClosingAsyncExecutor(@TempDir final Path dir) { final ExecutorService asyncTaskExecutor = mock(ExecutorService.class); final IllegalStateException closeException = new IllegalStateException("executor failed"); doThrow(closeException).when(asyncTaskEx...
@VisibleForTesting static InstructionOutput forInstructionOutput( InstructionOutput input, boolean replaceWithByteArrayCoder) throws Exception { InstructionOutput cloudOutput = clone(input, InstructionOutput.class); cloudOutput.setCodec(forCodec(cloudOutput.getCodec(), replaceWithByteArrayCoder)); r...
@Test public void testLengthPrefixInstructionOutputCoder() throws Exception { InstructionOutput output = new InstructionOutput(); output.setCodec(CloudObjects.asCloudObject(windowedValueCoder, /*sdkComponents=*/ null)); output.setFactory(new GsonFactory()); InstructionOutput prefixedOutput = forInstr...
@Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { if (lockConfiguration.getLockAtMostFor().compareTo(minimalLockAtMostFor) < 0) { throw new IllegalArgumentException( "Can not use KeepAliveLockProvider with lockAtMostFor shorter than " + minimal...
@Test void shouldScheduleKeepAliveTask() { mockExtension(originalLock, Optional.of(originalLock)); Optional<SimpleLock> lock = provider.lock(lockConfiguration); assertThat(lock).isNotNull(); tickMs(1_500); verify(originalLock).extend(lockConfiguration.getLockAtMostFor(), ofMi...
public static List<Import> getImportList(final List<String> importCells) { final List<Import> importList = new ArrayList<>(); if ( importCells == null ) { return importList; } for( String importCell: importCells ){ final StringTokenizer tokens = new StringTokeniz...
@Test public void getImportList_nullValue() { assertThat(getImportList(null)).isNotNull().isEmpty(); }
@VisibleForTesting void validateUsernameUnique(Long id, String username) { if (StrUtil.isBlank(username)) { return; } AdminUserDO user = userMapper.selectByUsername(username); if (user == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的用户 ...
@Test public void testValidateUsernameUnique_usernameExistsForUpdate() { // 准备参数 Long id = randomLongId(); String username = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); // 调用,校验异常 assertServiceException(() ->...
@Override public Cursor<Tuple> zScan(byte[] key, ScanOptions options) { return new KeyBoundCursor<Tuple>(key, 0, options) { private RedisClient client; @Override protected ScanIteration<Tuple> doScan(byte[] key, long cursorId, ScanOptions options) { if (...
@Test public void testZScan() { connection.zAdd("key".getBytes(), 1, "value1".getBytes()); connection.zAdd("key".getBytes(), 2, "value2".getBytes()); Cursor<RedisZSetCommands.Tuple> t = connection.zScan("key".getBytes(), ScanOptions.scanOptions().build()); assertThat(t.hasNext()).is...
public static SqlType fromValue(final BigDecimal value) { // SqlDecimal does not support negative scale: final BigDecimal decimal = value.scale() < 0 ? value.setScale(0, BigDecimal.ROUND_UNNECESSARY) : value; /* We can't use BigDecimal.precision() directly for all cases, since it defines ...
@Test public void shouldGetSchemaFromDecimal1_0() { // When: final SqlType schema = DecimalUtil.fromValue(new BigDecimal("0")); // Then: assertThat(schema, is(SqlTypes.decimal(1, 0))); }
@Override public void deregisterInstance(String serviceName, String ip, int port) throws NacosException { deregisterInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME); }
@Test void testDeregisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; int port = 10000; //when client.deregisterInstance(serviceName, ip, port); //then verify(proxy, times(1)).deregisterService(eq(...
@Udf(description = "Returns the inverse (arc) tangent of an INT value") public Double atan( @UdfParameter( value = "value", description = "The value to get the inverse tangent of." ) final Integer value ) { return atan(value == null ? null : value.doubleVa...
@Test public void shouldHandleLessThanNegativeOne() { assertThat(udf.atan(-1.1), closeTo(-0.8329812666744317, 0.000000000000001)); assertThat(udf.atan(-6.0), closeTo(-1.4056476493802699, 0.000000000000001)); assertThat(udf.atan(-2), closeTo(-1.1071487177940904, 0.000000000000001)); assertThat(udf.atan...
public static BigInteger factorial(BigInteger n) { if (n.equals(BigInteger.ZERO)) { return BigInteger.ONE; } return factorial(n, BigInteger.ZERO); }
@Test public void factorialTest(){ long factorial = NumberUtil.factorial(0); assertEquals(1, factorial); assertEquals(1L, NumberUtil.factorial(1)); assertEquals(1307674368000L, NumberUtil.factorial(15)); assertEquals(2432902008176640000L, NumberUtil.factorial(20)); factorial = NumberUtil.factorial(5, 0);...
@Override public Set<Long> calculateUsers(DelegateExecution execution, String param) { Set<Long> roleIds = StrUtils.splitToLongSet(param); return permissionApi.getUserRoleIdListByRoleIds(roleIds); }
@Test public void testCalculateUsers() { // 准备参数 String param = "1,2"; // mock 方法 when(permissionApi.getUserRoleIdListByRoleIds(eq(asSet(1L, 2L)))) .thenReturn(asSet(11L, 22L)); // 调用 Set<Long> results = strategy.calculateUsers(null, param); // 断言...
@VisibleForTesting ClientConfiguration createBkClientConfiguration(MetadataStoreExtended store, ServiceConfiguration conf) { ClientConfiguration bkConf = new ClientConfiguration(); if (conf.getBookkeeperClientAuthenticationPlugin() != null && conf.getBookkeeperClientAuthenticationPlu...
@Test public void testSetExplicitLacInterval() { BookKeeperClientFactoryImpl factory = new BookKeeperClientFactoryImpl(); ServiceConfiguration conf = new ServiceConfiguration(); conf.setMetadataStoreUrl("zk:localhost:2181"); assertEquals(factory.createBkClientConfiguration(mock(Metad...
public static MD5Hash computeMd5ForFile(File dataFile) throws IOException { InputStream in = Files.newInputStream(dataFile.toPath()); try { MessageDigest digester = MD5Hash.getDigester(); DigestInputStream dis = new DigestInputStream(in, digester); IOUtils.copyBytes(dis, new IOUtils.NullOutput...
@Test public void testComputeMd5ForFile() throws Exception { MD5Hash computedDigest = MD5FileUtils.computeMd5ForFile(TEST_FILE); assertEquals(TEST_MD5, computedDigest); }
static Set<String> parseStaleDataNodeList(String liveNodeJsonString, final int blockThreshold, final Logger log) throws IOException { final Set<String> dataNodesToReport = new HashSet<>(); JsonFactory fac = JacksonUtil.createBasicJsonFactory(); JsonParser parser = fac.createParser(IOUtils .to...
@Test public void testParseStaleDatanodeListMultipleDatanodes() throws Exception { String json = "{" + "\"1.2.3.4:1\": {\"numBlocks\": 0}, " + "\"1.2.3.4:2\": {\"numBlocks\": 15}, " + "\"1.2.3.4:3\": {\"numBlocks\": 5}, " + "\"1.2.3.4:4\": {\"numBlocks\": 10} " + "}"; S...
public String convert(ILoggingEvent le) { List<Marker> markers = le.getMarkerList(); if (markers == null || markers.isEmpty()) { return EMPTY; } int size = markers.size(); if (size == 1) return markers.get(0).toString(); StringBuffer buf = new St...
@Test public void testWithOneChildMarker() { Marker marker = markerFactory.getMarker("test"); marker.add(markerFactory.getMarker("child")); String result = converter.convert(createLoggingEvent(marker)); assertEquals("test [ child ]", result); }
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testDeterminismSet() { assertDeterministic(AvroCoder.of(StringSortedSet.class)); assertDeterministic(AvroCoder.of(StringTreeSet.class)); assertNonDeterministic( AvroCoder.of(StringHashSet.class), reasonField( StringHashSet.class, "stringCollection"...