focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@BuildStep AdditionalBeanBuildItem produce(Capabilities capabilities, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) { Set<Class<?>> additionalBeans = new HashSet<>(); additionalBeans.add(JobRunrProducer.class); additionalBeans.add(JobRunrStarter.class); additionalBeans...
@Test void jobRunrProducerUsesMongoDBStorageProviderIfMongoDBClientCapabilityIsPresent() { lenient().when(capabilities.isPresent(Capability.MONGODB_CLIENT)).thenReturn(true); final AdditionalBeanBuildItem additionalBeanBuildItem = jobRunrExtensionProcessor.produce(capabilities, jobRunrBuildTimeConfi...
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { final String target = new DefaultUrlProvider(session.getHost()).toUrl(renamed).find(Descrip...
@Test public void testMove() throws Exception { final Path test = new DAVTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); assertEquals(TransferStatus.UNKNOWN_LENGTH, ...
@Override public void setCapacity(int capacity) { get(setCapacityAsync(capacity)); }
@Test public void testSetCapacity() { RRingBuffer<Integer> buffer = redisson.getRingBuffer("test"); buffer.trySetCapacity(5); for (int i = 0; i < 10; i++) { buffer.add(i); } assertThat(buffer).containsExactly(5, 6, 7, 8, 9); buffer.setCapacity(3); ...
@Override public Response request(Request request, long timeoutMills) throws NacosException { DefaultRequestFuture pushFuture = sendRequestInner(request, null); try { return pushFuture.get(timeoutMills); } catch (Exception e) { throw new NacosException(NacosException....
@Test void testStatusRuntimeException() { Mockito.doReturn(new DefaultEventLoop()).when(channel).eventLoop(); Mockito.doThrow(new StatusRuntimeException(Status.CANCELLED)).when(streamObserver).onNext(Mockito.any()); Mockito.doReturn(true).when(streamObserver).isReady(); try ...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testChainStartEndSetting() throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // set parallelism to 2 to avoid chaining with source in case when available processors is // 1. env.setParallelism(2); // fromEle...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 2) { onInvalidDataReceived(device, data); return; } // Read the Op Code final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); // Estima...
@Test public void onCGMSpecificOpsOperationCompleted() { final Data data = new Data(new byte[] { 28, 2, 1}); callback.onDataReceived(null, data); assertTrue(success); assertFalse(secured); assertEquals(2, requestCode); }
public static String[] splitOnCharacter(String value, String needle, int count) { String[] rc = new String[count]; rc[0] = value; for (int i = 1; i < count; i++) { String v = rc[i - 1]; int p = v.indexOf(needle); if (p < 0) { return rc; ...
@Test public void testSplitOnCharacter() { String[] list = splitOnCharacter("foo", "'", 1); assertEquals(1, list.length); assertEquals("foo", list[0]); list = splitOnCharacter("foo,bar", ",", 2); assertEquals(2, list.length); assertEquals("foo", list[0]); ass...
public void replay( ConsumerGroupMemberMetadataKey key, ConsumerGroupMemberMetadataValue value ) { String groupId = key.groupId(); String memberId = key.memberId(); ConsumerGroup consumerGroup = getOrMaybeCreatePersistedConsumerGroup(groupId, value != null); Set<Stri...
@Test public void testConsumerGroupStates() { String groupId = "fooup"; String memberId1 = Uuid.randomUuid().toString(); Uuid fooTopicId = Uuid.randomUuid(); String fooTopicName = "foo"; MockPartitionAssignor assignor = new MockPartitionAssignor("range"); GroupMetada...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldCreateStreamCommandWithSingleValueWrappingFromConfig() { // Given: ksqlConfig = new KsqlConfig(ImmutableMap.of( KsqlConfig.KSQL_WRAP_SINGLE_VALUES, false )); final CreateStream statement = new CreateStream(SOME_NAME, ONE_KEY_ONE_VALUE, false, true, withProperti...
public static LocalUri parse(String path) { if (path.startsWith(SCHEME)) { URI parsed = URI.create(path); path = parsed.getPath(); } if (!path.startsWith(SLASH)) { throw new IllegalArgumentException("Path must start at root /"); } StringTokeniz...
@Test public void testParse() { String path = "/example/some-id/instances/some-instance-id"; LocalUri hpath = LocalUri.Root.append("example").append("some-id").append("instances").append("some-instance-id"); LocalUri parsedHPath = LocalUri.parse(path); assertEquals(hpath, parsedHPath...
public Stream<FactMapping> getFactMappingsByFactName(String factName) { return internalFilter(e -> e.getFactIdentifier().getName().equalsIgnoreCase(factName)); }
@Test public void getFactMappingsByFactName() { modelDescriptor.addFactMapping(FactIdentifier.create("test", String.class.getCanonicalName()), ExpressionIdentifier.create("test expression 0", EXPECT)); modelDescriptor.addFactMapping(FactIdentifier.create("test", String.class.getCanonicalName()), Exp...
public ChmCommons.EntryType getEntryType() { return entryType; }
@Test public void testGetEntryType() { assertEquals(TestParameters.entryType, dle.getEntryType()); }
@Override public void close() throws InterruptedException { beginShutdown("KafkaEventQueue#close"); eventHandlerThread.join(); log.info("closed event queue."); }
@Test public void testCreateAndClose() throws Exception { KafkaEventQueue queue = new KafkaEventQueue(Time.SYSTEM, logContext, "testCreateAndClose"); queue.close(); }
public void schedule(ExecutableMethod<?, ?> method) { if (hasParametersOutsideOfJobContext(method.getTargetMethod())) { throw new IllegalStateException("Methods annotated with " + Recurring.class.getName() + " can only have zero parameters or a single parameter of type JobContext."); } ...
@Test void beansWithMethodsAnnotatedWithRecurringCronAnnotationWillAutomaticallyBeRegistered() { final ExecutableMethod executableMethod = mock(ExecutableMethod.class); final Method method = getRequiredMethod(MyServiceWithRecurringJob.class, "myRecurringMethod"); when(executableMethod.getTar...
public static String nullToEmpty(String str) { return str == null ? "" : str; }
@Test public void nullToEmpty() { String string = "null"; Assert.assertEquals("null", StringUtil.nullToEmpty(string)); }
@Override public PageData<WidgetsBundle> findTenantWidgetsBundlesByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData( widgetsBundleRepository .findTenantWidgetsBundlesByTenantId( tenantId, ...
@Test public void testFindWidgetsBundlesByTenantId() { UUID tenantId1 = Uuids.timeBased(); UUID tenantId2 = Uuids.timeBased(); // Create a bunch of widgetBundles for (int i = 0; i < 10; i++) { createWidgetBundles(3, tenantId1, "WB1_" + i + "_"); createWidgetBu...
public <T> Map<String, Object> schemas(Class<? extends T> cls) { return this.schemas(cls, false); }
@SuppressWarnings("unchecked") @Test void dag() throws URISyntaxException { Helpers.runApplicationContext((applicationContext) -> { JsonSchemaGenerator jsonSchemaGenerator = applicationContext.getBean(JsonSchemaGenerator.class); Map<String, Object> generate = jsonSchemaGenerator...
public Set<String> getCaseInsensitivePKs() { Set<String> pks = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); allIndexes.forEach((key, index) -> { if (index.getIndextype().value() == IndexType.PRIMARY.value()) { for (ColumnMeta col : index.getValues()) { pk...
@Test public void testGetCaseInsensitivePKs() { tableMeta.getColumnMeta("col2".trim()).setColumnName("CoL2"); Set<String> pks = tableMeta.getCaseInsensitivePKs(); assertEquals(2, pks.size()); assertTrue(pks.contains("col1")); assertTrue(pks.contains("CoL2")); }
public static double similar(String strA, String strB) { String newStrA, newStrB; if (strA.length() < strB.length()) { newStrA = removeSign(strB); newStrB = removeSign(strA); } else { newStrA = removeSign(strA); newStrB = removeSign(strB); } // 用较大的字符串长度作为分母,相似子串作为分子计算出字串相似度 int temp = Math.max...
@Test public void similarTest(){ final double abd = TextSimilarity.similar("abd", "1111"); assertEquals(0, abd, 0); }
Integer getMaxSize( Collection<BeanInjectionInfo.Property> properties, Object obj ) { int max = Integer.MIN_VALUE; for ( BeanInjectionInfo.Property property: properties ) { max = Math.max( max, ( isCollection( property ) ? getCollectionSize( property, obj ) // if not collectio...
@Test public void getMaxSize_Collections() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); MetaBeanLevel1 mbl1 = new MetaBeanLevel1(); mbl1.setSub( new MetaBeanLevel2() ); mbl1.getSub().setFilenames( new String[] { "file1", "file2...
public String getObjectPath() { return objectPath; }
@Test public void testObjectPath() { assertEquals("/QSYS.LIB/LIBRARY.LIB/QUEUE.DTAQ", jt400Configuration.getObjectPath()); }
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); }...
@Test public void decimalToConnectOptionalWithDefaultValue() { BigDecimal reference = new BigDecimal(new BigInteger("156"), 2); Schema schema = Decimal.builder(2).optional().defaultValue(reference).build(); String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"org.apache.kafka.conne...
public static synchronized Date parseDate(String dateStr, PrimitiveType type) throws AnalysisException { Date date = null; Matcher matcher = DATETIME_FORMAT_REG.matcher(dateStr); if (!matcher.matches()) { throw new AnalysisException("Invalid date string: " + dateStr); } ...
@Test public void testDateParse() { // date List<String> validDateList = new LinkedList<>(); validDateList.add("2013-12-02"); validDateList.add("2013-12-02"); validDateList.add("2013-12-2"); validDateList.add("2013-12-2"); validDateList.add("9999-12-31"); ...
public void start() { worker.start(); }
@Test(timeout = 1000) public void catchNotification() throws IOException, InterruptedException { CountDownLatch catched = new CountDownLatch(1); AtomicReference<Selector> selectorRef = new AtomicReference<>(); Ctx ctx = new Ctx() { @Override public Selecto...
@Override public KeyValueIterator<K, V> reverseRange(final K from, final K to) { final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = new NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>>() { @Override public KeyValueIterator<K, V> apply(final Re...
@Test public void shouldReturnValueOnReverseRangeNullFromKey() { stubOneUnderlying.put("0", "zero"); stubOneUnderlying.put("1", "one"); stubOneUnderlying.put("2", "two"); final LinkedList<KeyValue<String, String>> expectedContents = new LinkedList<>(); expectedContents.add(n...
public void getConfig(StorDistributionConfig.Group.Builder builder) { builder.index(index == null ? "invalid" : index); builder.name(name == null ? "invalid" : name); partitions.ifPresent(builder::partitions); for (StorageNode node : nodes) { StorDistributionConfig.Group.Node...
@Test void testSingleGroup() { ContentCluster cluster = parse( "<content id=\"storage\">\n" + " <redundancy>3</redundancy>" + " <documents/>" + " <group>\n" + " <node hostalias=\"mockhost\" ...
public static Builder builder() { return new Builder(); }
@Test public void testBuilderDoesNotBuildInvalidRequests() { assertThatThrownBy(() -> GetNamespaceResponse.builder().withNamespace(null).build()) .isInstanceOf(NullPointerException.class) .hasMessage("Invalid namespace: null"); assertThatThrownBy(() -> GetNamespaceResponse.builder().setProper...
public static RpcInvokeContext getContext() { RpcInvokeContext context = LOCAL.get(); if (context == null) { context = new RpcInvokeContext(); LOCAL.set(context); } return context; }
@Test public void getContext() throws Exception { RpcInvokeContext old = RpcInvokeContext.peekContext(); try { if (old != null) { RpcInvokeContext.removeContext(); } RpcInvokeContext context = RpcInvokeContext.peekContext(); Assert.asse...
public BackgroundException map(final IOException failure, final Path directory) { return super.map("Connection failed", failure, directory); }
@Test public void testPeerShutDownIncorrectly() { final DefaultIOExceptionMappingService s = new DefaultIOExceptionMappingService(); final SSLHandshakeException failure = new SSLHandshakeException("Remote host closed connection during handshake"); failure.initCause(new EOFException("SSL peer...
@Override public Integer getLocalValue() { return this.max; }
@Test void testGet() { IntMaximum max = new IntMaximum(); assertThat(max.getLocalValue().intValue()).isEqualTo(Integer.MIN_VALUE); }
public void reset() { final long timestamp = System.currentTimeMillis(); if(log.isDebugEnabled()) { log.debug(String.format("Reset with timestamp %d", timestamp)); } this.reset(timestamp, transfer.getTransferred()); }
@Test public void testReset() throws Exception { final DownloadTransfer transfer = new DownloadTransfer(new Host(new TestProtocol()), new Path("/p", EnumSet.of(Path.Type.file)), new Local("/t")); final TransferSpeedometer s = new TransferSpeedometer(transfer); transfer.addSize(8L); a...
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testGettingJLSDefaults() throws Exception { ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); JLSDefaults proxy = handler.as(JLSDefaults.class); assertFalse(proxy.getBoolean()); assertEquals('\0', proxy.getChar()); assertEquals((byte) 0, proxy.getByt...
@SuppressWarnings("Duplicates") public byte[] get(int index) { assert index < _numValues; int offsetBufferIndex = index >>> OFFSET_BUFFER_SHIFT_OFFSET; PinotDataBuffer offsetBuffer = _offsetBuffers.get(offsetBufferIndex); int offsetIndex = index & OFFSET_BUFFER_MASK; int previousValueEndOffset = ...
@Test public void testGet() throws Exception { try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) { for (int i = 0; i < NUM_VALUES; i++) { offHeapMutableBytesStore.add(_values[i]); } for (int i = 0; i < NUM_VALUES; i++) { ...
public static Read read() { return new AutoValue_RabbitMqIO_Read.Builder() .setQueueDeclare(false) .setExchangeDeclare(false) .setMaxReadTime(null) .setMaxNumRecords(Long.MAX_VALUE) .setUseCorrelationId(false) .build(); }
@Test public void testReadDeclaredTopicExchange() throws Exception { final int numRecords = 10; RabbitMqIO.Read read = RabbitMqIO.read().withExchange("DeclaredTopicExchange", "topic", "user.create.#"); final Supplier<String> publishRoutingKeyGen = new Supplier<String>() { privat...
public static void validateRdwAid(byte[] aId) { for (final byte[] compare : RDW_AID) { if (Arrays.equals(compare, aId)) { return; } } logger.error("Driving licence has unknown aId: {}", Hex.toHexString(aId).toUpperCase()); throw new ClientException...
@Test public void validateRdwAidUnsuccessful() { ClientException thrown = assertThrows(ClientException.class, () -> CardValidations.validateRdwAid(Hex.decode("SSSSSS"))); assertEquals("Unknown aId", thrown.getMessage()); }
public static <T> RestResult<T> success() { return RestResult.<T>builder().withCode(200).build(); }
@Test void testSuccessWithDefault() { RestResult<Object> restResult = RestResultUtils.success(); assertRestResult(restResult, 200, null, null, true); }
public ExitStatus(Options options) { this.options = options; }
@Test void wip_with_ambiguous_scenarios() { createWipRuntime(); bus.send(testCaseFinishedWithStatus(Status.AMBIGUOUS)); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x0))); }
@Override public void sendSmsCode(SmsCodeSendReqDTO reqDTO) { SmsSceneEnum sceneEnum = SmsSceneEnum.getCodeByScene(reqDTO.getScene()); Assert.notNull(sceneEnum, "验证码场景({}) 查找不到配置", reqDTO.getScene()); // 创建验证码 String code = createSmsCode(reqDTO.getMobile(), reqDTO.getScene(), reqDTO....
@Test public void sendSmsCode_exceedDay() { // mock 数据 SmsCodeDO smsCodeDO = randomPojo(SmsCodeDO.class, o -> o.setMobile("15601691300").setTodayIndex(10).setCreateTime(LocalDateTime.now())); smsCodeMapper.insert(smsCodeDO); // 准备参数 SmsCodeSendReqDTO reqDTO = ...
private static String getNameServiceId(Configuration conf, String addressKey) { String nameserviceId = conf.get(DFS_NAMESERVICE_ID); if (nameserviceId != null) { return nameserviceId; } Collection<String> nsIds = DFSUtilClient.getNameServiceIds(conf); if (1 == nsIds.size()) { return nsId...
@Test public void getNameServiceId() { HdfsConfiguration conf = new HdfsConfiguration(); conf.set(DFS_NAMESERVICE_ID, "nn1"); assertEquals("nn1", DFSUtil.getNamenodeNameServiceId(conf)); }
public static Builder forCurrentMagic(ProduceRequestData data) { return forMagic(RecordBatch.CURRENT_MAGIC_VALUE, data); }
@Test public void testV3AndAboveCannotUseMagicV1() { ByteBuffer buffer = ByteBuffer.allocate(256); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V1, Compression.NONE, TimestampType.CREATE_TIME, 0L); builder.append(10L, null, "a".getBytes...
@Override @Deprecated public <KR, VR> KStream<KR, VR> transform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, KeyValue<KR, VR>> transformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(transformerSuppl...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullTransformerSupplierOnTransformWithStores() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.transform(null, "storeName")); assertThat(exception.getMessa...
public static L2ModificationInstruction modL2Dst(MacAddress addr) { checkNotNull(addr, "Dst l2 address cannot be null"); return new L2ModificationInstruction.ModEtherInstruction( L2ModificationInstruction.L2SubType.ETH_DST, addr); }
@Test public void testModL2DstMethod() { final Instruction instruction = Instructions.modL2Dst(mac1); final L2ModificationInstruction.ModEtherInstruction modEtherInstruction = checkAndConvert(instruction, Instruction.Type.L2MODIFICATION, ...
private boolean setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState, ContentService contentService, Condition condition, boolean throwOnFailure) { try { ClusterControll...
@Test public void verifySetNodeState() { OrchestratorContext context = OrchestratorContext.createContextForSingleAppOp(clock); wire.expect((url, body) -> { assertEquals("http://host1:19050/cluster/v2/cc/storage/2?timeout=9.6", url.asURI()....
@Override public void delete(LookupTableDto nativeEntity) { lookupTableService.deleteAndPostEventImmutable(nativeEntity.id()); }
@Test @MongoDBFixtures("LookupTableFacadeTest.json") public void delete() { final Optional<LookupTableDto> lookupTableDto = lookupTableService.get("5adf24dd4b900a0fdb4e530d"); assertThat(lookupTableService.findAll()).hasSize(1); lookupTableDto.ifPresent(facade::delete); assertT...
@ApiOperation(value = "Query for historic activity instances", tags = {"History", "Query" }, notes = "All supported JSON parameter fields allowed are exactly the same as the parameters found for getting a collection of historic task instances, but passed in as JSON-body arguments rather than URL-parameters ...
@Test @Deployment public void testQueryActivityInstances() throws Exception { HashMap<String, Object> processVariables = new HashMap<>(); processVariables.put("stringVar", "Azerty"); processVariables.put("intVar", 67890); processVariables.put("booleanVar", false); Proces...
public static String hashForStringArray(String[] stringData) { checkNotNull(stringData); return computeHashFor(stringData); }
@Test public void hashForStringArrayDoesNotIgnoreNull() { String[] array1 = new String[]{"a", "b"}; String[] array2 = new String[]{"a", "b", null}; String[] array3 = new String[]{"a", null, "b"}; //rehashing produces same output twice assertThat(hashForStringArray(array1), i...
@Override public void onCreating(AbstractJob job) { JobDetails jobDetails = job.getJobDetails(); Optional<Job> jobAnnotation = getJobAnnotation(jobDetails); setJobName(job, jobAnnotation); setAmountOfRetries(job, jobAnnotation); setLabels(job, jobAnnotation); }
@Test void testDisplayNameWithAnnotationUsingJobParametersAndMDCVariables() { MDC.put("customer.id", "1"); Job job = anEnqueuedJob() .withoutName() .withJobDetails(jobDetails() .withClassName(TestService.class) .withMeth...
static URI determineClasspathResourceUri(Path baseDir, String basePackagePath, Path resource) { String subPackageName = determineSubpackagePath(baseDir, resource); String resourceName = resource.getFileName().toString(); String classpathResourcePath = of(basePackagePath, subPackageName, resource...
@Test void determineFullyQualifiedResourceName() { Path baseDir = Paths.get("path", "to", "com", "example", "app"); String basePackageName = "com/example/app"; Path resourceFile = Paths.get("path", "to", "com", "example", "app", "app.feature"); URI fqn = ClasspathSupport.determineCla...
@Override public void flush() { internal.flush(); }
@Test public void shouldDelegateAndRecordMetricsOnFlush() { store.flush(); verify(inner).flush(); assertThat((Double) getMetric("flush-rate").metricValue(), greaterThan(0.0)); }
public static MagicDetector parse(MediaType mediaType, String type, String offset, String value, String mask) { int start = 0; int end = 0; if (offset != null) { int colon = offset.indexOf(':'); if (colon == -1) { star...
@Test public void testDetectString() throws Exception { String data = "abcdEFGhijklmnoPQRstuvwxyz0123456789"; MediaType testMT = new MediaType("application", "test"); Detector detector; // Check regular String matching detector = MagicDetector.parse(testMT, "string", "0:20",...
public List<Long> availableWindows() { return getWindowList(_oldestWindowIndex, _currentWindowIndex - 1); }
@Test public void testAddSamplesWithLargeInterval() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); // Populate samples for time window indexed from 0 to NUM_WINDOWS to aggregator. ...
public void convertQueueHierarchy(FSQueue queue) { List<FSQueue> children = queue.getChildQueues(); final String queueName = queue.getName(); emitChildQueues(queueName, children); emitMaxAMShare(queueName, queue); emitMaxParallelApps(queueName, queue); emitMaxAllocations(queueName, queue); ...
@Test public void testAutoCreateV2FlagsInWeightMode() { converter = builder.withPercentages(false).build(); converter.convertQueueHierarchy(rootQueue); assertTrue("root autocreate v2 flag", csConfig.isAutoQueueCreationV2Enabled(ROOT)); assertTrue("root.admins autocreate v2 flag", csC...
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DefaultUrlProvider(session.getHost()).toUrl(file); if(file.isFile()) { // Authenticated browser download using cookie-based Google account authentication in conjunction with ACL lis...
@Test public void testWebsiteConfiguration() { final GoogleStorageUrlProvider provider = new GoogleStorageUrlProvider(session); assertEquals("http://test.cyberduck.ch.storage.googleapis.com/f", provider.toUrl(new Path("test.cyberduck.ch/f", EnumSet.of(Path.Type.file))).find( DescriptiveU...
@Nullable @Override public GenericRow decode(byte[] payload, GenericRow destination) { try { destination = (GenericRow) _decodeMethod.invoke(null, payload, destination); } catch (Exception e) { throw new RuntimeException(e); } return destination; }
@Test public void testNestedMessageClass() throws Exception { ProtoBufCodeGenMessageDecoder messageDecoder = setupDecoder("complex_types.jar", "org.apache.pinot.plugin.inputformat.protobuf.ComplexTypes$TestMessage$NestedMessage", ImmutableSet.of(NESTED_STRING_FIELD, NESTED_INT_FIELD)); ...
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { Map<String, String> mdcContextMap = getMdcContextMap(); return super.schedule(ContextPropagator.decorateRunnable(contextPropagators, () -> { try { setMDCContext(mdcContextM...
@Test public void testScheduleCallablePropagatesMDCContext() { MDC.put("key", "value"); MDC.put("key2","value2"); final Map<String, String> contextMap = MDC.getCopyOfContextMap(); final ScheduledFuture<Map<String, String>> scheduledFuture = this.schedulerService .schedule...
@Override public String toString() { return "ConfigChangeItem{" + "key='" + key + '\'' + ", oldValue='" + oldValue + '\'' + ", newValue='" + newValue + '\'' + ", type=" + type + '}'; }
@Test void testToString() { ConfigChangeItem item = new ConfigChangeItem("testKey", null, "testValue"); item.setType(PropertyChangeType.ADDED); assertEquals("ConfigChangeItem{key='testKey', oldValue='null', newValue='testValue', type=ADDED}", item.toString()); }
public URI buildEncodedUri(String endpointUrl) { if (endpointUrl == null) { throw new RuntimeException("Url string cannot be null!"); } if (endpointUrl.isEmpty()) { throw new RuntimeException("Url string cannot be empty!"); } URI uri = UriComponentsBuilde...
@Test public void testBuildUriWithSpecialSymbols() { Mockito.when(client.buildEncodedUri(any())).thenCallRealMethod(); String url = "http://192.168.1.1/data?d={\"a\": 12}"; String expected = "http://192.168.1.1/data?d=%7B%22a%22:%2012%7D"; URI uri = client.buildEncodedUri(url); ...
public static KTableHolder<GenericKey> build( final KGroupedStreamHolder groupedStream, final StreamAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedStream, aggregate, buildContext, ...
@Test public void shouldBuildAggregatorParamsCorrectlyForWindowedAggregate() { for (final Runnable given : given()) { // Given: clearInvocations( groupedStream, timeWindowedStream, sessionWindowedStream, aggregated, aggregateParamsFactory ); ...
public TaskAcknowledgeResult acknowledgeCoordinatorState( OperatorInfo coordinatorInfo, @Nullable ByteStreamStateHandle stateHandle) { synchronized (lock) { if (disposed) { return TaskAcknowledgeResult.DISCARDED; } final OperatorID operatorId = c...
@Test void testDuplicateAcknowledgeCoordinator() throws Exception { final OperatorInfo coordinator = new TestingOperatorInfo(); final PendingCheckpoint checkpoint = createPendingCheckpointWithCoordinators(coordinator); checkpoint.acknowledgeCoordinatorState(coordinator, new TestingStreamSta...
public static void emptyCheck(String paramName, String value) { if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("The value of " + paramName + " can't be empty"); } }
@Test public void testEmptyCheck() { assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.emptyCheck("param1", "")); assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.emptyCheck("param2", null)); ValueValidationUtil.emptyCheck("param3", "nonEmpty"); ...
@Private public void handleEvent(JobHistoryEvent event) { synchronized (lock) { // If this is JobSubmitted Event, setup the writer if (event.getHistoryEvent().getEventType() == EventType.AM_STARTED) { try { AMStartedEvent amStartedEvent = (AMStartedEvent) event.getHist...
@Test (timeout=50000) public void testTimelineEventHandling() throws Exception { TestParams t = new TestParams(RunningAppContext.class, false); Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); long currentTime = System.currentTimeMillis()...
@Override public boolean overlap(final Window other) throws IllegalArgumentException { if (getClass() != other.getClass()) { throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type " + other.getClass() + "."); } final Ti...
@Test public void shouldOverlapIfOtherWindowContainsThisWindow() { /* * This: [-------) * Other: [------------------) */ assertTrue(window.overlap(new TimeWindow(0, end))); assertTrue(window.overlap(new TimeWindow(0, end + 1))); assertTrue(window.ove...
public long getActualStartTimeMs() { return actualStartTime; }
@Test void initCreate_noStartTime_setsCurrentTime() { AsyncInitializationWrapper init = new AsyncInitializationWrapper(); long initTime = ManagementFactory.getRuntimeMXBean().getStartTime(); assertEquals(initTime, init.getActualStartTimeMs()); }
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldParseCreateAsStatement() { // When: List<CommandParser.ParsedCommand> commands = parse("CREATE STREAM FOO AS SELECT col1, col2 + 2 FROM BAR;"); // Then: assertThat(commands.size(), is(1)); assertThat(commands.get(0).getStatement().isPresent(), is (false)); assertThat(c...
public static ApiVersionCollection filterApis( RecordVersion minRecordVersion, ApiMessageType.ListenerType listenerType, boolean enableUnstableLastVersion, boolean clientTelemetryEnabled ) { ApiVersionCollection apiKeys = new ApiVersionCollection(); for (ApiKeys apiKe...
@Test public void testMetadataQuorumApisAreDisabled() { ApiVersionsResponse response = new ApiVersionsResponse.Builder(). setThrottleTimeMs(AbstractResponse.DEFAULT_THROTTLE_TIME). setApiVersions(ApiVersionsResponse.filterApis( RecordVersion.current(), ...
@Deprecated @Override public void init(final ProcessorContext context, final StateStore root) { this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null; taskId = context.taskId(); initStoreSerde(context); s...
@Test public void shouldDelegateInit() { setUp(); final MeteredSessionStore<String, String> outer = new MeteredSessionStore<>( innerStore, STORE_TYPE, Serdes.String(), Serdes.String(), new MockTime() ); doNothing().when(inne...
@Override public void populateDisplayData(DisplayData.Builder builder) { builder .add(DisplayData.item("maxAttempts", maxAttempts).withLabel("maxAttempts")) .add(DisplayData.item("initialBackoff", initialBackoff).withLabel("initialBackoff")) .add(DisplayData.item("samplePeriod", samplePeri...
@Test public void populateDisplayData() { //noinspection unchecked ArgumentCaptor<ItemSpec<?>> captor = ArgumentCaptor.forClass(DisplayData.ItemSpec.class); DisplayData.Builder builder = mock(DisplayData.Builder.class); when(builder.add(captor.capture())).thenReturn(builder); RpcQosOptions rpcQos...
public static String getMethodResourceName(Invoker<?> invoker, Invocation invocation){ return getMethodResourceName(invoker, invocation, false); }
@Test public void testGetResourceName() throws NoSuchMethodException { Invoker invoker = mock(Invoker.class); when(invoker.getInterface()).thenReturn(DemoService.class); Invocation invocation = mock(Invocation.class); Method method = DemoService.class.getDeclaredMethod("sayHello", S...
public static String printLogical(List<PlanFragment> fragments, FunctionAndTypeManager functionAndTypeManager, Session session) { Map<PlanFragmentId, PlanFragment> fragmentsById = Maps.uniqueIndex(fragments, PlanFragment::getId); PlanNodeIdGenerator idGenerator = new PlanNodeIdGenerator(); ...
@Test public void testPrintLogicalForJoinNode() { ValuesNode valuesNode = new ValuesNode(Optional.empty(), new PlanNodeId("right"), ImmutableList.of(), ImmutableList.of(), Optional.empty()); PlanNode node = new JoinNode( Optional.empty(), new PlanNodeId("join"), ...
public static String sanitizeInput(String input) { // iterate through input and keep sanitizing until it's fully injection proof String sanitizedInput; String sanitizedInputTemp = input; while (true) { sanitizedInput = sanitizeInputOnce(sanitizedInputTemp); if (sanitizedInput.equals(sanitiz...
@Test public void testSanitizeInput() { // This function is sanitize the string. It removes ";","|","&&","..." // from string. assertEquals("a", sanitizeInput("|a|")); // test the removing of pipe sign from string. assertEquals("a", sanitizeInput("...a...")); // test the removing of dots from string. ...
@Override public BulkOperationResponse executeBulkOperation(final BulkOperationRequest bulkOperationRequest, final C userContext, final AuditParams params) { if (bulkOperationRequest.entityIds() == null || bulkOperationRequest.entityIds().isEmpty()) { throw new BadRequestException(NO_ENTITY_IDS_...
@Test void returnsProperResponseOnPartiallySuccessfulBulkRemoval() throws Exception { mockUserContext(); doThrow(new MongoException("MongoDB is striking against increasing retirement age")).when(singleEntityOperationExecutor).execute(eq("1"), eq(context)); final BulkOperationResponse bulkOpe...
@GET @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "Get prekey count", description = "Gets the number of one-time prekeys uploaded for this device and still available") @ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", use...
@Test void putPrekeyWithInvalidSignature() { final ECSignedPreKey badSignedPreKey = KeysHelper.signedECPreKey(1, Curve.generateKeyPair()); final SetKeysRequest setKeysRequest = new SetKeysRequest(List.of(), badSignedPreKey, null, null); Response response = resources.getJerseyTest() .ta...
@Nonnull public static String pathToString(@Nonnull Path path) { return path.toString(); }
@Test void testPathToString() { assertEquals("foo" + File.separator + "bar.txt", StringUtil.pathToString(Paths.get("foo/bar.txt"))); }
public static <K, V> KvSwap<K, V> create() { return new KvSwap<>(); }
@Test @Category(NeedsRunner.class) public void testKvSwapEmpty() { PCollection<KV<String, Integer>> input = p.apply( Create.of(Arrays.asList(EMPTY_TABLE)) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<KV<Integer, String>> output =...
@SuppressWarnings("unchecked") private UDFType deserializeUDF() { return (UDFType) deserializeObjectFromKryo(udfSerializedBytes, (Class<Serializable>) getUDFClass()); }
@SuppressWarnings("unchecked") @Test public void testDeserializeUDF() throws Exception { // test deserialize udf GenericUDFMacro udfMacro = new GenericUDFMacro(); HiveFunctionWrapper<GenericUDFMacro> functionWrapper = new HiveFunctionWrapper<>(GenericUDFMacro.class, udfMa...
public static String post(String url, String username, String password, Map<String, Object> params) throws Exception { return post(url, username, password, JSON.toJSONString(params), CONNECT_TIMEOUT_DEFAULT_IN_MILL, SOCKET_TIMEOUT_DEFAULT_IN_MILL); }
@Test public void testSimpleCase() throws Exception { String url = "https://httpbin.org/post"; Map<String, Object> params = new HashMap<String, Object>(); params.put("foo", "bar"); String rsp = HttpUtils.post(url, null,null,params); System.out.println(rsp); Assert.as...
public void sendTestEmail(String toAddress, String subject, String message) throws EmailException { try { EmailMessage emailMessage = new EmailMessage(); emailMessage.setTo(toAddress); emailMessage.setSubject(subject); emailMessage.setPlainTextMessage(message + getServerBaseUrlFooter()); ...
@Test public void sendTestEmailShouldSanitizeLog() throws Exception { logTester.setLevel(LoggerLevel.TRACE); configure(); underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a message \n containing line breaks \r that should be sanitized when logged."); assertThat(logTeste...
public static void main(String[] args) { var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); Saga.Result goodOrder = sagaOrchestrator.execute("good_order"); Saga.Result badOrder = sagaOrchestrator.execute("bad_order"); Saga.Result crashedOrder = sagaOrchestrator.execute("crashed...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> SagaApplication.main(new String[]{})); }
public static Resource file2Resource(String filename) throws MalformedURLException { Path file = Paths.get(filename); Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return resource; } else { log.error("File ca...
@Test public void testFile2Resource() throws IOException { // Define dest file path String destFilename = rootPath + System.getProperty("file.separator") + "resource.txt"; logger.info("destFilename: " + destFilename); // Define test resource File file = new File(destFilenam...
public String getCurrentGtidLastCommit() { return gtidMap.get(CURRENT_GTID_LAST_COMMIT); }
@Test public void getCurrentGtidLastCommitOutputNull() { // Arrange final LogHeader objectUnderTest = new LogHeader(0); // Act final String actual = objectUnderTest.getCurrentGtidLastCommit(); // Assert result Assert.assertNull(actual); }
public static void addNumEntriesActiveMemTableMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( ...
@Test public void shouldAddNumEntriesActiveMemTableMetric() { final String name = "num-entries-active-mem-table"; final String description = "Total number of entries in the active memtable"; runAndVerifyMutableMetric( name, description, () -> RocksDBMetric...
@SuppressWarnings("MethodLength") static void dissectControlRequest( final ArchiveEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); ...
@Test void controlRequestMigrateSegments() { internalEncodeLogHeader(buffer, 0, 1000, 1000, () -> 500_000_000L); final MigrateSegmentsRequestEncoder requestEncoder = new MigrateSegmentsRequestEncoder(); requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) ...
public static Catalog buildIcebergCatalog(String name, Map<String, String> options, Object conf) { String catalogImpl = options.get(CatalogProperties.CATALOG_IMPL); if (catalogImpl == null) { String catalogType = PropertyUtil.propertyAsString(options, ICEBERG_CATALOG_TYPE, ICEBERG_CATALOG_TYPE_H...
@Test public void buildCustomCatalog_withTypeSet() { Map<String, String> options = Maps.newHashMap(); options.put(CatalogProperties.CATALOG_IMPL, "CustomCatalog"); options.put(CatalogUtil.ICEBERG_CATALOG_TYPE, "hive"); Configuration hadoopConf = new Configuration(); String name = "custom"; ass...
public boolean isTimeout() { return System.currentTimeMillis() - start > timeout; }
@Test public void testIsTimeOut() throws Exception { MessageFuture messageFuture = new MessageFuture(); messageFuture.setTimeout(TIME_OUT_FIELD); assertThat(messageFuture.isTimeout()).isFalse(); Thread.sleep(TIME_OUT_FIELD + 1); assertThat(messageFuture.isTimeout()).isTrue();...
public void deleteKVConfig(final String namespace, final String key) { try { this.lock.writeLock().lockInterruptibly(); try { HashMap<String, String> kvTable = this.configTable.get(namespace); if (null != kvTable) { String value = kvTab...
@Test public void testDeleteKVConfig() { kvConfigManager.deleteKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest"); byte[] kvConfig = kvConfigManager.getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG); assertThat(kvConfig).isNull(); Assert.assertTrue(kvConfig =...
public static String getViewActiveVersionNode(final String databaseName, final String schemaName, final String viewName) { return String.join("/", getMetaDataNode(), databaseName, SCHEMAS_NODE, schemaName, VIEWS_NODE, viewName, ACTIVE_VERSION); }
@Test void assertGetViewActiveVersionNode() { assertThat(ViewMetaDataNode.getViewActiveVersionNode("foo_db", "foo_schema", "foo_view"), is("/metadata/foo_db/schemas/foo_schema/views/foo_view/active_version")); }
@Subscribe @AllowConcurrentEvents public void handleIndexReopening(IndicesReopenedEvent event) { for (final String index : event.indices()) { if (!indexSetRegistry.isManagedIndex(index)) { LOG.debug("Not handling reopened index <{}> because it's not managed by any index set."...
@Test @MongoDBFixtures("MongoIndexRangeServiceTest.json") public void testHandleIndexReopening() throws Exception { final DateTime begin = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC); final DateTime end = new DateTime(2016, 1, 15, 0, 0, DateTimeZone.UTC); when(indices.indexRangeStat...
public MutablePersistentHashSet<K> beginWrite() { return new MutablePersistentHashSet<>(this); }
@Test public void iterationTest() { Random random = new Random(8234890); PersistentHashSet.MutablePersistentHashSet<Integer> tree = new PersistentHashSet<Integer>().beginWrite(); int[] p = genPermutation(random); HashSet<Integer> added = new HashSet<>(); for (int i = 0; i < E...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void getStickerSet() { GetStickerSetResponse response = bot.execute(new GetStickerSet(stickerSet)); StickerSet stickerSet = response.stickerSet(); for (Sticker sticker : response.stickerSet().stickers()) { StickerTest.check(sticker, true, true); } // ...
@Operation(summary = "get", description = "Get a cluster") @GetMapping("/{id}") public ResponseEntity<ClusterVO> get(@PathVariable Long id) { return ResponseEntity.success(clusterService.get(id)); }
@Test void getReturnsNotFoundForInvalidId() { Long id = 999L; when(clusterService.get(id)).thenReturn(null); ResponseEntity<ClusterVO> response = clusterController.get(id); assertTrue(response.isSuccess()); assertNull(response.getData()); }
public static Instruction pushVlan() { return new L2ModificationInstruction.ModVlanHeaderInstruction( L2ModificationInstruction.L2SubType.VLAN_PUSH, EthType.EtherType.VLAN.ethType()); }
@Test public void testPushVlanMethod() { final Instruction instruction = Instructions.pushVlan(); final L2ModificationInstruction.ModVlanHeaderInstruction pushHeaderInstruction = checkAndConvert(instruction, Instruction.Type.L2MODIFICATION, ...
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) { Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">"); if(object == null) return null; if(object instanceof Object[]) { return (T)Array.get(object, 0); } else { ...
@Test public void testInfoValidator() { Validator<Info> infoValidator = SingletonServiceFactory.getBean(Validator.class, Info.class); Info info = SingletonServiceFactory.getBean(Info.class); Assert.assertTrue(infoValidator.validate(info)); }
@Override public String getSignVersion() { return "V4"; }
@Test public void testGetSignVersion() { DefaultAuthSigner signer = new DefaultAuthSigner(); String expectedVersion = "V4"; String actualVersion = signer.getSignVersion(); // Assert the returned version matches the expected version Assertions.assertEquals(expectedVersion, ac...
@Override public void cancel() { // we are already in the state canceling }
@Test void testCancelIsIgnored() throws Exception { try (MockStateWithExecutionGraphContext ctx = new MockStateWithExecutionGraphContext()) { Canceling canceling = createCancelingState(ctx, new StateTrackingMockExecutionGraph()); canceling.cancel(); ctx.assertNoStateTrans...
private RemotingCommand resetMasterFlushOffset(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); if (this.brokerController.getBrokerConfig().getBrokerId() != MixAll.MASTER_ID) { ...
@Test public void testResetMasterFlushOffset() throws RemotingCommandException { ResetMasterFlushOffsetHeader requestHeader = new ResetMasterFlushOffsetHeader(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.RESET_MASTER_FLUSH_OFFSET,requestHeader); RemotingComma...
public static BigDecimal minus(Object minuend, Object subtrahend) { if (!minuend.getClass().equals(subtrahend.getClass())) { throw new IllegalStateException( String.format( "Unsupported operand type, the minuend type %s is different with subtrahend typ...
@Test public void testMinus() { assertEquals(BigDecimal.valueOf(9999), ObjectUtils.minus(10000, 1)); assertEquals( BigDecimal.valueOf(4294967295L), ObjectUtils.minus(Integer.MAX_VALUE, Integer.MIN_VALUE)); assertEquals(BigDecimal.valueOf(9999999999999L), Obje...
public final void containsEntry(@Nullable Object key, @Nullable Object value) { // TODO(kak): Can we share any of this logic w/ MapSubject.containsEntry()? checkNotNull(actual); if (!actual.containsEntry(key, value)) { Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value); ...
@Test public void containsEntry() { ImmutableMultimap<String, String> multimap = ImmutableMultimap.of("kurt", "kluever"); assertThat(multimap).containsEntry("kurt", "kluever"); }
public static <U> U valueOrElse(Versioned<U> versioned, U defaultValue) { return versioned == null ? defaultValue : versioned.value(); }
@Test public void testOrElse() { Versioned<String> vv = new Versioned<>("foo", 1); Versioned<String> nullVV = null; assertThat(Versioned.valueOrElse(vv, "bar"), is("foo")); assertThat(Versioned.valueOrElse(nullVV, "bar"), is("bar")); }
@Override public boolean acquirePermission(final int permits) { long timeoutInNanos = state.get().config.getTimeoutDuration().toNanos(); State modifiedState = updateStateWithBackOff(permits, timeoutInNanos); boolean result = waitForPermissionIfNecessary(timeoutInNanos, modifiedState.nanosToW...
@Test public void reserveFewThenSkipCyclesBeforeRefresh() throws Exception { setup(Duration.ofNanos(CYCLE_IN_NANOS)); setTimeOnNanos(CYCLE_IN_NANOS); boolean permission = rateLimiter.acquirePermission(); then(permission).isTrue(); then(metrics.getAvailablePermissions()).isZe...
@Override public double p(double[] x) { return Math.exp(logp(x)); }
@Test public void testPdf() { System.out.println("pdf"); MultivariateGaussianDistribution instance = new MultivariateGaussianDistribution(mu, Matrix.of(sigma)); for (int i = 0; i < x.length; i++) { assertEquals(pdf[i], instance.p(x[i]), 1E-4); } }