focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static UForAll create(List<UTypeVar> typeVars, UType quantifiedType) { return new AutoValue_UForAll(ImmutableList.copyOf(typeVars), quantifiedType); }
@Test public void serialization() { UType nullType = UPrimitiveType.create(TypeKind.NULL); UType objectType = UClassType.create("java.lang.Object", ImmutableList.<UType>of()); UTypeVar eType = UTypeVar.create("E", nullType, objectType); UType listOfEType = UClassType.create("java.util.List", Immutable...
public static void unzip(Path archive, Path destination) throws IOException { unzip(archive, destination, false); }
@Test public void testUnzip_modificationTimePreserved() throws URISyntaxException, IOException { Path archive = Paths.get(Resources.getResource("plugins-common/test-archives/test.zip").toURI()); Path destination = tempFolder.getRoot().toPath(); ZipUtil.unzip(archive, destination); assertThat...
public static String stringifyException(final Throwable e) { if (e == null) { return STRINGIFIED_NULL_EXCEPTION; } try { StringWriter stm = new StringWriter(); PrintWriter wrt = new PrintWriter(stm); e.printStackTrace(wrt); wrt.close()...
@Test void testStringifyNullException() { assertThat(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION) .isEqualTo(ExceptionUtils.stringifyException(null)); }
public static void initializeBootstrapProperties( Properties properties, Optional<String> bootstrapServer, Optional<String> bootstrapControllers ) { if (bootstrapServer.isPresent()) { if (bootstrapControllers.isPresent()) { throw new InitializeBootstrapExc...
@Test public void testInitializeBootstrapPropertiesWithControllerBootstrap() { Properties props = createTestProps(); CommandLineUtils.initializeBootstrapProperties(props, Optional.empty(), Optional.of("127.0.0.2:9094")); assertNull(props.getProperty("bootstrap.servers")); ...
public static final void saveAttributesMap( DataNode dataNode, AttributesInterface attributesInterface ) throws KettleException { saveAttributesMap( dataNode, attributesInterface, NODE_ATTRIBUTE_GROUPS ); }
@Test public void testSaveAttributesMap_DefaultTag() throws Exception { try( MockedStatic<AttributesMapUtil> mockedAttributesMapUtil = mockStatic( AttributesMapUtil.class) ) { mockedAttributesMapUtil.when( () -> AttributesMapUtil.saveAttributesMap( any( DataNode.class ), any( AttributesInterface.cl...
public static ProxyBackendHandler newInstance(final DatabaseType databaseType, final String sql, final SQLStatement sqlStatement, final ConnectionSession connectionSession, final HintValueContext hintValueContext) throws SQLException { if (sqlStatement instanceo...
@Disabled("FIXME") @Test void assertNewInstanceWithQuery() throws SQLException { String sql = "SELECT * FROM t_order limit 1"; ProxyContext proxyContext = ProxyContext.getInstance(); when(proxyContext.getAllDatabaseNames()).thenReturn(new HashSet<>(Collections.singletonList("db"))); ...
@Override public int getUnsignedMedium(int index) { checkIndex(index, 3); return _getUnsignedMedium(index); }
@Test public void testGetUnsignedMediumAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getUnsignedMedium(0); } }); }
public static double[] toDoubleArray(String name, Object value) { try { if (value instanceof BigDecimal[]) { return Arrays.stream((BigDecimal[]) value).mapToDouble(BigDecimal::doubleValue).toArray(); } else if (value instanceof double[]) { return (double[]) value; } else if (value ...
@Test public void testInvalidToDoubleArray() { AssertHelper.assertThrows( "Invalid number format", MaestroInternalError.class, "Invalid number format for evaluated result: [true, 5.6]", () -> ParamHelper.toDoubleArray("foo", Arrays.asList(true, 5.6))); AssertHelper.assertThrow...
@SuppressWarnings("unchecked") @Override public <T> Attribute<T> attr(AttributeKey<T> key) { ObjectUtil.checkNotNull(key, "key"); DefaultAttribute newAttribute = null; for (;;) { final DefaultAttribute[] attributes = this.attributes; final int index = searchAttrib...
@Test public void testGetSetInt() { AttributeKey<Integer> key = AttributeKey.valueOf("Nada"); Attribute<Integer> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent(3653); assertEquals(Integer.valueOf(3653), one.get()); one.setIfAbsent(1); ...
public static <R> R callConstructor( Class<? extends R> clazz, ClassParameter<?>... classParameters) { perfStatsCollector.incrementCount("ReflectionHelpers.callConstructor-" + clazz.getName()); try { final Class<?>[] classes = ClassParameter.getClasses(classParameters); final Object[] values =...
@Test public void callConstructorReflectively_rethrowsUncheckedException() { try { ReflectionHelpers.callConstructor(ThrowsUncheckedException.class); fail("Expected exception not thrown"); } catch (TestRuntimeException e) { } catch (RuntimeException e) { throw new RuntimeException("Incor...
public static Pair<DataSchema, int[]> getResultTableDataSchemaAndColumnIndices(QueryContext queryContext, DataSchema dataSchema) { List<ExpressionContext> selectExpressions = queryContext.getSelectExpressions(); int numSelectExpressions = selectExpressions.size(); ColumnDataType[] columnDataTypesInDat...
@Test public void testGetResultTableColumnIndices() { // Select * without order-by QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT * FROM testTable"); DataSchema dataSchema = new DataSchema(new String[]{"col1", "col2", "col3"}, new ColumnDataType[]{ ColumnDataType.IN...
boolean sendRecords() { int processed = 0; recordBatch(toSend.size()); final SourceRecordWriteCounter counter = toSend.isEmpty() ? null : new SourceRecordWriteCounter(toSend.size(), sourceTaskMetricsGroup); for (final SourceRecord preTransformRecord : toSend) { ...
@Test public void testSendRecordsRetriableException() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECO...
@Override public Double getLocalValue() { if (this.count == 0) { return 0.0; } return this.sum / this.count; }
@Test void testGet() { AverageAccumulator average = new AverageAccumulator(); assertThat(average.getLocalValue()).isCloseTo(0.0, within(0.0)); }
@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 throwsBadRequestExceptionOnEmptyEntityIdsList() { assertThrows(BadRequestException.class, () -> toTest.executeBulkOperation(new BulkOperationRequest(List.of()), context, params), NO_ENTITY_IDS_ERROR); }
@Override public Object toConnectRow(final Object ksqlData) { final Object compatible = ConnectSchemas.withCompatibleSchema(avroCompatibleSchema, ksqlData); return innerTranslator.toConnectRow(compatible); }
@Test public void shouldUseExplicitSchemaName() { // Given: final Schema schema = SchemaBuilder.struct() .field("COLUMN_NAME", Schema.OPTIONAL_INT64_SCHEMA) .optional() .build(); final String schemaFullName = "com.custom.schema"; final AvroDataTranslator dataTranslator = new ...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test public void testAndAnd() { final Predicate parsed = PredicateExpressionParser.parse("com.linkedin.data.it.AlwaysTruePredicate & com.linkedin.data.it.AlwaysTruePredicate & com.linkedin.data.it.AlwaysFalsePredicate"); Assert.assertEquals(parsed.getClass(), AndPredicate.class); final List<Predicate>...
@Override public void addTask(Object key, AbstractDelayTask newTask) { super.addTask(key, newTask); MetricsMonitor.getDumpTaskMonitor().set(tasks.size()); }
@Test void testRemoveProcessor() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(true); taskManager.addProcessor("test", testTaskProcessor); taskManager.removeProcessor("test"); taskManager.addTask("test", abstractTask); TimeUnit.MILLISECOND...
@Override public void onActivityCreated(Activity activity, Bundle bundle) { }
@Test public void onActivityCreated() { mActivityLifecycle.onActivityCreated(mActivity, null); }
public PipelineOptions get() { return options; }
@Test public void testSerializationAndDeserialization() throws Exception { PipelineOptions options = PipelineOptionsFactory.fromArgs("--foo=testValue", "--ignoredField=overridden") .as(MyOptions.class); SerializablePipelineOptions serializableOptions = new SerializablePipelineOptions(opti...
public static void removeDupes( final List<CharSequence> suggestions, List<CharSequence> stringsPool) { if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i...
@Test public void testRemoveDupesOneItemTwoTypes() throws Exception { ArrayList<CharSequence> list = new ArrayList<>(Arrays.<CharSequence>asList("typed", "something")); IMEUtil.removeDupes(list, mStringPool); Assert.assertEquals(2, list.size()); Assert.assertEquals("typed", list.get(0)); A...
@Override public void init(File dataFile, @Nullable Set<String> fieldsToRead, @Nullable RecordReaderConfig recordReaderConfig) throws IOException { _dataFile = dataFile; CSVRecordReaderConfig config = (CSVRecordReaderConfig) recordReaderConfig; Character multiValueDelimiter = null; if (config ==...
@Test public void testInvalidDelimiterInHeader() { // setup CSVRecordReaderConfig csvRecordReaderConfig = new CSVRecordReaderConfig(); csvRecordReaderConfig.setMultiValueDelimiter(CSV_MULTI_VALUE_DELIMITER); csvRecordReaderConfig.setHeader("col1;col2;col3;col4;col5;col6;col7;col8;col9;col10"); csv...
@Override public Processor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>> get() { return new ContextualProcessor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>>() { private KT...
@Test public void shouldPropagateNullIfNoFKAvailableV0() { final MockProcessorContext<String, SubscriptionResponseWrapper<String>> context = new MockProcessorContext<>(); processor.init(context); final SubscriptionWrapper<String> newValue = new SubscriptionWrapper<>( new long[]{...
public static <T> Mono<Long> writeAll(Writer writer, Flux<T> values) throws IOException { return writeAll(DEFAULT_OBJECT_MAPPER, writer, values); }
@Test void writeAll_fromEmptySource() throws IOException { final Path outputTempFilePath = createTempFile(); final Long outputCount = FileSerde.writeAll(Files.newBufferedWriter(outputTempFilePath), Flux.empty()).block(); assertThat(outputCount, is(0L)); }
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) { if (statsEnabled) { stats.log(deviceStateServiceMsg); } stateService.onQueueMsg(deviceStateServiceMsg, callback); }
@Test public void givenStatsDisabled_whenForwardingDisconnectMsgToStateService_thenStatsAreNotRecorded() { // GIVEN ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "stats", statsMock); ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "statsEnabled", false); ...
@Override public String lowerKey(String key) { return complete(treeMap.lowerKey(key)); }
@Test(expected = ConsistentMapException.Timeout.class) public void testTimeout() { ConsistentTreeMapWithError<String> consistentMap = new ConsistentTreeMapWithError<>(); consistentMap.setErrorState(TestingCompletableFutures.ErrorState.TIMEOUT_EXCEPTION); DefaultConsistentTree...
public synchronized boolean createIndex(String indexName) throws ElasticsearchResourceManagerException { LOG.info("Creating index using name '{}'.", indexName); try { // Check to see if the index exists if (indexExists(indexName)) { return false; } managedIndexNames.add(i...
@Test public void testCreateCollectionShouldThrowErrorWhenElasticsearchFailsToGetDB() throws IOException { when(elasticsearchClient .indices() .exists(any(GetIndexRequest.class), eq(RequestOptions.DEFAULT))) .thenThrow(IllegalArgumentException.class); assertThrows( ...
@Override public WidgetType findByTenantIdAndFqn(UUID tenantId, String fqn) { return DaoUtil.getData(widgetTypeRepository.findWidgetTypeByTenantIdAndFqn(tenantId, fqn)); }
@Test public void testFindByTenantIdAndFqn() { WidgetType result = widgetTypeList.get(0); assertNotNull(result); WidgetType widgetType = widgetTypeDao.findByTenantIdAndFqn(TenantId.SYS_TENANT_ID.getId(), "FQN_0"); assertEquals(result.getId(), widgetType.getId()); }
@Override public Algorithm getEncryption(final Path file) throws BackgroundException { if(containerService.isContainer(file)) { final String key = String.format("s3.encryption.key.%s", containerService.getContainer(file).getName()); if(StringUtils.isNotBlank(new HostPreferences(sessi...
@Test public void testSetEncryptionKMSDefaultKeySignatureVersionV4() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Pat...
public static CoordinatorRecord newConsumerGroupSubscriptionMetadataRecord( String groupId, Map<String, TopicMetadata> newSubscriptionMetadata ) { ConsumerGroupPartitionMetadataValue value = new ConsumerGroupPartitionMetadataValue(); newSubscriptionMetadata.forEach((topicName, topicM...
@Test public void testNewConsumerGroupSubscriptionMetadataRecord() { Uuid fooTopicId = Uuid.randomUuid(); Uuid barTopicId = Uuid.randomUuid(); Map<String, TopicMetadata> subscriptionMetadata = new LinkedHashMap<>(); subscriptionMetadata.put("foo", new TopicMetadata( fooT...
@Override public KTable<Windowed<K>, Long> count() { return count(NamedInternal.empty()); }
@Test public void shouldMaterializeCount() { windowedStream.count( Materialized.<String, Long, WindowStore<Bytes, byte[]>>as("count-store") .withKeySerde(Serdes.String()) .withValueSerde(Serdes.Long())); try (final TopologyTestDriver driver = new Topology...
public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException { long result = 0; if (cronEntry == null || cronEntry.length() == 0) { return result; } // Handle the once per minute case "* * * * *" // starting the ne...
@Test public void testgetNextTimeMonthVariant() throws MessageFormatException { // using an absolute date so that result will be absolute - Monday 7 March 2011 Calendar current = Calendar.getInstance(); current.set(2011, Calendar.MARCH, 7, 9, 15, 30); LOG.debug("start:" + current.ge...
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testEncryptedEmptyPassword() throws Exception { PrivateKey key = SslContext.toPrivateKey( ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), ""); assertNotNull(key); }
@Operation(summary = "queryEnvironmentListPaging", description = "QUERY_ENVIRONMENT_LIST_PAGING_NOTES") @Parameters({ @Parameter(name = "searchVal", description = "SEARCH_VAL", schema = @Schema(implementation = String.class)), @Parameter(name = "pageSize", description = "PAGE_SIZE", required...
@Test public void testQueryEnvironmentListPaging() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("searchVal", "test"); paramsMap.add("pageSize", "2"); paramsMap.add("pageNo", "2"); MvcResult mvcResult = mockMvc.perfor...
public abstract int status(HttpServletResponse response);
@Test void servlet25_status_cachesUpToTenTypes() { assertThat(servlet25.status(new Response1())) .isEqualTo(200); assertThat(servlet25.status(new Response2())) .isEqualTo(200); assertThat(servlet25.status(new Response3())) .isEqualTo(200); assertThat(servlet25.status(new Response4())) ...
@Override public <R> R run(Action<R, C, E> action) throws E, InterruptedException { return run(action, retryByDefault); }
@Test public void testNoRetryingWhenDisabled() { try (MockClientPoolImpl mockClientPool = new MockClientPoolImpl(2, RetryableException.class, false, 3)) { assertThatThrownBy(() -> mockClientPool.run(client -> client.succeedAfter(3))) .isInstanceOf(RetryableException.class); assertTha...
public static <T> Map<String, T> translateDeprecatedConfigs(Map<String, T> configs, String[][] aliasGroups) { return translateDeprecatedConfigs(configs, Stream.of(aliasGroups) .collect(Collectors.toMap(x -> x[0], x -> Stream.of(x).skip(1).collect(Collectors.toList())))); }
@Test public void testDuplicateSynonyms() { Map<String, String> config = new HashMap<>(); config.put("foo.bar", "baz"); config.put("foo.bar.deprecated", "derp"); Map<String, String> newConfig = ConfigUtils.translateDeprecatedConfigs(config, new String[][]{ {"foo.bar", "fo...
@Retries.RetryTranslated public void retry(String action, String path, boolean idempotent, Retried retrying, InvocationRaisingIOE operation) throws IOException { retry(action, path, idempotent, retrying, () -> { operation.apply(); return null; }); ...
@Test public void testRetryOnThrottle() throws Throwable { final AtomicInteger counter = new AtomicInteger(0); invoker.retry("test", null, false, () -> { if (counter.incrementAndGet() < 5) { throw newThrottledException(); } }); }
@Override public String toString() { return Stream.of( elements ).filter(Objects::nonNull).collect(toList() ).toString(); }
@Test public void testShuffled() { long time = System.currentTimeMillis(); for (int k = 0; k < 10; k++) { for (Integer[] perm : perms) { Group group = new Group("group"); for (Integer i : perm) { Item item = new Item(group, ...
@Override public Map<K, V> getAll(Set<? extends K> keys) { checkNotClosed(); if (keys == null) { throw new NullPointerException(); } for (K key : keys) { checkKey(key); } if (!atomicExecution && !config.isReadThrough()) { long star...
@Test public void testGetAll() throws Exception { URL configUrl = getClass().getResource("redisson-jcache.yaml"); Config cfg = Config.fromYAML(configUrl); Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg); Cache<String, String> cache = Caching.getC...
@SuppressWarnings("ChainOfInstanceofChecks") public OpenFileInformation prepareToOpenFile( final Path path, final OpenFileParameters parameters, final long blockSize) throws IOException { Configuration options = parameters.getOptions(); Set<String> mandatoryKeys = parameters.getMandatoryKeys...
@Test public void testFileLength() throws Throwable { ObjectAssert<OpenFileSupport.OpenFileInformation> asst = assertFileInfo(prepareToOpenFile( params(FS_OPTION_OPENFILE_LENGTH, "8192") .withStatus(null))); asst.extracting(f -> f.getStatus()) .isNotNull(); asst...
@Override public URL select(List<URL> urls, String serviceId, String tag, String requestKey) { String key = tag == null ? serviceId : serviceId + "|" + tag; // search for a URL in the same ip first List<URL> localUrls = searchLocalUrls(urls, ip); if(localUrls.size() > 0) { ...
@Test public void testSelectWithEmptyList() throws Exception { List<URL> urls = new ArrayList<>(); URL url = loadBalance.select(urls, "serviceId", "tag", null); Assert.assertNull(url); }
public static void main(String[] args) throws IOException { if (args.length < 2) { _log.error("Usage: AvroSchemaGenerator targetDirectoryPath [sourceFile or sourceDirectory or schemaName]+"); System.exit(1); } String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_P...
@Test(dataProvider = "toAvroSchemaDataBeforeReferree") public void testReferrerBeforeReferreeInArgs(Map<String, String> testSchemas, String testPath, boolean override) throws IOException { Map<File, Map.Entry<String,String>> files = TestUtil.createSchemaFiles(_testDir, testSchemas, _debug); Collection<Strin...
@SuppressWarnings("unchecked") public Mono<RateLimiterResponse> isAllowed(final String id, final RateLimiterHandle limiterHandle) { double replenishRate = limiterHandle.getReplenishRate(); double burstCapacity = limiterHandle.getBurstCapacity(); double requestCount = limiterHandle.getRequest...
@Test public void leakyBucketNotAllowedTest() { leakyBucketPreInit(0L, 300L); rateLimiterHandle.setAlgorithmName("leakyBucket"); Mono<RateLimiterResponse> responseMono = redisRateLimiter.isAllowed(DEFAULT_TEST_ID, rateLimiterHandle); StepVerifier.create(responseMono).assertNext(r -> ...
public List<SchemaChangeEvent> applySchemaChange(SchemaChangeEvent schemaChangeEvent) { List<SchemaChangeEvent> events = new ArrayList<>(); TableId originalTable = schemaChangeEvent.tableId(); boolean noRouteMatched = true; for (Tuple3<Selectors, String, String> route : routes) { ...
@Test void testIncompatibleTypes() { SchemaManager schemaManager = new SchemaManager(); SchemaDerivation schemaDerivation = new SchemaDerivation(schemaManager, ROUTES, new HashMap<>()); // Create table 1 List<SchemaChangeEvent> derivedChangesAfterCreateTable = ...
@Override public Metrics toDay() { MaxFunction metrics = (MaxFunction) createNew(); metrics.setEntityId(getEntityId()); metrics.setTimeBucket(toTimeBucketInDay()); metrics.setServiceId(getServiceId()); metrics.setValue(getValue()); return metrics; }
@Test public void testToDay() { function.setTimeBucket(TimeBucket.getMinuteTimeBucket(System.currentTimeMillis())); function.accept(MeterEntity.newService("service-test", Layer.GENERAL), LARGE_VALUE); function.accept(MeterEntity.newService("service-test", Layer.GENERAL), SMALL_VALUE); ...
public IssuesChangesNotification newIssuesChangesNotification(Set<DefaultIssue> issues, Map<String, UserDto> assigneesByUuid) { AnalysisChange change = new AnalysisChange(analysisMetadataHolder.getAnalysisDate()); Set<ChangedIssue> changedIssues = issues.stream() .map(issue -> new ChangedIssue.Builder(iss...
@Test public void newIssuesChangesNotification_fails_with_ISE_if_issue_has_assignee_not_in_assigneesByUuid() { RuleKey ruleKey = RuleKey.of("foo", "bar"); String assigneeUuid = randomAlphabetic(40); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStat...
Integer calculateFeePrice(Integer withdrawPrice, Integer percent) { Integer feePrice = 0; if (percent != null && percent > 0) { feePrice = MoneyUtils.calculateRatePrice(withdrawPrice, Double.valueOf(percent)); } return feePrice; }
@Test public void testCalculateFeePrice() { Integer withdrawPrice = 100; // 测试手续费比例未设置 Integer percent = null; assertEquals(brokerageWithdrawService.calculateFeePrice(withdrawPrice, percent), 0); // 测试手续费给为0 percent = 0; assertEquals(brokerageWithdrawService.c...
@Override public Future<Map<ByteBuffer, ByteBuffer>> get(Collection<ByteBuffer> keys) { CompletableFuture<Void> endFuture = new CompletableFuture<>(); readToEnd(endFuture); return endFuture.thenApply(ignored -> { Map<ByteBuffer, ByteBuffer> values = new HashMap<>(); f...
@Test public void testGetFromEmpty() throws Exception { testOffsetBackingStore(false); assertTrue(offsetBackingStore.get( Arrays.asList(ByteBuffer.wrap("empty-key".getBytes(UTF_8))) ).get().isEmpty()); }
public static Set<String> verifyTopologyOptimizationConfigs(final String config) { final List<String> configs = Arrays.asList(config.split("\\s*,\\s*")); final Set<String> verifiedConfigs = new HashSet<>(); // Verify it doesn't contain none or all plus a list of optimizations if (configs...
@Test public void shouldEnableAllOptimizationsWithOptimizeConfig() { final Set<String> configs = StreamsConfig.verifyTopologyOptimizationConfigs(StreamsConfig.OPTIMIZE); assertEquals(3, configs.size()); assertTrue(configs.contains(StreamsConfig.REUSE_KTABLE_SOURCE_TOPICS)); assertTru...
@Override public long getPos() throws IOException { return position; }
@Test public void shouldConstructStream() throws IOException { if (empty) { assertEquals(0, fsDataOutputStream.getPos()); } else { assertEquals(position, fsDataOutputStream.getPos()); } }
@PostMapping("add-to-favourites") public Mono<String> addProductToFavourites(@ModelAttribute("product") Mono<Product> productMono) { return productMono .map(Product::id) .flatMap(productId -> this.favouriteProductsClient.addProductToFavourites(productId) ...
@Test void addProductToFavourites_RequestIsValid_RedirectsToProductPage() { // given doReturn(Mono.just(new FavouriteProduct(UUID.fromString("25ec67b4-cbac-11ee-adc8-4bd80e8171c4"), 1))) .when(this.favouriteProductsClient).addProductToFavourites(1); // when StepVerif...
public DecommissioningNodesWatcher(RMContext rmContext) { this.rmContext = rmContext; pollTimer = new Timer(true); mclock = new MonotonicClock(); }
@Test public void testDecommissioningNodesWatcher() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODE_GRACEFUL_DECOMMISSION_TIMEOUT, "40"); rm = new MockRM(conf); rm.start(); DecommissioningNodesWatcher watcher = new DecommissioningNodesWatch...
public static void createTopics( Logger log, String bootstrapServers, Map<String, String> commonClientConf, Map<String, String> adminClientConf, Map<String, NewTopic> topics, boolean failOnExisting) throws Throwable { // this method wraps the call to createTopics() that takes admin clien...
@Test public void testCreateRetriesOnTimeout() throws Throwable { adminClient.timeoutNextRequest(1); WorkerUtils.createTopics( log, adminClient, Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), true); assertEquals( new TopicDescription( TEST_TOP...
@Description("compute sha1 hash") @ScalarFunction @SqlType(StandardTypes.VARBINARY) public static Slice sha1(@SqlType(StandardTypes.VARBINARY) Slice slice) { return computeHash(Hashing.sha1(), slice); }
@Test public void testSha1() { assertFunction("sha1(CAST('' AS VARBINARY))", VARBINARY, sqlVarbinaryHex("DA39A3EE5E6B4B0D3255BFEF95601890AFD80709")); assertFunction("sha1(CAST('hashme' AS VARBINARY))", VARBINARY, sqlVarbinaryHex("FB78992E561929A6967D5328F49413FA99048D06")); }
public ProcessContinuation run( PartitionRecord partitionRecord, RestrictionTracker<StreamProgress, StreamProgress> tracker, OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator) throws IOException { BytesThroughputEstimator<...
@Test public void testCloseStreamNewPartitionMerge() throws IOException { // Force lock fail because CloseStream should not depend on locking when(metadataTableDao.doHoldLock(partition, uuid)).thenReturn(false); // NewPartitions field includes the merge target. ChangeStreamContinuationToken's partition ma...
public static void load(Configuration conf, InputStream is) throws IOException { conf.addResource(is); }
@Test public void constructors3() throws Exception { InputStream is = new ByteArrayInputStream( "<xxx><property name=\"key1\" value=\"val1\"/></xxx>".getBytes()); Configuration conf = new Configuration(false); ConfigurationUtils.load(conf, is); assertEquals("val1", conf.get("key1")); }
public static Schema create(Type type) { switch (type) { case STRING: return new StringSchema(); case BYTES: return new BytesSchema(); case INT: return new IntSchema(); case LONG: return new LongSchema(); case FLOAT: return new FloatSchema(); case DOUBLE: ...
@Test void doubleAsFloatDefaultValue() { Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.FLOAT), "doc", 1.0d); assertTrue(field.hasDefaultValue()); assertEquals(1.0f, field.defaultVal()); assertEquals(1.0f, GenericData.get().getDefaultValue(field)); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStart, final Range<Instant> windowEnd, final Optional<Position> position ) { try { final ReadOnlySessionStore<GenericKey, GenericRow> store = sta...
@Test public void shouldReturnValueIfSessionEndsBetweenBounds() { // Given: final Instant wstart = LOWER_INSTANT.minusMillis(5); final Instant wend = UPPER_INSTANT.minusMillis(1); givenSingleSession(wstart, wend); // When: final Iterator<WindowedRow> rowIterator = table.get(A_KEY, PAR...
@Override public Double parse(final String value) { return Double.parseDouble(value); }
@Test void assertParse() { assertThat(new PostgreSQLDoubleValueParser().parse("1"), is(1D)); }
public static Rating computeRating(@Nullable Double percent) { if (percent == null || percent >= 80.0D) { return A; } else if (percent >= 70.0D) { return B; } else if (percent >= 50.0D) { return C; } else if (percent >= 30.0D) { return D; } return E; }
@Test @UseDataProvider("values") public void compute_rating(double percent, Rating expectedRating) { assertThat(computeRating(percent)).isEqualTo(expectedRating); }
public void setTitle(CharSequence title) { TextView cta = findViewById(R.id.cta_title); cta.setText(title); }
@Test public void testSetsTheTitleFromAttribute() { Context context = ApplicationProvider.getApplicationContext(); final var rootTest = LayoutInflater.from(context).inflate(R.layout.test_search_layout, null); final AddOnStoreSearchView underTest = rootTest.findViewById(R.id.test_search_view); final T...
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR if (splittee == null || splitChar == null) { return new String[0]; } final String EMPTY_ELEMENT = ""; int spot; final int splitLength = splitChar.length(); final Stri...
@Test public void testSplitStringNullString() { Assertions.assertThrows( NullPointerException.class, () -> JOrphanUtils.split("a,bc,,", null, "?")); }
@Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processSignificantCodeFile(file, context); } }
@Test public void testExecution() throws IOException { File significantCode = new File(baseDir, "src/foo.xoo.significantCode"); FileUtils.write(significantCode, "1,1,4\n2,2,5"); context.fileSystem().add(inputFile); sensor.execute(context); assertThat(context.significantCodeTextRange("foo:src/foo...
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) { return mRxSharedPreferences.getBoolean( mResources.getString(prefKey), mResources.getBoolean(defaultValue)); }
@Test public void testConvertBottomGenericRow() { SharedPrefsHelper.setPrefsValue( "settings_key_ext_kbd_bottom_row_key", "3DFFC2AD-8BC8-47F3-962A-918156AD8DD0"); SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 10); SharedPreferences preferences = PreferenceManager.ge...
public SpeedStat getReadSpeedStat() { return mReadSpeedStat; }
@Test public void statJson() throws Exception { IOTaskResult result = new IOTaskResult(); // Reading 200MB took 1s result.addPoint(new IOTaskResult.Point(IOTaskResult.IOMode.READ, 1L, 200 * 1024 * 1024)); // Reading 196MB took 1s result.addPoint(new IOTaskResult.Point(IOTaskResult.IOMode.READ, 1L,...
public static String notEmpty(String str, String name) { if (str == null) { throw new IllegalArgumentException(name + " cannot be null"); } if (str.length() == 0) { throw new IllegalArgumentException(name + " cannot be empty"); } return str; }
@Test public void notEmptyNotEmtpy() { assertEquals(Check.notEmpty("value", "name"), "value"); }
@Override @Transactional public void updateProduct(Integer id, String title, String details) { this.productRepository.findById(id) .ifPresentOrElse(product -> { product.setTitle(title); product.setDetails(details); }, () -> { ...
@Test void updateProduct_ProductDoesNotExist_ThrowsNoSuchElementException() { // given var productId = 1; var title = "Новое название"; var details = "Новое описание"; // when assertThrows(NoSuchElementException.class, () -> this.service .updateProduc...
@Override public long extractWatermark(IcebergSourceSplit split) { return split.task().files().stream() .map( scanTask -> { Preconditions.checkArgument( scanTask.file().lowerBounds() != null && scanTask.file().lowerBounds().get(eventTimeFie...
@TestTemplate public void testTimeUnit() throws IOException { assumeThat(columnName).isEqualTo("long_column"); ColumnStatsWatermarkExtractor extractor = new ColumnStatsWatermarkExtractor(SCHEMA, columnName, TimeUnit.MICROSECONDS); assertThat(extractor.extractWatermark(split(0))) .isEqualT...
public boolean isChangeExpiryOnUpdate() { return changeExpiryOnUpdate; }
@Test public void changeExpiryOnUpdate_is_true_when_default() { State state = new State(null, null); assertTrue(state.isChangeExpiryOnUpdate()); }
public static PostgreSQLCommandPacket newInstance(final CommandPacketType commandPacketType, final PostgreSQLPacketPayload payload) { if (!OpenGaussCommandPacketType.isExtendedProtocolPacketType(commandPacketType)) { payload.getByteBuf().skipBytes(1); return getCommandPacket(commandPacke...
@Test void assertNewOpenGaussComBatchBindPacket() { when(payload.getByteBuf()).thenReturn(mock(ByteBuf.class)); assertThat(OpenGaussCommandPacketFactory.newInstance(OpenGaussCommandPacketType.BATCH_BIND_COMMAND, payload), instanceOf(PostgreSQLAggregatedCommandPacket.class)); }
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Version", getVersion()); setAttribute(protobuf...
@Test public void return_Lines_of_Codes_from_StatisticsSupport(){ when(statisticsSupport.getLinesOfCode()).thenReturn(17752L); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf,"Lines of Code", 17752L); }
public static Map<String, String> resolveMessagesForTemplate(final Locale locale, ThemeContext theme) { // Compute all the resource names we should use: *_gl_ES-gheada.properties, *_gl_ES // .properties, _gl.properties... // The order here is important: as we will let values from more s...
@Test void resolveMessagesForTemplateForDefault() throws URISyntaxException { Map<String, String> properties = ThemeMessageResolutionUtils.resolveMessagesForTemplate(Locale.CHINESE, getTheme()); assertThat(properties).hasSize(1); assertThat(properties).containsEntry("index.welcom...
@Override public void onWorkflowFinalized(Workflow workflow) { WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput()); WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow); String reason = workflow.getReasonForIncompletion(); LOG.inf...
@Test public void testWorkflowFinalizedTimedOut() { when(workflow.getStatus()).thenReturn(Workflow.WorkflowStatus.TIMED_OUT); when(instanceDao.getWorkflowInstanceStatus(eq("test-workflow-id"), anyLong(), anyLong())) .thenReturn(WorkflowInstance.Status.IN_PROGRESS); statusListener.onWorkflowFinaliz...
@Override public double sd() { return Math.sqrt(2 * nu); }
@Test public void testSd() { System.out.println("sd"); ChiSquareDistribution instance = new ChiSquareDistribution(20); instance.rand(); assertEquals(Math.sqrt(40), instance.sd(), 1E-7); }
@Override public List<LogicalSlot> peakSlotsToAllocate(SlotTracker slotTracker) { updateOptionsPeriodically(); List<LogicalSlot> slotsToAllocate = Lists.newArrayList(); int curNumAllocatedSmallSlots = numAllocatedSmallSlots; for (SlotContext slotContext : requiringSmallSlots.values...
@Test public void testSmallSlot() { QueryQueueOptions opts = QueryQueueOptions.createFromEnv(); SlotSelectionStrategyV2 strategy = new SlotSelectionStrategyV2(); SlotTracker slotTracker = new SlotTracker(ImmutableList.of(strategy)); LogicalSlot largeSlot = generateSlot(opts.v2().get...
@GetMapping("/readiness") public ResponseEntity<String> readiness(HttpServletRequest request) { ReadinessResult result = ModuleHealthCheckerHolder.getInstance().checkReadiness(); if (result.isSuccess()) { return ResponseEntity.ok().body("OK"); } return ResponseEntity.stat...
@Test void testReadinessBothFailure() { // Config and Naming are not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))) .thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); Mockito.when(serverStatusManager.getServerStatus...
@Override public VersionedKeyValueStore<K, V> build() { final KeyValueStore<Bytes, byte[]> store = storeSupplier.get(); if (!(store instanceof VersionedBytesStore)) { throw new IllegalStateException("VersionedBytesStoreSupplier.get() must return an instance of VersionedBytesStore"); ...
@Test public void shouldNotHaveChangeLoggingStoreWhenDisabled() { setUp(); final VersionedKeyValueStore<String, String> store = builder .withLoggingDisabled() .build(); assertThat(store, instanceOf(MeteredVersionedKeyValueStore.class)); final StateStore next ...
@Override public Long createSmsLog(String mobile, Long userId, Integer userType, Boolean isSend, SmsTemplateDO template, String templateContent, Map<String, Object> templateParams) { SmsLogDO.SmsLogDOBuilder logBuilder = SmsLogDO.builder(); // 根据是否要发送,设置状态 logBui...
@Test public void testCreateSmsLog() { // 准备参数 String mobile = randomString(); Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); Boolean isSend = randomBoolean(); SmsTemplateDO templateDO = randomPojo(SmsTemplateDO.class, ...
@Override public ExecuteContext after(ExecuteContext context) { // Higher versions of Properties will call the Map method to avoid duplicate entries if (MarkUtils.getMark() != null) { return context; } if (handler != null) { handler.doAfter(context); }...
@Test public void testAfter() { ExecuteContext context = ExecuteContext.forMemberMethod(mockConsumer, null, null, null, null); interceptor.after(context); KafkaConsumerWrapper wrapper = KafkaConsumerController.getKafkaConsumerCache() .get(mockConsumer.hashCode()); A...
@Override public String get(String url, String path) throws RestClientException { return get(url, path, String.class); }
@Test public void testGetWithType() throws RestClientException{ Pet pet = restClientTemplate.get("https://localhost:9991", "/v1/pets/1", Pet.class); assertTrue(pet.getId()==1); }
public void init(Collection<T> allObjectsToTest) { }
@Test @UseDataProvider("conditionCombinations") public void join_inits_all_conditions(ConditionCombination combination) { ConditionWithInitAndFinish one = someCondition("one"); ConditionWithInitAndFinish two = someCondition("two"); combination.combine(one, two).init(singleton("init")); ...
public static <T> T decodeFromByteArray(Coder<T> coder, byte[] encodedValue) throws CoderException { return decodeFromByteArray(coder, encodedValue, Coder.Context.OUTER); }
@Test public void testClosingCoderFailsWhenDecodingByteArray() throws Exception { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Caller does not own the underlying"); CoderUtils.decodeFromByteArray(new ClosingCoder(), new byte[0]); }
@Override @MethodNotAvailable public CompletionStage<Void> setAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testSetAsyncWithExpiryPolicy() { ExpiryPolicy expiryPolicy = new HazelcastExpiryPolicy(1, 1, 1, TimeUnit.MILLISECONDS); adapter.setAsync(42, "value", expiryPolicy); }
@Override public QuoteCharacter getQuoteCharacter() { return QuoteCharacter.QUOTE; }
@Test void assertGetQuoteCharacter() { assertThat(dialectDatabaseMetaData.getQuoteCharacter(), is(QuoteCharacter.QUOTE)); }
@Override public Headers headers() { if (recordContext == null) { // This is only exposed via the deprecated ProcessorContext, // in which case, we're preserving the pre-existing behavior // of returning dummy values when the record context is undefined. // Fo...
@Test public void shouldReturnHeadersFromRecordContext() { assertThat(context.headers(), equalTo(recordContext.headers())); }
@Override public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff) throws IOException, InterruptedException { IOException lastException = null; do { try { // Match inputPath which may contains glob Collection<Metadata> files = Iterables.getOnlyElement...
@Test public void testReadWithRetriesFailsWhenTemplateIncorrect() throws Exception { File tmpFile = tmpFolder.newFile(); Files.asCharSink(tmpFile, StandardCharsets.UTF_8).write("Test for file checksum verifier."); NumberedShardedFile shardedFile = new NumberedShardedFile(filePattern, Pattern.comp...
public static boolean isFloatingNumber(String text) { final int startPos = findStartPosition(text); if (startPos < 0) { return false; } boolean dots = false; for (int i = startPos; i < text.length(); i++) { char ch = text.charAt(i); if (!Chara...
@Test @DisplayName("Tests that isFloatingNumber returns true for integers") void isFloatingNumberIntegers() { assertTrue(ObjectHelper.isFloatingNumber("1234")); assertTrue(ObjectHelper.isFloatingNumber("-1234")); assertTrue(ObjectHelper.isFloatingNumber("1")); assertTrue(ObjectHe...
public static JobIndexInfo getIndexInfo(String jhFileName) throws IOException { String fileName = jhFileName.substring(0, jhFileName.indexOf(JobHistoryUtils.JOB_HISTORY_FILE_EXTENSION)); JobIndexInfo indexInfo = new JobIndexInfo(); String[] jobDetails = fileName.split(DELIMITER); JobID o...
@Test public void testUserNamePercentDecoding() throws IOException { String jobHistoryFile = String.format(JOB_HISTORY_FILE_FORMATTER, JOB_ID, SUBMIT_TIME, USER_NAME_WITH_DELIMITER_ESCAPE, JOB_NAME, FINISH_TIME, NUM_MAPS, NUM_REDUCES, JOB_STATUS, ...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_display_statistics_for_non_select_statement() { // Given String query = "USE zeppelin;\nCREATE TABLE IF NOT EXISTS no_select(id int PRIMARY KEY);"; final String rawResult = reformatHtml(readTestResource( "/scalate/NoResultWithExecutionInfo.html")); // When final Interpre...
public Schema getSchema() { return context.getSchema(); }
@Test public void testEnumSchema() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(EnumMessage.getDescriptor()); Schema schema = schemaProvider.getSchema(); assertEquals(ENUM_SCHEMA, schema); }
public List<Pipeline> parsePipelines(String pipelines) throws ParseException { final ParseContext parseContext = new ParseContext(false); final SyntaxErrorListener errorListener = new SyntaxErrorListener(parseContext); final RuleLangLexer lexer = new RuleLangLexer(new ANTLRInputStream(pipelines...
@Test void pipelineDeclaration() throws Exception { final List<Pipeline> pipelines = parser.parsePipelines(ruleForTest()); assertEquals(1, pipelines.size()); final Pipeline pipeline = Iterables.getOnlyElement(pipelines); assertEquals("cisco", pipeline.name()); assertEquals(2,...
public UiTopoLayout parent(UiTopoLayoutId parentId) { if (isRoot()) { throw new IllegalArgumentException(E_ROOT_PARENT); } // TODO: consider checking ancestry chain to prevent loops parent = parentId; return this; }
@Test public void setParentOnOther() { mkOtherLayout(); layout.parent(OTHER_ID); assertEquals("wrong parent", OTHER_ID, layout.parent()); layout.parent(null); assertEquals("non-null parent", null, layout.parent()); }
String filenameValidatorForInputFiles( String filename ) { Repository rep = getTransMeta().getRepository(); if ( rep != null && rep.isConnected() && filename .contains( Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY ) ) { return environmentSubstitute( filename.replace( Const.INTERNAL_VARIABLE_ENTRY...
@Test public void testFilenameValidatorForInputFilesConnectedToRep() { CsvInput csvInput = mock( CsvInput.class ); String internalEntryVariable = "internalEntryVariable"; String internalTransformationVariable = "internalTransformationVariable"; String filename = Const.INTERNAL_VARIABLE_ENTRY_CURRENT...
private List<Class<?>> scanForClassesInPackage(String packageName, Predicate<Class<?>> classFilter) { requireValidPackageName(packageName); requireNonNull(classFilter, "classFilter must not be null"); List<URI> rootUris = getUrisForPackage(getClassLoader(), packageName); return findClass...
@Test void scanForClassesInNonExistingPackage() { List<Class<?>> classes = scanner.scanForClassesInPackage("io.cucumber.core.resource.does.not.exist"); assertThat(classes, empty()); }
@Override public Path find() throws BackgroundException { return new MantaAccountHomeInfo(host.getCredentials().getUsername(), host.getDefaultPath()).getNormalizedHomePath(); }
@Test public void testHomeFeature() throws BackgroundException { final Path drive = new MantaHomeFinderFeature(session.getHost()).find(); assertNotNull(drive); assertFalse(drive.isRoot()); assertTrue(drive.isPlaceholder()); assertNotEquals("null", drive.getName()); as...
@Override // FsDatasetSpi public ReplicaHandler append(ExtendedBlock b, long newGS, long expectedBlockLen) throws IOException { try (AutoCloseableLock lock = lockManager.writeLock(LockLevel.VOLUME, b.getBlockPoolId(), getStorageUuidForLock(b))) { // If the block was successfully finalized bec...
@Test(timeout = 30000) public void testAppend() { MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(1) .storageTypes(new StorageType[]{StorageType.DISK, StorageType.DISK}) .storagesPerDatanode(2) .build(); FileSyst...
public static String capitaliseFirstLetter(String string) { if (string == null || string.length() == 0) { return string; } else { return string.substring(0, 1).toUpperCase() + string.substring(1); } }
@Test public void testCapitaliseFirstLetter() { assertEquals(capitaliseFirstLetter(""), ("")); assertEquals(capitaliseFirstLetter("a"), ("A")); assertEquals(capitaliseFirstLetter("aa"), ("Aa")); assertEquals(capitaliseFirstLetter("A"), ("A")); assertEquals(capitaliseFirstLett...
public boolean isSevere() { return severe; }
@Test public void testIsSevere() throws Exception { assertTrue( exception.isSevere() ); }
public static DocumentBuilderFactory newSecureDocumentBuilderFactory() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setFeature(DISALLOW_DOCTYPE_DECL, true); dbf.setFeat...
@Test public void testSecureDocumentBuilderFactory() throws Exception { DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader("<root/>"))); Assertions.assertThat(doc).describedAs("parsed document").isNotNull(); }
@VisibleForTesting ZonedDateTime parseZoned(final String text, final ZoneId zoneId) { final TemporalAccessor parsed = formatter.parse(text); final ZoneId parsedZone = parsed.query(TemporalQueries.zone()); ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply( ObjectUtils.defaultIfNull(parsedZone...
@Test public void shouldResolveDefaultsForDayOfYear() { // Given final String format = "DDD"; final String timestamp = "100"; // When final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID); // Then assertThat(ts, is(sameInstant(EPOCH.withDayOfYear(100).wi...