focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@ApiOperation(value = "Delete a user", tags = { "Users" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the user was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested user was...
@Test public void testUpdateUserNoFields() throws Exception { User savedUser = null; try { User newUser = identityService.newUser("testuser"); newUser.setFirstName("Fred"); newUser.setLastName("McDonald"); newUser.setDisplayName("Fred McDonald"); ...
@Override public DescriptiveUrlBag toUrl(final Path file) { if(file.isVolume()) { return DescriptiveUrlBag.empty(); } final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(file.isFile()) { final String download = String.format("%s/file/%s/%s", session.get...
@Test public void testToUrl() throws Exception { final Path bucket = new Path("/test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final B2VersionIdProvider filei...
@Udf(description = "Returns the sine of an INT value") public Double sin( @UdfParameter( value = "value", description = "The value in radians to get the sine of." ) final Integer value ) { return sin(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleMoreThanPositive2Pi() { assertThat(udf.sin(9.1), closeTo(0.3190983623493521, 0.000000000000001)); assertThat(udf.sin(6.3), closeTo(0.016813900484349713, 0.000000000000001)); assertThat(udf.sin(7), closeTo(0.6569865987187891, 0.000000000000001)); assertThat(udf.sin(7L), cl...
@Override public Method getMethod() { return method; }
@Test void getMethod() { Assertions.assertEquals("sayHello", method.getMethod().getName()); }
@Operation(summary = "queryRuleList", description = "QUERY_RULE_LIST_NOTES") @GetMapping(value = "/ruleList") @ResponseStatus(HttpStatus.OK) @ApiException(QUERY_RULE_LIST_ERROR) public Result<List<DqRule>> queryRuleList() { List<DqRule> dqRules = dqRuleService.queryAllRuleList(); return ...
@Test public void testQueryRuleList() { when(dqRuleService.queryAllRuleList()).thenReturn(getRuleList()); Result<List<DqRule>> listResult = dataQualityController.queryRuleList(); Assertions.assertEquals(Status.SUCCESS.getCode(), listResult.getCode().intValue()); }
@Override public Integer call() throws Exception { return this.call( Template.class, yamlFlowParser, modelValidator, (Object object) -> { Template template = (Template) object; return template.getNamespace() + " / " + template.g...
@Test void runServer() { URL directory = TemplateValidateCommandTest.class.getClassLoader().getResource("invalidsTemplates/template.yml"); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext....
abstract void execute(Admin admin, Namespace ns, PrintStream out) throws Exception;
@Test public void testDescribeTransaction() throws Exception { String transactionalId = "foo"; String[] args = new String[] { "--bootstrap-server", "localhost:9092", "describe", "--transactional-id", transactionalId }; Desc...
@Override public KvMetadata resolveMetadata( boolean isKey, List<MappingField> resolvedFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe...
@Test @Parameters({ "true, __key", "false, this" }) public void test_resolveMetadata(boolean key, String prefix) { Map<String, String> options = Map.of( (key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT, (key ? OPTION_KEY_CLASS : OPT...
@Override public void run() { try { // We kill containers until the kernel reports the OOM situation resolved // Note: If the kernel has a delay this may kill more than necessary while (true) { String status = cgroups.getCGroupParam( CGroupsHandler.CGroupController.MEMORY, ...
@Test public void testKillOnlyRunningContainersUponOOM() throws Exception { ConcurrentHashMap<ContainerId, Container> containers = new ConcurrentHashMap<>(); Container c1 = createContainer(1, false, 1L, false); containers.put(c1.getContainerId(), c1); Container c2 = createContainer(2, false, 2...
@Override public synchronized ScheduleResult schedule() { dropListenersFromWhenFinishedOrNewLifespansAdded(); int overallSplitAssignmentCount = 0; ImmutableSet.Builder<RemoteTask> overallNewTasks = ImmutableSet.builder(); List<ListenableFuture<?>> overallBlockedFutures = new Arr...
@Test public void testScheduleNoSplits() { SubPlan plan = createPlan(); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); StageScheduler scheduler = getSourcePartitionedScheduler(createFixedSplitSou...
@Override public <VR> KTable<K, VR> aggregate(final Initializer<VR> initializer, final Aggregator<? super K, ? super V, VR> aggregator, final Materialized<K, VR, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(ini...
@Test public void shouldAggregateAndMaterializeResults() { groupedStream.aggregate( MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("aggregate") .withKeySerde(Serdes.String()) ...
public RequestUrl(String url, Map<String, String> params) { this.url = url; this.params = params; this.queryParams = initQueryParams(url); }
@Test void testRequestUrl() { RequestUrl requestUrl = new MatchUrl("/api/jobs/enqueued?offset=2&limit=2").toRequestUrl("/api/jobs/:state"); assertThat(requestUrl.getUrl()).isEqualTo("/api/jobs/enqueued?offset=2&limit=2"); }
public static void mergeMap(boolean decrypt, Map<String, Object> config) { merge(decrypt, config); }
@Test(expected = RuntimeException.class) public void testMap_key_notAllowNullOverwrite() { Map<String, Object> testMap = new HashMap<>(); testMap.put("${TEST.null: key}", "value"); CentralizedManagement.mergeMap(true, testMap); }
public static <T> T loadData(Map<String, Object> config, T existingData, Class<T> dataCls) { try { String existingConfigJson = MAPPER.writeValueAsString(existingData); Map<String, Object> existingConfig = MAPPER.readValue(...
@Test public void testLoadConsumerConfigurationData() { ConsumerConfigurationData confData = new ConsumerConfigurationData(); confData.setSubscriptionName("unknown-subscription"); confData.setPriorityLevel(10000); confData.setConsumerName("unknown-consumer"); confData.setAuto...
@ApiOperation(value = "Create Or Update the Mobile application settings (saveMobileAppSettings)", notes = "The request payload contains configuration for android/iOS applications and platform qr code widget settings." + SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @PostM...
@Test public void testSaveMobileAppSettings() throws Exception { loginSysAdmin(); MobileAppSettings mobileAppSettings = doGet("/api/mobile/app/settings", MobileAppSettings.class); assertThat(mobileAppSettings.getQrCodeConfig().getQrCodeLabel()).isEqualTo(TEST_LABEL); assertThat(mobil...
public static void checkCPSubsystemConfig(CPSubsystemConfig config) { checkTrue(config.getGroupSize() <= config.getCPMemberCount(), "The group size parameter cannot be bigger than the number of the CP member count"); checkTrue(config.getSessionTimeToLiveSeconds() > config.getSessionHear...
@Test(expected = IllegalArgumentException.class) public void testValidationFails_whenGroupSizeSetCPMemberCountNotSet() { CPSubsystemConfig config = new CPSubsystemConfig(); config.setGroupSize(3); checkCPSubsystemConfig(config); }
public void refreshMetadata(String clusterName, MetadataResponse metadataResponse) { List<Node> list = new ArrayList<>(); for (Node node : metadataResponse.getNodes()) { if (node.getRole() == ClusterRole.LEADER) { this.setLeaderNode(clusterName, node); } ...
@Test public void testRefreshMetadata() { Node node = new Node(); node.setGroup("group"); node.setRole(ClusterRole.LEADER); Node node1 = new Node(); node1.setGroup("group"); node1.setRole(ClusterRole.FOLLOWER); List<Node> nodes = new ArrayList<>(); no...
public String getName() { return name; }
@Test public void getName() throws Exception { ProviderGroup pg = new ProviderGroup(null, null); Assert.assertNull(pg.getName()); pg = new ProviderGroup("xxx"); Assert.assertEquals(pg.getName(), "xxx"); pg = new ProviderGroup("xxx", null); Assert.assertEquals(pg.get...
@Override public double readDouble() throws EOFException { return Double.longBitsToDouble(readLong()); }
@Test public void testReadDouble() throws Exception { double readDouble = in.readDouble(); long longB = Bits.readLong(INIT_DATA, 0, byteOrder == BIG_ENDIAN); double aDouble = Double.longBitsToDouble(longB); assertEquals(aDouble, readDouble, 0); }
@Override public List<String> getList(PropertyKey key) { checkArgument(key.getType() == PropertyKey.PropertyType.LIST); String value = (String) get(key); return ConfigurationUtils.parseAsList(value, key.getDelimiter()); }
@Test public void getList() { mConfiguration.set(PropertyKey.WORKER_PAGE_STORE_DIRS, Lists.newArrayList("/a", "/b", "/c")); assertEquals( Lists.newArrayList("/a", "/b", "/c"), mConfiguration.getList(PropertyKey.WORKER_PAGE_STORE_DIRS)); }
public List<KuduPredicate> convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testNot() { ConstantOperator intOp = ConstantOperator.createInt(5); ConstantOperator varcharOp = ConstantOperator.createVarchar("abc"); ScalarOperator ge1 = new BinaryPredicateOperator(BinaryType.GT, F0, intOp); ScalarOperator ge2 = new BinaryPredicateOperator(Binar...
public static boolean isGzipStream(byte[] bytes) { int minByteArraySize = 2; if (bytes == null || bytes.length < minByteArraySize) { return false; } return GZIPInputStream.GZIP_MAGIC == ((bytes[1] << 8 | bytes[0]) & 0xFFFF); }
@Test public void testIsGzipStream() { byte[] gzipBytes = new byte[2]; gzipBytes[0] = (byte) GZIPInputStream.GZIP_MAGIC; gzipBytes[1] = (byte) (GZIPInputStream.GZIP_MAGIC >> 8); byte[] invalidGzipBytes = new byte[2]; invalidGzipBytes[0] = (byte) (GZIPInputStream.GZIP_MAGIC + ...
public <T> T retryable(CheckedSupplier<T> action) throws RetryException { long attempt = 0L; do { try { attempt++; return action.get(); } catch (Exception ex) { logger.error("Backoff retry exception", ex); } ...
@Test public void testWithoutException() throws Exception { ExponentialBackoff backoff = new ExponentialBackoff(1L); CheckedSupplier<Integer> supplier = () -> 1 + 1; Assertions.assertThatCode(() -> backoff.retryable(supplier)).doesNotThrowAnyException(); Assertions.assertThat(backoff...
void clearPendingRequests() { pendingRequests.clear(); }
@Test void testClearPendingRequests() { SharingPhysicalSlotRequestBulk bulk = createBulk(); bulk.clearPendingRequests(); assertThat(bulk.getPendingRequests()).isEmpty(); }
@Override public @NotNull Iterator<E> iterator() { return new LinkedHashIterator(); }
@Test public void iterator() { final LinkedHashSet<Integer> tested = new LinkedHashSet<>(); for (int i = 0; i < 10000; ++i) { tested.add(i); } int i = 0; for (Integer key : tested) { Assert.assertEquals(i++, key.intValue()); tested.remove(...
@Override public Graph<EntityDescriptor> resolveNativeEntity(EntityDescriptor entityDescriptor) { final MutableGraph<EntityDescriptor> mutableGraph = GraphBuilder.directed().build(); mutableGraph.addNode(entityDescriptor); final ModelId modelId = entityDescriptor.id(); try { ...
@Test public void resolveMatchingDependecyForCreation() throws ValidationException { final GrokPattern noDepGrokPattern = grokPatternService.save(GrokPattern.create("HALFLIFE", "\\d\\d")); final EntityDescriptor noDepEntityDescriptor = EntityDescriptor.create(ModelId.of(noDepGrokPattern.id()), ...
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) { invokeCompletedOffsetCommitCallbacks(); if (offsets.isEmpty()) { // We guarantee that the callbacks for all commitAsync() will be invoked when // commitSync() completes, even if the u...
@Test public void testCommitOffsetMetadataSync() { subscriptions.assignFromUser(singleton(t1p)); client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE)); prepareOffsetCommitRequest(singletonMap(t1p, 100L), ...
@Override public @Nullable String getFilename() { Path fileName = getPath().getFileName(); return fileName == null ? null : fileName.toString(); }
@Test public void testGetFilename() { assertNull(toResourceIdentifier("/").getFilename()); assertEquals("tmp", toResourceIdentifier("/root/tmp").getFilename()); assertEquals("tmp", toResourceIdentifier("/root/tmp/").getFilename()); assertEquals("xyz.txt", toResourceIdentifier("/root/tmp/xyz.txt").getF...
static UContinue create(@Nullable CharSequence label) { return new AutoValue_UContinue((label == null) ? null : StringName.of(label)); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UContinue.create(null)) .addEqualityGroup(UContinue.create("foo")) .addEqualityGroup(UContinue.create("bar")) .testEquals(); }
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } checkNoComponentAnnotations(stepClass); if (hasCucumberContextConfiguration(stepClass)) { checkOnlyOneClassHasCucumberContextConfiguration(step...
@Test void shouldFailIfClassWithSpringComponentAnnotationsIsFound() { final ObjectFactory factory = new SpringFactory(); Executable testMethod = () -> factory.addClass(WithComponentAnnotation.class); CucumberBackendException actualThrown = assertThrows(CucumberBackendException.class, testMe...
public static Type fromHudiType(Schema avroSchema) { Schema.Type columnType = avroSchema.getType(); LogicalType logicalType = avroSchema.getLogicalType(); PrimitiveType primitiveType = null; boolean isConvertedFailed = false; switch (columnType) { case BOOLEAN: ...
@Test public void testArrayHudiSchema() { Schema unionSchema; Schema arraySchema; unionSchema = Schema.createUnion(Schema.create(Schema.Type.INT)); Assert.assertEquals(fromHudiType(unionSchema), ScalarType.createType(PrimitiveType.INT)); unionSchema = Schema.createUnion(Sch...
public static File zip(String srcPath) throws UtilException { return zip(srcPath, DEFAULT_CHARSET); }
@Test @Disabled public void zipMultiFileTest(){ final File[] dd={FileUtil.file("d:\\test\\qr_a.jpg") ,FileUtil.file("d:\\test\\qr_b.jpg")}; ZipUtil.zip(FileUtil.file("d:\\test\\qr.zip"),false,dd); }
protected static com.github.zafarkhaja.semver.Version parseVersion(final String version) { try { return Version.parse(version); } catch (Exception e) { throw new ElasticsearchException("Unable to parse Elasticsearch version: " + version, e); } }
@Test void testInvalidValues() { assertThatThrownBy(() -> SearchVersion.parseVersion("v1")).isInstanceOfAny(ElasticsearchException.class); assertThatThrownBy(() -> SearchVersion.parseVersion("1.2.x")).isInstanceOfAny(ElasticsearchException.class); }
public static int parseInt(String number) throws NumberFormatException { if (StrUtil.isBlank(number)) { return 0; } if (StrUtil.startWithIgnoreCase(number, "0x")) { // 0x04表示16进制数 return Integer.parseInt(number.substring(2), 16); } if (StrUtil.containsIgnoreCase(number, "E")) { // 科学计数法忽略支持,科学计数...
@Test public void parseIntTest() { int number = NumberUtil.parseInt("0xFE"); assertEquals(254, number); // 0开头 number = NumberUtil.parseInt("010"); assertEquals(10, number); number = NumberUtil.parseInt("10"); assertEquals(10, number); number = NumberUtil.parseInt(" "); assertEquals(0, number); ...
public List<String> getAddresses() { if (args.length < 3) { return Collections.singletonList(DEFAULT_BIND_ADDRESS); } List<String> addresses = Arrays.asList(args[2].split(",")); return addresses.stream().filter(InetAddresses::isInetAddress).collect(Collectors.toList()); }
@Test void assertGetAddressesWithSingleArgument() { assertThat(new BootstrapArguments(new String[]{"3306"}).getAddresses(), is(Collections.singletonList("0.0.0.0"))); }
public boolean hasContent() { return !createItems.isEmpty() || !updateItems.isEmpty() || !deleteItems.isEmpty(); }
@Test public void testHasContent() { assertTrue(configChangeContentBuilder.hasContent()); configChangeContentBuilder.getCreateItems().clear(); assertTrue(configChangeContentBuilder.hasContent()); configChangeContentBuilder.getUpdateItems().clear(); assertTrue(configChangeContentBuilder.hasContent(...
@Override public void onMsg(TbContext ctx, TbMsg msg) { String serviceIdStr = msg.getMetaData().getValue(config.getServiceIdMetaDataAttribute()); String sessionIdStr = msg.getMetaData().getValue(config.getSessionIdMetaDataAttribute()); String requestIdStr = msg.getMetaData().getValue(config....
@Test public void sendReplyToEdgeQueue() { when(ctx.getTenantId()).thenReturn(tenantId); when(ctx.getEdgeEventService()).thenReturn(edgeEventService); when(edgeEventService.saveAsync(any())).thenReturn(SettableFuture.create()); when(ctx.getDbCallbackExecutor()).thenReturn(listeningEx...
@Override public ProviderCert getProviderConnectionConfig(URL localAddress) { CertPair certPair = dubboCertManager.generateCert(); if (certPair == null) { return null; } return new ProviderCert( certPair.getCertificate().getBytes(StandardCharsets.UTF_8), ...
@Test void getProviderConnectionConfigTest() { AtomicReference<DubboCertManager> reference = new AtomicReference<>(); try (MockedConstruction<DubboCertManager> construction = Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { reference.set(mock)...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, PhotosContainerResource resource) throws Exception { KoofrClient koofrClient = koofrClientFactory.create(authData); monitor.debug( () ->...
@Test public void testImportItemFromJobStoreUserTimeZoneCalledOnce() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); when(jobStore.getStream(any(), any())).thenReturn(new InputStreamWrapper(inputStream, 5L)); UUID jobId = UUID.randomUUID(); ...
Object getFromSignalDependency(String signalDependencyName, String paramName) { try { return executor .submit(() -> fromSignalDependency(signalDependencyName, paramName)) .get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new MaestroInternalError( ...
@Test public void testInvalidGetFromSignalDependency() { when(signalDependenciesParams.get("dev/foo/bar")) .thenReturn( Collections.singletonList( Collections.singletonMap( "param1", StringParameter.builder().evaluatedResult("hello").build()))); AssertHe...
@Override protected List<String> deleteObjects(List<String> keys) throws IOException { try { DeleteObjectsRequest request = new DeleteObjectsRequest(mBucketName); request.setKeys(keys); DeleteObjectsResult result = mClient.deleteObjects(request); return result.getDeletedObjects(); } ca...
@Test public void testDeleteObjects() throws IOException { String[] stringKeys = new String[]{"key1", "key2", "key3"}; List<String> keys = new ArrayList<>(); Collections.addAll(keys, stringKeys); // test successful delete objects Mockito.when(mClient.deleteObjects(ArgumentMatchers.any(DeleteObject...
public int getErrCode() { return errCode; }
@Test void testConstructorWithFull() { NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM, "test", new RuntimeException("cause test")); assertEquals(NacosException.INVALID_PARAM, exception.getErrCode()); assertEquals("errCode: 400, errMsg...
public void addClusterMetadata(Service service, String clusterName, ClusterMetadata clusterMetadata) { MetadataOperation<ServiceMetadata> operation = buildMetadataOperation(service); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setEphemeral(service.isEphemeral()); ...
@Test void testAddClusterMetadata() { assertThrows(NacosRuntimeException.class, () -> { String clusterName = "clusterName"; ClusterMetadata clusterMetadata = new ClusterMetadata(); namingMetadataOperateService.addClusterMetadata(service, clusterName, clusterMetadata); ...
@Override public Consumer createConsumer(Processor aProcessor) throws Exception { // validate that all of the endpoint is configured properly if (getMonitorType() != null) { if (!isPlatformServer()) { throw new IllegalArgumentException(ERR_PLATFORM_SERVER); }...
@Test public void noThresholdHigh() throws Exception { JMXEndpoint ep = context.getEndpoint( "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=gauge&observedAttribute=foo&thresholdLow=100&notifyHigh=true", JMXEndpoint.class); try { ...
public static String toString(String unicode) { if (StrUtil.isBlank(unicode)) { return unicode; } final int len = unicode.length(); StringBuilder sb = new StringBuilder(len); int i; int pos = 0; while ((i = StrUtil.indexOfIgnoreCase(unicode, "\\u", pos)) != -1) { sb.append(unicode, pos, i);//写入Unic...
@Test public void convertTest5() { String str = "{\"code\":403,\"enmsg\":\"Product not found\",\"cnmsg\":\"\\u4ea7\\u54c1\\u4e0d\\u5b58\\u5728\\uff0c\\u6216\\u5df2\\u5220\\u9664\",\"data\":null}"; String res = UnicodeUtil.toString(str); assertEquals("{\"code\":403,\"enmsg\":\"Product not found\",\"cnmsg\":\"产品不存...
@Override public ConsumerBuilder<T> patternAutoDiscoveryPeriod(int periodInMinutes) { checkArgument(periodInMinutes >= 0, "periodInMinutes needs to be >= 0"); patternAutoDiscoveryPeriod(periodInMinutes, TimeUnit.MINUTES); return this; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testConsumerBuilderImplWhenPatternAutoDiscoveryPeriodPeriodIsNegative() { consumerBuilderImpl.patternAutoDiscoveryPeriod(-1, TimeUnit.MINUTES); }
public static boolean isActiveBody( String method ) { if ( Utils.isEmpty( method ) ) { return false; } return ( method.equals( HTTP_METHOD_POST ) || method.equals( HTTP_METHOD_PUT ) || method.equals( HTTP_METHOD_PATCH ) ); }
@Test public void testEntityEnclosingMethods() { assertTrue( RestMeta.isActiveBody( RestMeta.HTTP_METHOD_POST ) ); assertTrue( RestMeta.isActiveBody( RestMeta.HTTP_METHOD_PUT ) ); assertTrue( RestMeta.isActiveBody( RestMeta.HTTP_METHOD_PATCH ) ); assertFalse( RestMeta.isActiveBody( RestMeta.HTTP_METH...
public static boolean shutdownExecutorForcefully(ExecutorService executor, Duration timeout) { return shutdownExecutorForcefully(executor, timeout, true); }
@Test void testShutdownExecutorForcefully() { MockExecutorService executor = new MockExecutorService(5); assertThat( ComponentClosingUtils.shutdownExecutorForcefully( executor, Duration.ofDays(1), false)) .isTrue(); asse...
public Acl deserialize(T serialized) { final Deserializer<?> dict = deserializer.create(serialized); final Acl acl = new Acl(); final List<String> keys = dict.keys(); for(String key : keys) { final Acl.CanonicalUser user = new Acl.CanonicalUser(key); acl.addAll(us...
@Test public void testSerialize() { Acl attributes = new Acl(new Acl.UserAndRole(new Acl.CanonicalUser(), new Acl.Role("w"))); Acl clone = new AclDictionary<>().deserialize(attributes.serialize(SerializerFactory.get())); assertEquals(attributes.get(new Acl.CanonicalUser()), clone.get(new Acl...
protected long mergeNumDistinctValueEstimator(String columnName, List<NumDistinctValueEstimator> estimators, long oldNumDVs, long newNumDVs) { if (estimators == null || estimators.size() != 2) { throw new IllegalArgumentException("NDV estimators list must be set and contain exactly two elements, " + ...
@Test public void testMergeNDVEstimatorsSecondNull() { NumDistinctValueEstimator estimator1 = NumDistinctValueEstimatorFactory.getNumDistinctValueEstimator(HLL_1.serialize()); for (ColumnStatsMerger<?> MERGER : MERGERS) { List<NumDistinctValueEstimator> estimatorList = Arrays.asList(estimator1,...
protected synchronized boolean ensureCoordinatorReady(final Timer timer) { return ensureCoordinatorReady(timer, false); }
@Test public void testCoordinatorDiscoveryExponentialBackoff() { // With exponential backoff, we will get retries at 10, 20, 40, 80, 100 ms (with jitter) int shortRetryBackoffMs = 10; int shortRetryBackoffMaxMs = 100; setupCoordinator(shortRetryBackoffMs, shortRetryBackoffMaxMs); ...
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 shouldBuildKeySerdeCorrectlyForWindowedAggregate() { for (final Runnable given : given()) { // Given: clearInvocations(groupedStream, timeWindowedStream, sessionWindowedStream, aggregated, buildContext); given.run(); // When: windowedAggregate.build(planBuilder, pl...
public void harvest(Consumer<AbstractHistogram> consumer) { AbstractHistogram current = claim(_current); _current.set(claim(_inactive)); //unblock other writers try { consumer.accept(current); } catch (Throwable t) { LOG.error("failed to consume histogram for latencies metric", t); } fin...
@Test public void testNoRecording() { LatencyMetric metric = new LatencyMetric(); final AtomicLong totalCount = new AtomicLong(); metric.harvest(h -> totalCount.set(h.getTotalCount())); assertEquals(totalCount.get(), 0L); metric.harvest(h -> totalCount.set(h.getTotalCount())); assertEquals(t...
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getData(); switch (metric.getType().getValueType()) { case ...
@Test public void toMeasure_maps_alert_properties_in_dto_for_String_Metric() { MeasureDto measureDto = new MeasureDto().setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_STRING_METRIC); assertThat(measure).i...
static Map<String, Object> addField(Map<String, Object> event, Map<String, Object> fieldsToAdd) { Event tempEvent = new org.logstash.Event(event); addField(tempEvent, fieldsToAdd); return tempEvent.getData(); }
@Test public void testAddField() { // add field to empty event Event e = new Event(); String testField = "test_field"; String testStringValue = "test_value"; CommonActions.addField(e, Collections.singletonMap(testField, testStringValue)); Assert.assertEquals(testStrin...
abstract public <T extends ComponentRoot> T get(Class<T> providerId);
@Test public void testAppRoot_withEfestoAppRootAsComponentRoot() { LocalComponentIdA retrievedA = new ReflectiveAppRoot() .get(EfestoAppRoot.class) .get(EfestoComponentRootBar.class) .get(ComponentRootA.class) .get("fileName", "name"); ...
public Header getHeader() { return header; }
@Test public void testHeader() { Assertions.assertDoesNotThrow(() -> generateDataFilePredictable()); File reportFile = new File(testDir, "test.data"); Assumptions.assumeTrue(reportFile.exists()); try (LogReader reader = new LogReader(reportFile)) { Header fileHeader = r...
public String getSubscriptionDurability() { if (!isEmpty(subscriptionDurability)) { return subscriptionDurability; } return null; }
@Test(timeout = 60000) public void testDefaultSubscriptionDurabilitySetCorrectly() { assertEquals("Incorrect default value", ActiveMQActivationSpec.NON_DURABLE_SUBSCRIPTION, activationSpec.getSubscriptionDurability()); }
public <T> MongoCollection<T> nonEntityCollection(String collectionName, Class<T> valueType) { return getCollection(collectionName, valueType); }
@Test void testEncryptedValue() { final MongoCollection<Secret> collection = collections.nonEntityCollection("secrets", Secret.class); final EncryptedValue encryptedValue = encryptedValueService.encrypt("gary"); collection.insertOne(new Secret(encryptedValue)); assertThat(collection....
public void refreshConnectorTableBasicStatisticsCache(String catalogName, String dbName, String tableName, List<String> columns, boolean async) { Table table; try { table = MetaUtils.getTable(catalogName, dbName, tableName); }...
@Test public void testRefreshConnectorTableBasicStatisticsCache(@Mocked CachedStatisticStorage cachedStatisticStorage) { Table table = connectContext.getGlobalStateMgr().getMetadataMgr().getTable("hive0", "partitioned_db", "t1"); new Expectations() { { cachedStatisticStor...
@Override public boolean renameTo(File dest) throws IOException { ObjectUtil.checkNotNull(dest, "dest"); if (byteBuf == null) { // empty file if (!dest.createNewFile()) { throw new IOException("file exists already: " + dest); } return t...
@Test public void testRenameTo() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null); tmpFile.deleteOnExit(); final int totalByteCount = 4096; ...
public boolean addAll(final IntArrayList list) { @DoNotSub final int numElements = list.size; if (numElements > 0) { ensureCapacityPrivate(size + numElements); System.arraycopy(list.elements, 0, elements, size, numElements); size += numElements; ...
@Test void shouldCreateObjectRefArray() { final int count = 20; final List<Integer> expected = new ArrayList<>(); IntStream.range(0, count).forEachOrdered(expected::add); list.addAll(expected); assertArrayEquals(expected.toArray(), list.toArray()); }
@Override public Block apply(Block rowNumberBlock) { requireNonNull(rowNumberBlock, "rowNumberBlock is null"); int positionCount = rowNumberBlock.getPositionCount(); Block lazyBlock = new LazyBlock(positionCount, (block) -> { BlockBuilder blockBuilder = VARBINARY.createBlock...
@Test public void testApply() { Block rowNumbers = new LongArrayBlockBuilder(null, 5) .writeLong(7L) .writeLong(Long.MIN_VALUE) .writeLong(0L) .writeLong(1L) .writeLong(-1L) .writeLong(Long.MAX_VALUE) ...
public static <T> void forEachWithIndex(Iterable<T> iterable, ObjectIntProcedure<? super T> procedure) { FJIterate.forEachWithIndex(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
@Test public void testForEachWithIndexToArrayUsingImmutableList() { Integer[] array = new Integer[200]; ImmutableList<Integer> list = Interval.oneTo(200).toList().toImmutable(); assertTrue(ArrayIterate.allSatisfy(array, Predicates.isNull())); FJIterate.forEachWithIndex(list, (eac...
public abstract void scan(File dir, FileVisitor visitor) throws IOException;
@Test public void globShouldUseDefaultExcludes() throws Exception { FilePath tmp = new FilePath(tmpRule.getRoot()); try { tmp.child(".gitignore").touch(0); FilePath git = tmp.child(".git"); git.mkdirs(); git.child("HEAD").touch(0); DirScanner ...
@Override public Table getTable(String dbName, String tblName) { Table table; try { table = hmsOps.getTable(dbName, tblName); } catch (StarRocksConnectorException e) { LOG.error("Failed to get hive table [{}.{}.{}]", catalogName, dbName, tblName, e); throw...
@Test public void testShowCreateHiveTbl() { HiveTable hiveTable = (HiveTable) hiveMetadata.getTable("db1", "table1"); Assert.assertEquals("CREATE TABLE `table1` (\n" + " `col2` int(11) DEFAULT NULL,\n" + " `col1` int(11) DEFAULT NULL\n" + ")\n" + ...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = cross.getValue(index); traceIsSatisfied(index, satisfied); return satisfied; }
@Test public void onlyThresholdBetweenFirstBarAndLastBar() { Indicator<Num> evaluatedIndicator = new FixedDecimalIndicator(series, 11, 10, 10, 9); CrossedDownIndicatorRule rule = new CrossedDownIndicatorRule(evaluatedIndicator, 10); assertFalse(rule.isSatisfied(0)); assertFalse(rule...
@Override public boolean passes(final String scope) { if (skipTestScope && SCOPE_TEST.equals(scope)) { return true; } if (skipProvidedScope && SCOPE_PROVIDED.equals(scope)) { return true; } if (skipSystemScope && SCOPE_SYSTEM.equals(scope)) { ...
@Test public void shouldExcludeArtifact() { final Filter<String> artifactScopeExcluded = new ArtifactScopeExcluded(skipTestScope, skipProvidedScope, skipSystemScope, skipRuntimeScope); assertThat(expectedResult, is(equalTo(artifactScopeExcluded.passes(testString)))); }
@Override public Flux<ServiceInstance> getInstances(String serviceId) { return Mono.justOrEmpty(serviceId).flatMapMany(loadInstancesFromPolaris()) .subscribeOn(Schedulers.boundedElastic()); }
@Test public void testGetInstances() throws PolarisException { when(serviceDiscovery.getInstances(anyString())).thenAnswer(invocation -> { String serviceName = invocation.getArgument(0); if (SERVICE_PROVIDER.equalsIgnoreCase(serviceName)) { return singletonList(mock(ServiceInstance.class)); } else {...
public static DecimalParseResult parseIncludeLeadingZerosInPrecision(String stringValue) { return parse(stringValue, true); }
@Test public void testParseIncludeLeadingZerosInPrecision() { assertParseResultIncludeLeadingZerosInPrecision("0", 0L, 1, 0); assertParseResultIncludeLeadingZerosInPrecision("+0", 0L, 1, 0); assertParseResultIncludeLeadingZerosInPrecision("-0", 0L, 1, 0); assertParseResultInclude...
public void disableBroker() throws Exception { serviceUnitStateChannel.cleanOwnerships(); leaderElectionService.close(); brokerRegistry.unregister(); // Close the internal topics (if owned any) after giving up the possible leader role, // so that the subsequent lookups could hit ...
@Test public void testDisableBroker() throws Exception { // Test rollback to modular load manager. ServiceConfiguration defaultConf = getDefaultConf(); defaultConf.setAllowAutoTopicCreation(true); defaultConf.setForceDeleteNamespaceAllowed(true); defaultConf.setLoadManagerCla...
@Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringC...
@Test public final void getCacheShouldReturnNullItWasChangedByRemoteCacheManager() { // When objectUnderTest.getCache(TEST_CACHE_NAME); remoteCacheManager.administration().removeCache(TEST_CACHE_NAME); // Then assertNull(objectUnderTest.getCache(TEST_CACHE_NAME)); }
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { if ( isJettyMode() && !request.getContextPath().startsWith( CONTEXT_PATH ) ) { return; } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "ExecuteTransServlet.Lo...
@Test public void doGetMissingMandatoryParamRepoTest() throws Exception { HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class ); HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class ); KettleLogStore.init(); StringWriter out = new StringWriter(); Pr...
static String readFileContents(String fileName) { try { File file = new File(fileName); return Files.readString(file.toPath(), StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException("Could not get " + fileName, e); } }
@Test public void readFileContents() throws IOException { // given String expectedContents = "Hello, world!\nThis is a test with Unicode ✓."; String testFile = createTestFile(expectedContents); // when String actualContents = AzureDiscoveryStrategyFactory.readFil...
@Override public int size() { return eventHandler.size(); }
@Test public void testHandleExceptionThrowingAnException() throws Exception { try (KafkaEventQueue queue = new KafkaEventQueue(Time.SYSTEM, logContext, "testHandleExceptionThrowingAnException")) { CompletableFuture<Void> initialFuture = new CompletableFuture<>(); queue.append(() -> i...
public static ResolvableInetSocketAddress wrap(InetSocketAddress socketAddress) { if (socketAddress == null) { return null; } return new ResolvableInetSocketAddress(socketAddress); }
@Test public void testWrapWithNull() throws Exception { assertThat(ResolvableInetSocketAddress.wrap(null)).isNull(); }
@Override public boolean contains(Object o) { for (M member : members) { if (selector.select(member) && o.equals(member)) { return true; } } return false; }
@Test public void testDoesNotContainOtherMemberWhenDataMembersSelected() { Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, DATA_MEMBER_SELECTOR); assertFalse(collection.contains(nonExistingMember)); }
public SymbolTableMetadata extractMetadata(String fullName) { int index = fullName.indexOf(SERVER_NODE_URI_PREFIX_TABLENAME_SEPARATOR); // If no separator char was found, we assume it's a local table. if (index == -1) { return new SymbolTableMetadata(null, fullName, false); } if (index...
@Test public void testExtractTableInfoLocalTable() { SymbolTableMetadata metadata = new SymbolTableMetadataExtractor().extractMetadata("Prefix-1000"); Assert.assertNull(metadata.getServerNodeUri()); Assert.assertEquals(metadata.getSymbolTableName(), "Prefix-1000"); Assert.assertFalse(metadat...
@Override public synchronized Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) { selectedBundlesCache.clear(); final double threshold = conf.getLoadBalancerBrokerThresho...
@Test public void testLowerBoundarySheddingBrokerWithOneBundle() { int brokerNum = 11; int lowLoadNode = 5; int brokerWithManyBundles = 3; LoadData loadData = new LoadData(); double throughput = 100 * 1024 * 1024; //There are 11 Brokers, of which 10 are loaded at 80% ...
public static Read<DynamicMessage> readProtoDynamicMessages( ProtoDomain domain, String fullMessageName) { SerializableFunction<PubsubMessage, DynamicMessage> parser = message -> { try { return DynamicMessage.parseFrom( domain.getDescriptor(fullMessageName), messa...
@Test public void testProtoDynamicMessagesFromDescriptor() { ProtoCoder<Primitive> coder = ProtoCoder.of(Primitive.class); ImmutableList<Primitive> inputs = ImmutableList.of( Primitive.newBuilder().setPrimitiveInt32(42).build(), Primitive.newBuilder().setPrimitiveBool(true).bui...
public static <T> T checkNotNull(T argument, String name) { if (argument == null) { throw new NullPointerException(name + " can't be null"); } return argument; }
@Test public void test_checkNotNull2_whenNotNull() { checkNotNull(new LinkedList(), "foo"); }
public static Optional<Object> doLogin(final String username, final String password, final String url) throws IOException { Map<String, Object> loginMap = new HashMap<>(2); loginMap.put(Constants.LOGIN_NAME, username); loginMap.put(Constants.PASS_WORD, password); String result = OkHttpTo...
@Test public void testDoLogin() throws IOException { final String userName = "userName"; final String password = "password"; final String token = "token"; Map<String, Object> loginMap = new HashMap<>(2); loginMap.put(Constants.LOGIN_NAME, userName); loginMap.put(Const...
public static boolean isBlank(final CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; }
@Test public void testIsBlank() { assertFalse(StringUtils.isBlank("abc")); assertTrue(StringUtils.isNotBlank("abc")); assertTrue(StringUtils.isBlank(" ")); assertTrue(StringUtils.isBlank(null)); }
public static boolean xor(boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty"); } boolean result = false; for (final boolean element : array) { result ^= element; } return result; }
@Test public void xorTest(){ assertTrue(BooleanUtil.xor(true,false)); assertTrue(BooleanUtil.xorOfWrap(true,false)); }
public ByteBuffer fetchOnePacket() throws IOException { int readLen; ByteBuffer result = defaultBuffer; result.clear(); while (true) { headerByteBuffer.clear(); readLen = readAll(headerByteBuffer); if (readLen != PACKET_HEADER_LEN) { /...
@Test public void testReceive() throws IOException { // mock new Expectations() { { channel.read((ByteBuffer) any); minTimes = 0; result = new Delegate() { int fakeRead(ByteBuffer buffer) { MysqlS...
public static List<String> getAliasesGroup(String registry) { for (ImmutableSet<String> aliasGroup : REGISTRY_ALIAS_GROUPS) { if (aliasGroup.contains(registry)) { // Found a group. Move the requested "registry" to the front before returning it. Stream<String> self = Stream.of(registry); ...
@Test public void testGetAliasesGroup_noKnownAliases() { List<String> singleton = RegistryAliasGroup.getAliasesGroup("something.gcr.io"); Assert.assertEquals(1, singleton.size()); Assert.assertEquals("something.gcr.io", singleton.get(0)); }
public ReliableTopicConfig addMessageListenerConfig(ListenerConfig listenerConfig) { checkNotNull(listenerConfig, "listenerConfig can't be null"); listenerConfigs.add(listenerConfig); return this; }
@Test public void addMessageListenerConfig() { ReliableTopicConfig config = new ReliableTopicConfig("foo"); ListenerConfig listenerConfig = new ListenerConfig("foobar"); config.addMessageListenerConfig(listenerConfig); assertEquals(List.of(listenerConfig), config.getMessageListener...
@Override public K getKey() { if (keyObject == null) { keyObject = serializationService.toObject(keyData); } return keyObject; }
@Test public void testGetKey() { String keyObject = "key"; Data keyData = serializationService.toData(keyObject); QueryableEntry entry = createEntry(keyData, new Object(), newExtractor()); Object key = entry.getKey(); assertEquals(keyObject, key); }
public static List<UnixMountInfo> getUnixMountInfo() throws IOException { Preconditions.checkState(OSUtils.isLinux() || OSUtils.isMacOS()); String output = execCommand(MOUNT_COMMAND); List<UnixMountInfo> mountInfo = new ArrayList<>(); for (String line : output.split("\n")) { mountInfo.add(parseMou...
@Test public void getMountInfo() throws Exception { assumeTrue(OSUtils.isMacOS() || OSUtils.isLinux()); List<UnixMountInfo> info = ShellUtils.getUnixMountInfo(); assertTrue(info.size() > 0); }
public int[] startBatchWithRunStrategy( @NotNull String workflowId, @NotNull RunStrategy runStrategy, List<WorkflowInstance> instances) { if (instances == null || instances.isEmpty()) { return new int[0]; } return withMetricLogError( () -> { Set<String> uuids = ...
@Test public void testStartBatchRunStrategyWithFirstOnly() throws Exception { List<WorkflowInstance> batch = prepareBatch(); int[] res = runStrategyDao.startBatchWithRunStrategy( TEST_WORKFLOW_ID, RunStrategy.create("FIRST_ONLY"), batch); assertArrayEquals(new int[] {1, 0, -1}, res); ...
public static Predicate decode(byte[] buf) { Objects.requireNonNull(buf, "buf"); Slime slime = com.yahoo.slime.BinaryFormat.decode(buf); return decode(slime.get()); }
@Test void requireThatDecodeNullThrows() { try { BinaryFormat.decode(null); fail(); } catch (NullPointerException e) { assertEquals("buf", e.getMessage()); } }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testNetVersion() throws Exception { web3j.netVersion().send(); verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"net_version\",\"params\":[],\"id\":1}"); }
public String build( final String cellValue ) { switch ( type ) { case FORALL: return buildForAll( cellValue ); case INDEXED: return buildMulti( cellValue ); default: return buildSingle( cellValue ); } }
@Test public void testForAllOrMultiple() { final String snippet = "forall(||){something == $} && forall(||){something < $}"; final SnippetBuilder snip = new SnippetBuilder(snippet); final String result = snip.build("x, y"); assertThat(result).isEqualTo("something == x || something ==...
@Override public List<String> readMultiParam(String key) { String[] values = source.getParameterValues(key); return values == null ? emptyList() : ImmutableList.copyOf(values); }
@Test public void read_multi_param_from_source_with_values() { when(source.getParameterValues("param")).thenReturn(new String[]{"firstValue", "secondValue", "thirdValue"}); List<String> result = underTest.readMultiParam("param"); assertThat(result).containsExactly("firstValue", "secondValue", "thirdValu...
public void addWriteStat(String partitionPath, HoodieWriteStat stat) { if (!partitionToWriteStats.containsKey(partitionPath)) { partitionToWriteStats.put(partitionPath, new ArrayList<>()); } partitionToWriteStats.get(partitionPath).add(stat); }
@Test public void verifyFieldNamesInCommitMetadata() throws IOException { List<HoodieWriteStat> fakeHoodieWriteStats = HoodieTestUtils.generateFakeHoodieWriteStat(10); HoodieCommitMetadata commitMetadata = new HoodieCommitMetadata(); fakeHoodieWriteStats.forEach(stat -> commitMetadata.addWriteStat(stat.ge...
@Override public CompletableFuture<SchemaAndMetadata> getSchema(String schemaId) { return this.service.getSchema(schemaId); }
@Test public void testGetSchemaByVersion() { String schemaId = "test-schema-id"; CompletableFuture<SchemaAndMetadata> getFuture = new CompletableFuture<>(); when(underlyingService.getSchema(eq(schemaId), any(SchemaVersion.class))) .thenReturn(getFuture); assertSame(getFut...
public static String toShortString(Throwable e, int stackLevel) { StackTraceElement[] traces = e.getStackTrace(); StringBuilder sb = new StringBuilder(1024); sb.append(e.toString()).append("\t"); if (traces != null) { for (int i = 0; i < traces.length; i++) { ...
@Test public void toShortString() throws Exception { SofaRpcException exception = new SofaRpcException(RpcErrorType.SERVER_BUSY, "111"); String string = ExceptionUtils.toShortString(exception, 1); Assert.assertNotNull(string); Pattern pattern = Pattern.compile("at"); Matcher ...
public void undelete() { // make a copy because the selected trash items changes as soon as trashService.undelete is called List<UIDeletedObject> selectedTrashFileItemsSnapshot = new ArrayList<UIDeletedObject>( selectedTrashFileItems ); if ( selectedTrashFileItemsSnapshot != null && selectedTrashFileItemsSn...
@Test public void testUnDeleteTransformation() throws Exception { testUnDelete( RepositoryObjectType.TRANSFORMATION.name(), true ); verify( trashServiceMock, times( 1 ) ).undelete( anyList() ); verify( transMetaMock, times( 1 ) ).clearChanged(); verify( repositoryMock, times( 1 ) ).loadTransformation...
public Object getAsJavaType( String valueName, Class<?> destinationType, InjectionTypeConverter converter ) throws KettleValueException { int idx = rowMeta.indexOfValue( valueName ); if ( idx < 0 ) { throw new KettleValueException( "Unknown column '" + valueName + "'" ); } ValueMetaInterface ...
@Test public void testIntegerConversion() throws Exception { row = new RowMetaAndData( rowsMeta, null, null, 7L ); assertEquals( true, row.getAsJavaType( "int", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "int", Boolean.class, converter ) ); assertEquals( 7, row.getAsJavaType...
public static <T> List<LocalProperty<T>> grouped(Collection<T> columns) { return ImmutableList.of(new GroupingProperty<>(columns)); }
@Test public void testConstantWithMultiGroup() { List<LocalProperty<String>> actual = builder() .constant("a") .grouped("a", "b") .grouped("a", "c") .build(); assertMatch( actual, builder().grouped("...