focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() { return new UnbindChangeProcessor(); }
@Test public void leftJoinShouldPropagateNewPrimaryKeyWithNonNullFK() { final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>(); leftJoinProcessor.init(context); context.setRecordMetadata("topic", 0, 0); final Left...
@Override public boolean isTypeOf(Class<?> type) { checkNotNull(type); return id.isTypeOf(type); }
@Test public void testTypeOf() { DiscreteResource discrete = Resources.discrete(D1, P1, VLAN1).resource(); assertThat(discrete.isTypeOf(DeviceId.class), is(false)); assertThat(discrete.isTypeOf(PortNumber.class), is(false)); assertThat(discrete.isTypeOf(VlanId.class), is(true)); ...
@Override public boolean tryStartNewSegment( TieredStorageSubpartitionId subpartitionId, int segmentId, int minNumBuffers) { File filePath = dataFilePath.toFile(); boolean canStartNewSegment = filePath.getUsableSpace() - (long) Math.max(num...
@Test void testStartNewSegmentSuccess() throws IOException { String partitionFile = TempDirUtils.newFile(tempFolder, "test").toString(); File testFile = new File(partitionFile + DATA_FILE_SUFFIX); assertThat(testFile.createNewFile()).isTrue(); try (DiskTierProducerAgent diskTierProdu...
@Override public void configure(ResourceGroup group, SelectionContext<VariableMap> context) { Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry = getMatchingSpec(group, context); configureGroup(group, entry.getValue()); }
@Test public void testExtractVariableConfiguration() throws IOException { ResourceGroupConfigurationManager<VariableMap> manager = parse("resource_groups_config_extract_variable.json"); VariableMap variableMap = new VariableMap(ImmutableMap.of("USER", "user", "domain", "prestodb", "region", "us...
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.w...
@Test public void testMoveFile() throws Exception { final Path home = new DefaultHomeFinderService(session).find(); final Path file = new DropboxTouchFeature(session).touch(new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); asse...
public static AclOperation getDeniedOperation(final String errorMessage) { final Matcher matcher = DENIED_OPERATION_STRING_PATTERN.matcher(errorMessage); if (matcher.matches()) { return AclOperation.fromString(matcher.group(1)); } else { return AclOperation.UNKNOWN; } }
@Test public void shouldReturnKnownDeniedOperationFromValidAuthorizationMessage() { // When: final AclOperation operation = SchemaRegistryUtil.getDeniedOperation( "User is denied operation Write on Subject: t2-value; error code: 40301"); // Then: assertThat(operation, is(AclOperation.WRITE));...
public static Combine.BinaryCombineDoubleFn ofDoubles() { return new Max.MaxDoubleFn(); }
@Test public void testMaxDoubleFn() { testCombineFn(Max.ofDoubles(), Lists.newArrayList(1.0, 2.0, 3.0, 4.0), 4.0); }
public static Read<JmsRecord> read() { return new AutoValue_JmsIO_Read.Builder<JmsRecord>() .setMaxNumRecords(Long.MAX_VALUE) .setCoder(SerializableCoder.of(JmsRecord.class)) .setCloseTimeout(DEFAULT_CLOSE_TIMEOUT) .setRequiresDeduping(false) .setMessageMapper( ne...
@Test public void testSplitForQueue() throws Exception { JmsIO.Read read = JmsIO.read().withQueue(QUEUE); PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); int desiredNumSplits = 5; JmsIO.UnboundedJmsSource initialSource = new JmsIO.UnboundedJmsSource(read); List<JmsIO.UnboundedJm...
public static LogicalSchema buildSchema( final LogicalSchema sourceSchema, final List<Expression> partitionBys, final FunctionRegistry functionRegistry ) { final List<PartitionByColumn> partitionByCols = getPartitionByColumnName(sourceSchema, partitionBys); return buildSchema(source...
@Test public void shouldThrowIfPartitioningByMultipleExpressionsIncludingNull() { // Given: final List<Expression> partitionBy = ImmutableList.of( new UnqualifiedColumnReferenceExp(COL1), new NullLiteral() ); // Expect / When: final Exception e = assertThrows( KsqlExceptio...
@Override public void disconnectResourceManager( final ResourceManagerId resourceManagerId, final Exception cause) { if (isConnectingToResourceManager(resourceManagerId)) { reconnectToResourceManager(cause); } }
@Test void testReconnectionAfterDisconnect() throws Exception { try (final JobMaster jobMaster = new JobMasterBuilder(jobGraph, rpcService) .withJobMasterId(jobMasterId) .withConfiguration(configuration) .withHighAvailab...
public boolean shouldLog(final Logger logger, final String path, final int responseCode) { if (rateLimitersByPath.containsKey(path)) { final RateLimiter rateLimiter = rateLimitersByPath.get(path); if (!rateLimiter.tryAcquire()) { if (pathLimitHit.tryAcquire()) { logger.info("Hit rate l...
@Test public void shouldLog() { // When: assertThat(loggingRateLimiter.shouldLog(logger, PATH, 200), is(true)); // Then: verify(rateLimiter).tryAcquire(); verify(logger, never()).info(any()); }
public B sticky(Boolean sticky) { this.sticky = sticky; return getThis(); }
@Test void sticky() { ReferenceBuilder builder = new ReferenceBuilder(); builder.sticky(true); Assertions.assertTrue(builder.build().getSticky()); builder.sticky(false); Assertions.assertFalse(builder.build().getSticky()); }
public static <K, V> Read<K, V> read() { return new AutoValue_KafkaIO_Read.Builder<K, V>() .setTopics(new ArrayList<>()) .setTopicPartitions(new ArrayList<>()) .setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN) .setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES) ...
@Test public void testDeserializationWithHeaders() throws Exception { // To assert that we continue to prefer the Deserializer API with headers in Kafka API 2.1.0 // onwards int numElements = 1000; String topic = "my_topic"; KafkaIO.Read<Integer, Long> reader = KafkaIO.<Integer, Long>read...
public static boolean isDone( Map<String, StepTransition> runtimeDag, Map<String, Boolean> idStatusMap, RestartConfig restartConfig) { Map<String, Set<String>> parentMap = new HashMap<>(); Map<String, Set<String>> childMap = new HashMap<>(); Deque<String> deque = prepareDagForTrav...
@Test public void testRestartIncomplete() { Map<String, Boolean> idStatusMap = new LinkedHashMap<>(); idStatusMap.put("job_3", Boolean.FALSE); idStatusMap.put("job_9", Boolean.TRUE); Assert.assertFalse( DagHelper.isDone( runtimeDag1, idStatusMap, RestartConf...
protected static TransferItem resolve(final Path remote, final Local local, final boolean append) { if(local.isDirectory()) { // Local path resolves to folder if(remote.isDirectory()) { if(append) { return new TransferItem(new Path(remote, local.getNam...
@Test public void testResolveFileToFile() { final Local temp = new FlatTemporaryFileService().create(new AlphanumericRandomStringService().random()); final Path file = new Path("/f", EnumSet.of(Path.Type.file)); final TransferItem item = UploadTransferItemFinder.resolve(file, temp, false); ...
@Override protected final CompletableFuture<MetricCollectionResponseBody> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { metricFetcher.update(); final MetricStore.ComponentMetricStore component...
@Test void testReturnEmptyListIfNoComponentMetricStore() throws Exception { testMetricsHandler.returnComponentMetricStore = false; final CompletableFuture<MetricCollectionResponseBody> completableFuture = testMetricsHandler.handleRequest( HandlerRequest.creat...
public static boolean objectContainsFieldOrProperty(Object object, String fieldName) { if (object == null) return false; return objectContainsField(object, fieldName) || objectContainsProperty(object, fieldName); }
@Test void testObjectContainsFieldOrProperty() { final TestObject test = new TestObject("test"); assertThat(objectContainsFieldOrProperty(test, "field")).isTrue(); assertThat(objectContainsFieldOrProperty(test, "anotherField")).isTrue(); assertThat(objectContainsFieldOrProperty(test...
@Override public void run() { if (!redoService.isConnected()) { LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task"); return; } try { redoForInstances(); redoForSubscribes(); } catch (Exception e) { ...
@Test void testRunRedoDeregisterInstance() throws NacosException { Set<InstanceRedoData> mockData = generateMockInstanceData(true, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy).doDeregisterService(SERVICE, GROUP, INST...
@Override public void open(Configuration parameters) throws Exception { this.rateLimiterTriggeredCounter = getRuntimeContext() .getMetricGroup() .addGroup( TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT) .counter(TableMain...
@Test void testDataFileCount() throws Exception { TriggerManager manager = manager( sql.tableLoader(TABLE_NAME), new TriggerEvaluator.Builder().dataFileCount(3).build()); try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness = harness(manager)) { ...
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = false; boolean containsNull = false; // Spec. definiti...
@Test void invokeArrayParamTypeHeterogenousArray() { FunctionTestUtil.assertResultError(anyFunction.invoke(new Object[]{Boolean.FALSE, 1}), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(anyFunction.invoke(new Object[]{Boolean.TRUE, 1}), ...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TableMeta)) { return false; } TableMeta tableMeta = (TableMeta) o; if (!Objects.equals(tableMeta.tableName, this.tableName)) { return fal...
@Test public void testEquals() { assertTrue(tableMeta.equals(tableMeta2)); tableMeta2.setTableName("different_table"); assertFalse(tableMeta.equals(tableMeta2)); }
@Override public T deserialize(final String topicName, final byte[] record) { return deserializer.get().deserialize(topicName, record); }
@Test public void shouldUseAThreadLocalDeserializer() throws InterruptedException { final List<Deserializer<GenericRow>> serializers = new LinkedList<>(); final ThreadLocalDeserializer<GenericRow> serializer = new ThreadLocalDeserializer<>( () -> { final Deserializer<GenericRow> local = moc...
public static List<Object> getObjects() { FS.FileStoreAttributes.setBackground(true); return Arrays.asList( JGitBlameCommand.class, CompositeBlameCommand.class, NativeGitBlameCommand.class, DefaultBlameStrategy.class, ProcessWrapperFactory.class, GitScmProvider.class, G...
@Test public void getClasses() { assertThat(GitScmSupport.getObjects()).isNotEmpty(); }
public void init(ApplicationConfiguration applicationConfiguration) throws ModuleNotFoundException, ProviderNotFoundException, ServiceNotProvidedException, CycleDependencyException, ModuleConfigException, ModuleStartException { String[] moduleNames = applicationConfiguration.moduleList(); ...
@Test public void testModuleMissing() { assertThrows(ModuleNotFoundException.class, () -> { ApplicationConfiguration configuration = new ApplicationConfiguration(); configuration.addModule("BaseA").addProviderConfiguration("P-A", new Properties()); configuration.addModule...
public AlarmCallback create(AlarmCallbackConfiguration configuration) throws ClassNotFoundException, AlarmCallbackConfigurationException { AlarmCallback alarmCallback = create(configuration.getType()); alarmCallback.initialize(new Configuration(configuration.getConfiguration())); return alarmCa...
@Test public void testCreateByClass() throws Exception { AlarmCallback alarmCallback = alarmCallbackFactory.create(DummyAlarmCallback.class); assertTrue(alarmCallback instanceof DummyAlarmCallback); assertEquals(dummyAlarmCallback, alarmCallback); }
SqlResult execute(CreateMappingPlan plan, SqlSecurityContext ssc) { catalog.createMapping(plan.mapping(), plan.replace(), plan.ifNotExists(), ssc); return UpdateSqlResultImpl.createUpdateCountResult(0); }
@Test @Parameters({ "true", "false" }) public void test_dropMappingExecution(boolean ifExists) { // given String name = "name"; DropMappingPlan plan = new DropMappingPlan(planKey(), name, ifExists, planExecutor); // when SqlResult result = pla...
public ModuleBuilder owner(String owner) { this.owner = owner; return getThis(); }
@Test void owner() { ModuleBuilder builder = ModuleBuilder.newBuilder(); builder.owner("owner"); Assertions.assertEquals("owner", builder.build().getOwner()); }
@Override protected boolean isSelectable(InstancesChangeEvent event) { return event != null && event.getHosts() != null && event.getInstancesDiff() != null; }
@Test public void testSelectable() { NamingSelectorWrapper selectorWrapper = new NamingSelectorWrapper(null, null); assertFalse(selectorWrapper.isSelectable(null)); InstancesChangeEvent event1 = new InstancesChangeEvent(null, null, null, null, null, null); assertFalse(selectorWrapper...
public static FileSystem write(final FileSystem fs, final Path path, final byte[] bytes) throws IOException { Objects.requireNonNull(path); Objects.requireNonNull(bytes); try (FSDataOutputStream out = fs.createFile(path).overwrite(true).build()) { out.write(bytes); } return fs; }
@Test public void testWriteStringNoCharSetFileSystem() throws IOException { URI uri = tmp.toURI(); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(uri, conf); Path testPath = new Path(new Path(uri), "writestring.out"); String write = "A" + "\u00ea" + "\u00f1" + "\u00fc" +...
private PolicerId(URI u) { super(u.toString()); uri = u; }
@Test public void testEquality() { // Create URI representing the id one URI uriOne = URI.create(OF_SCHEME + ":" + Integer.toHexString(ONE)); // Create String representing the id one String stringOne = OF_SCHEME + ":" + Integer.toHexString(ONE); // Create String representing ...
public static ByteBuf newTxnAbortMarker(long sequenceId, long txnMostBits, long txnLeastBits) { return newTxnMarker( MarkerType.TXN_ABORT, sequenceId, txnMostBits, txnLeastBits); }
@Test public void testTxnAbortMarker() throws IOException { long sequenceId = 1L; long mostBits = 1234L; long leastBits = 2345L; ByteBuf buf = Markers.newTxnAbortMarker(sequenceId, mostBits, leastBits); MessageMetadata msgMetadata = Commands.parseMessageMetadata(buf); ...
public Map<String, LdapUserMapping> getUserMappings() { if (userMappings == null) { createUserMappings(); } return userMappings; }
@Test public void getUserMappings_shouldCreateUserMappings_whenSingleLdapConfig() { Configuration configuration = generateSingleLdapSettingsWithUserAndGroupMapping().asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); Map<String, LdapUserMapping> result = settingsMan...
public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
@Test public void testHexDump() { assertEquals("", ByteBufUtil.hexDump(EMPTY_BUFFER)); ByteBuf buffer = wrappedBuffer(new byte[]{ 0x12, 0x34, 0x56 }); assertEquals("123456", ByteBufUtil.hexDump(buffer)); buffer.release(); buffer = wrappedBuffer(new byte[]{ 0...
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; ...
@Test public void decodeFailsWithBlankMessage() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"example.org\"," + "\"message\": \" \"" + "}"; final RawMessage rawMessage = new RawMessage(json.get...
public void process() { LOGGER.debug("Beginning Composer lock processing"); try { final JsonObject composer = jsonReader.readObject(); if (composer.containsKey("packages")) { LOGGER.debug("Found packages"); final JsonArray packages = composer.getJs...
@Test(expected = ComposerException.class) public void testNotComposer() throws Exception { String input = "[\"ham\",\"eggs\"]"; ComposerLockParser clp = new ComposerLockParser(new ByteArrayInputStream(input.getBytes(Charset.defaultCharset()))); clp.process(); }
public static String processingLogStreamCreateStatement( final ProcessingLogConfig config, final KsqlConfig ksqlConfig ) { return processingLogStreamCreateStatement( config.getString(ProcessingLogConfig.STREAM_NAME), getTopicName(config, ksqlConfig) ); }
@Test public void shouldBuildCorrectStreamCreateDDL() { // Given: serviceContext.getTopicClient().createTopic(TOPIC, 1, (short) 1); // When: final String statement = ProcessingLogServerUtils.processingLogStreamCreateStatement( config, ksqlConfig); // Then: ass...
public static Stream<Vertex> reverseDepthFirst(Graph g) { return reverseDepthFirst(g.getLeaves()); }
@Test public void testDFSReverse() { DepthFirst.reverseDepthFirst(g).forEach(v -> visitCount.incrementAndGet()); assertEquals("It should visit each node once", visitCount.get(), 3); }
Future<Boolean> canRoll(int podId) { LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId); return canRollBroker(descriptions, podId); }
@Test public void testNoMinIsr(VertxTestContext context) { KSB ksb = new KSB() .addNewTopic("A", false) .addNewPartition(0) .replicaOn(0, 1, 2) .leader(0) .isr(0, 1, 2) .endPartiti...
@Override public void register(PiPipeconf pipeconf) throws IllegalStateException { checkNotNull(pipeconf); if (pipeconfs.containsKey(pipeconf.id())) { throw new IllegalStateException(format("Pipeconf %s is already registered", pipeconf.id())); } pipeconfs.put(pipeconf.id(...
@Test public void register() { mgr.register(pipeconf); assertTrue("PiPipeconf should be registered", mgr.pipeconfs.containsValue(pipeconf)); }
@Override public List<TableInfo> getTableList(Long dataSourceConfigId, String nameLike, String commentLike) { List<TableInfo> tables = getTableList0(dataSourceConfigId, null); return tables.stream().filter(tableInfo -> (StrUtil.isEmpty(nameLike) || tableInfo.getName().contains(nameLike)) ...
@Test public void testGetTableList() { // 准备参数 Long dataSourceConfigId = randomLongId(); // mock 方法 DataSourceConfigDO dataSourceConfig = new DataSourceConfigDO().setUsername("sa").setPassword("") .setUrl("jdbc:h2:mem:testdb"); when(dataSourceConfigService.get...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 1) { if ("dateIntToTs".equals(methodName)) { return dateIntToTs(args[0]); } else if ("tsToDateInt".equals(methodName)) { return tsToDateInt(args[0]); } } else if (args.length == 2) { i...
@Test(expected = NumberFormatException.class) public void testCallTsToDateIntInvalid() { SelUtilFunc.INSTANCE.call("tsToDateInt", new SelType[] {SelString.of("123.45")}); }
public synchronized boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleStepException { meta = (ShapeFileReaderMeta) smi; data = (ShapeFileReaderData) sdi; int partnr; boolean retval = true; if ( data.shapeNr >= data.shapeFile.getNrShapes() ) { setOutputDone(); ...
@Test public void processRowPolyLineCloneRowTest() throws KettleException { shapePoint = mock( ShapePoint.class ); shapePoint.x = 0; shapePoint.y = 0; shapePolyLine = mock( ShapePolyLine.class ); shapePolyLine.nrparts = 0; shapePolyLine.nrpoints = 1; shapePolyLine.point = new ShapePoint[]...
public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry>...
@Test public void testFilterAclEntriesByAclSpecDefaultMaskPreserved() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", READ)) .add(aclEntry(ACCESS, USER, "diana", READ_WRITE)) ...
@Override public Long createDataSourceConfig(DataSourceConfigSaveReqVO createReqVO) { DataSourceConfigDO config = BeanUtils.toBean(createReqVO, DataSourceConfigDO.class); validateConnectionOK(config); // 插入 dataSourceConfigMapper.insert(config); // 返回 return config.g...
@Test public void testCreateDataSourceConfig_success() { try (MockedStatic<JdbcUtils> databaseUtilsMock = mockStatic(JdbcUtils.class)) { // 准备参数 DataSourceConfigSaveReqVO reqVO = randomPojo(DataSourceConfigSaveReqVO.class) .setId(null); // 避免 id 被设置 //...
public File dumpHeap() throws MalformedObjectNameException, InstanceNotFoundException, ReflectionException, MBeanException, IOException { return dumpHeap(localDumpFolder); }
@Test public void heapDumpOnce() throws Exception { File folder = tempFolder.newFolder(); File dump1 = MemoryMonitor.dumpHeap(folder); assertNotNull(dump1); assertTrue(dump1.exists()); assertThat(dump1.getParentFile(), Matchers.equalTo(folder)); }
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowStatement) { return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s...
@Test void assertCreateWithSelectDatabase() { SQLStatement sqlStatement = parseSQL(PSQL_SELECT_DATABASES); SelectStatementContext selectStatementContext = mock(SelectStatementContext.class); when(selectStatementContext.getSqlStatement()).thenReturn((SelectStatement) sqlStatement); Op...
public abstract VoiceInstructionValue getConfigForDistance( double distance, String turnDescription, String thenVoiceInstruction);
@Test public void fixedDistanceInitialVICImperialTest() { FixedDistanceVoiceInstructionConfig configImperial = new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_PLURAL.imperial, trMap, locale, 2000, 2); compareVoiceInstructionValues( 2000, "I...
public static CompositeData parseComposite(URI uri) throws URISyntaxException { CompositeData rc = new CompositeData(); rc.scheme = uri.getScheme(); String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); parseComposite(uri, rc, ssp); rc.fragment = uri.ge...
@Test public void testCompositePath() throws Exception { CompositeData data = URISupport.parseComposite(new URI("test:(path)/path")); assertEquals("path", data.getPath()); data = URISupport.parseComposite(new URI("test:path")); assertNull(data.getPath()); }
@Override public ChannelFuture resetStream(final ChannelHandlerContext ctx, int streamId, long errorCode, ChannelPromise promise) { final Http2Stream stream = connection().stream(streamId); if (stream == null) { return resetUnknownStream(ctx, streamId...
@Test public void writeRstOnClosedStreamShouldSucceed() throws Exception { handler = newHandler(); when(stream.id()).thenReturn(STREAM_ID); when(frameWriter.writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class))).thenReturn(future); when(stream.s...
public static <E> List<E> ensureImmutable(List<E> list) { if (list.isEmpty()) return Collections.emptyList(); // Faster to make a copy than check the type to see if it is already a singleton list if (list.size() == 1) return Collections.singletonList(list.get(0)); if (isImmutable(list)) return list; ...
@Test void ensureImmutable_doesntCopyImmutableList() { List<Object> list = ImmutableList.of("foo", "bar"); assertThat(Lists.ensureImmutable(list)) .isSameAs(list); }
public static <T> Collector<T, ?, Optional<T>> singleton() { return Collectors.collectingAndThen( Collectors.toList(), list -> { if (list.size() > 1) throw new IllegalArgumentException("More than one element"); return list.stream().findAny(...
@Test public void collector_returns_singleton() { List<String> items = List.of("foo1", "bar", "foo2"); Optional<String> bar = items.stream().filter(s -> s.startsWith("bar")).collect(CustomCollectors.singleton()); assertEquals(Optional.of("bar"), bar); }
boolean publishVersion() { try { TxnInfoPB txnInfo = new TxnInfoPB(); txnInfo.txnId = watershedTxnId; txnInfo.combinedTxnLog = false; txnInfo.txnType = TxnTypePB.TXN_NORMAL; txnInfo.commitTime = finishedTimeMs / 1000; for (long partitionId ...
@Test public void testPublishVersion() throws AlterCancelException { new MockUp<Utils>() { @Mock public void publishVersion(@NotNull List<Tablet> tablets, TxnInfoPB txnInfo, long baseVersion, long newVersion, long warehouseId) ...
static Map<String, Comparable> prepareProperties(Map<String, Comparable> properties, Collection<PropertyDefinition> propertyDefinitions) { Map<String, Comparable> mappedProperties = createHashMap(propertyDefinitions.size()); for (PropertyDefinition p...
@Test(expected = InvalidConfigurationException.class) public void unsatisfiedRequiredProperty() { // given Map<String, Comparable> properties = emptyMap(); Collection<PropertyDefinition> propertyDefinitions = singletonList(PROPERTY_DEFINITION_1); // when prepareProperties(pr...
public static Logger logger(Class<?> clazz) { return getLogger(clazz); }
@Test void testLogger() { Logger logger = LogUtils.logger(LogUtilsTest.class); assertNotNull(logger); }
@Override public void upgrade() { if (clusterConfigService.get(V20161216123500_Succeeded.class) != null) { return; } // The default index set must have been created first. checkState(clusterConfigService.get(DefaultIndexSetCreated.class) != null, "The default index set h...
@Test public void migrationDoesNotRunAgainIfMigrationWasSuccessfulBefore() { when(clusterConfigService.get(V20161216123500_Succeeded.class)).thenReturn(V20161216123500_Succeeded.create()); migration.upgrade(); verify(clusterConfigService).get(V20161216123500_Succeeded.class); verify...
public static void deleteIfExists(final File file) { try { Files.deleteIfExists(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
@Test void deleteIfExistsEmptyDirectory() throws IOException { final Path dir = tempDir.resolve("dir"); Files.createDirectory(dir); IoUtil.deleteIfExists(dir.toFile()); assertFalse(Files.exists(dir)); }
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void maintenance_nodes_in_downed_group_are_not_affected() { final ClusterFixture fixture = ClusterFixture .forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3)) .bringEntireClusterUp() .proposeStorageNodeWantedState(3, State.MAINTE...
@Override public CompletableFuture<Collection<PartitionWithMetrics>> getPartitionWithMetrics( Duration timeout, Set<ResultPartitionID> expectedPartitions) { this.partitionsToFetch = expectedPartitions; this.fetchPartitionsFuture = new CompletableFuture<>(); // check already fetc...
@Test void testGetPartitionWithMetrics() throws Exception { JobVertex jobVertex = new JobVertex("jobVertex"); jobVertex.setInvokableClass(NoOpInvokable.class); jobVertex.setParallelism(1); final JobGraph jobGraph = JobGraphTestUtils.batchJobGraph(jobVertex); try (final JobMa...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PiAction piAction = (PiAction) o; return Objects.equal(actionId, piAction.actionId) && Ob...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(piAction1, sameAsPiAction1) .addEqualityGroup(piAction2) .testEquals(); }
public List<TimerangePreset> convert(final Map<Period, String> timerangeOptions) { if (timerangeOptions == null) { return List.of(); } return timerangeOptions.entrySet() .stream() .map(entry -> new TimerangePreset( periodConvert...
@Test void testConversionReturnsEmptyListOnEmptyInput() { assertThat(toTest.convert(Map.of())).isEmpty(); }
@Override public Option<IndexedRecord> combineAndGetUpdateValue(IndexedRecord currentValue, Schema schema, Properties properties) throws IOException { // Specific to Postgres: If the updated record has TOASTED columns, // we will need to keep the previous value for those columns // see https://debezium.io...
@Test public void testMergeWithUpdate() throws IOException { GenericRecord updateRecord = createRecord(1, Operation.UPDATE, 100L); PostgresDebeziumAvroPayload payload = new PostgresDebeziumAvroPayload(updateRecord, 100L); GenericRecord existingRecord = createRecord(1, Operation.INSERT, 99L); Option<I...
@Override public WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(Integer userType, String phoneCode) { WxMaService service = getWxMaService(userType); try { return service.getUserService().getPhoneNoInfo(phoneCode); } catch (WxErrorException e) { log.error("[getPhoneNoInfo...
@Test public void testGetWxMaPhoneNumberInfo_success() throws WxErrorException { // 准备参数 Integer userType = randomPojo(UserTypeEnum.class).getValue(); String phoneCode = randomString(); // mock 方法 WxMaUserService userService = mock(WxMaUserService.class); when(wxMaSer...
public int read(final MessageHandler handler) { return read(handler, Integer.MAX_VALUE); }
@Test void shouldCopeWithExceptionFromHandler() { final int msgLength = 16; final int recordLength = HEADER_LENGTH + msgLength; final int alignedRecordLength = align(recordLength, ALIGNMENT); final long tail = alignedRecordLength * 2L; final long head = 0L; final ...
@Override public void runCheck() throws PreflightCheckException { checkDatanodeLock(directories.getConfigurationTargetDir()); checkDatanodeLock(directories.getLogsTargetDir()); }
@Test void testLockCreation(@TempDir Path dataDir, @TempDir Path logsDir, @TempDir Path configDir) throws IOException { final Path logsDirLock = logsDir.resolve(DatanodeDirectoriesLockfileCheck.DATANODE_LOCKFILE); final Path configDirLock = config...
public static FieldScope all() { return FieldScopeImpl.all(); }
@Test public void testFieldScopes_all() { Message message = parse("o_int: 3 r_string: \"foo\""); Message diffMessage = parse("o_int: 5 r_string: \"bar\""); expectThat(diffMessage).withPartialScope(FieldScopes.all()).isNotEqualTo(message); expectThat(diffMessage).ignoringFieldScope(FieldScopes.all())....
public LoadCompConf scaleParallel(double v) { return setParallel(Math.max(1, (int) Math.ceil(parallelism * v))); }
@Test public void scaleParallel() { LoadCompConf orig = new LoadCompConf.Builder() .withId("SOME_SPOUT") .withParallelism(1) .withStream(new OutputStream("default", new NormalDistStats(500.0, 100.0, 300.0, 600.0), false)) .build(); assertEquals(500.0, ...
@Override public void createOrUpdate(final String path, final Object data) { zkClient.createOrUpdate(path, data, CreateMode.PERSISTENT); }
@Test public void testOnRuleChangedCreate() { RuleData ruleData = RuleData.builder() .id(MOCK_ID) .name(MOCK_NAME) .pluginName(MOCK_PLUGIN_NAME) .selectorId(MOCK_SELECTOR_ID) .build(); String ruleRealPath = DefaultPathCo...
public static <T> T loadWithSecrets(Map<String, Object> map, Class<T> clazz, SourceContext sourceContext) { return loadWithSecrets(map, clazz, secretName -> sourceContext.getSecret(secretName)); }
@Test public void testSinkLoadWithSecrets() { Map<String, Object> configMap = new HashMap<>(); configMap.put("notSensitive", "foo"); TestConfig testConfig = IOConfigUtils.loadWithSecrets(configMap, TestConfig.class, new TestSinkContext()); Assert.assertEquals(testConfig.notSensitiv...
@SuppressWarnings("unchecked") public static <E extends Enum<E>> EnumSet<E> parseEnumSet(final String key, final String valueString, final Class<E> enumClass, final boolean ignoreUnknown) throws IllegalArgumentException { // build a map of lower case string to enum values. final Map<String,...
@Test public void testUnknownEnumNotIgnored() throws Throwable { intercept(IllegalArgumentException.class, "unrecognized", () -> parseEnumSet("key", "c, unrecognized", SimpleEnum.class, false)); }
@Override public void open(Map<String, Object> config, SinkContext ctx) throws Exception { kafkaSinkConfig = PulsarKafkaConnectSinkConfig.load(config); Objects.requireNonNull(kafkaSinkConfig.getTopic(), "Kafka topic is not set"); Preconditions.checkArgument(ctx.getSubscriptionType() == Subsc...
@Test public void subscriptionTypeTest() throws Exception { try (KafkaConnectSink sink = new KafkaConnectSink()) { log.info("Failover is allowed"); sink.open(props, context); } when(context.getSubscriptionType()).thenReturn(SubscriptionType.Exclusive); try (K...
@Override public LabelsToNodesInfo getLabelsToNodes(Set<String> labels) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); Class[] argsClasses = new Class[]{Set.class}; Object[] args = n...
@Test public void testGetLabelsToNodes() throws Exception { LabelsToNodesInfo labelsToNodesInfo = interceptor.getLabelsToNodes(null); Map<NodeLabelInfo, NodeIDsInfo> map = labelsToNodesInfo.getLabelsToNodes(); Assert.assertNotNull(map); Assert.assertEquals(3, map.size()); NodeLabel labelX = NodeL...
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("innerCoder", innerCoder) .add("dict", dict == null ? null : "base64:" + BaseEncoding.base64().encode(dict)) .add("level", level) .toString(); }
@Test public void testToString() throws Exception { assertEquals( "ZstdCoder{innerCoder=StringUtf8Coder, dict=null, level=0}", ZstdCoder.of(StringUtf8Coder.of(), null, 0).toString()); assertEquals( "ZstdCoder{innerCoder=ByteArrayCoder, dict=base64:, level=1}", ZstdCoder.of(Byte...
@Override public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, String managementContextPath, Integer managementPort) { if (isRandom(managementPort)) { return null; } if (managementPort == null && isRandom(serverPort)) { return null; } String heal...
@Test void managementPortIsRandom() { int serverPort = 0; String serverContextPath = "/"; String managementContextPath = null; Integer managementPort = 0; ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); assertThat(actual).isNull...
public AstNode rewrite(final AstNode node, final C context) { return rewriter.process(node, context); }
@Test public void shouldRewriteInsertIntoWithPartitionBy() { // Given: final InsertInto ii = new InsertInto(location, sourceName, query, insertIntoProperties); when(mockRewriter.apply(query, context)).thenReturn(rewrittenQuery); when(expressionRewriter.apply(expression, context)).thenReturn(rewrittenE...
@Override protected void rename( List<HadoopResourceId> srcResourceIds, List<HadoopResourceId> destResourceIds, MoveOptions... moveOptions) throws IOException { if (moveOptions.length > 0) { throw new UnsupportedOperationException("Support for move options is not yet implemented."); ...
@Test public void testRename() throws Exception { create("testFileA", "testDataA".getBytes(StandardCharsets.UTF_8)); create("testFileB", "testDataB".getBytes(StandardCharsets.UTF_8)); // ensure files exist assertArrayEquals("testDataA".getBytes(StandardCharsets.UTF_8), read("testFileA", 0)); asse...
@Override public Serializable getValueFromText(final String xmlMessage) { Serializable readObject = null; try { XStream xstream = JMeterUtils.createXStream(); readObject = (Serializable) xstream.fromXML(xmlMessage, readObject); } catch (Exception e) { throw new Illega...
@Test public void getValueFromText() { String text = "<org.apache.jmeter.protocol.jms.sampler.render.Person><name>Doe</name></org.apache.jmeter.protocol.jms.sampler.render.Person>"; Serializable object = render.getValueFromText(text); assertObject(object, "Doe"); }
@Override public TableBuilder buildTable(TableIdentifier identifier, Schema schema) { return new ViewAwareTableBuilder(identifier, schema); }
@Test public void testCommitExceptionWithoutMessage() { TableIdentifier tableIdent = TableIdentifier.of("db", "tbl"); BaseTable table = (BaseTable) catalog.buildTable(tableIdent, SCHEMA).create(); TableOperations ops = table.operations(); TableMetadata metadataV1 = ops.current(); table.updateSche...
@Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc, boolean addFieldName, boolean addCr ) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); ...
@Test public void testGetFieldDefinition() { assertEquals( "FOO DATETIME", odbcMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) ); assertEquals( "DATETIME", odbcMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, false, false ) ); asse...
@Override public Write.Append append(final Path file, final TransferStatus status) throws BackgroundException { return new Write.Append(status.isExists()).withStatus(status); }
@Test @Ignore public void testAppend() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/iRODS (iPl...
public static COSName getPDFName(String aName) { WeakReference<COSName> weakRef = NAME_MAP.get(aName); COSName name = weakRef != null ? weakRef.get() : null; if (name == null) { // Although we use a ConcurrentHashMap, we cannot use computeIfAbsent() because the returned ...
@Test void PDFBox4076() throws IOException { String special = "中国你好!"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (PDDocument document = new PDDocument()) { PDPage page = new PDPage(); document.addPage(page); document.getDoc...
@Override public boolean onTouchEvent(MotionEvent ev) { if (isEnabled()) return super.onTouchEvent(ev); else return false; }
@Test public void testOnTouchEventDisabled() throws Exception { mUnderTest.setEnabled(false); Assert.assertFalse( mUnderTest.onTouchEvent(MotionEvent.obtain(10, 10, MotionEvent.ACTION_DOWN, 1f, 1f, 0))); }
static void addGetCharacteristicMethod(final String characteristicVariableName, final Characteristic characteristic, final List<Field<?>> fields, final ClassOrInterfaceDeclaration characteris...
@Test void addGetCharacteristicMethod() throws IOException { final String characteristicName = "CharacteristicName"; String expectedMethod = "get" + characteristicName; assertThat(characteristicsTemplate.getMethodsByName(expectedMethod)).isEmpty(); KiePMMLCharacteristicsFactory.addGe...
@Override public void upgrade() { final DBCollection collection = mongoConnection.getDatabase().getCollection("preflight"); final WriteResult result = collection.update( new BasicDBObject("result", new BasicDBObject("$exists", true)), new BasicDBObject(Map.of( ...
@Test @MongoDBFixtures({"V20230929142900_CreateInitialPreflightPassword/old_preflight_config_structure.json"}) void testMigrateConfigCreatePassword() { Assertions.assertThat(collection.countDocuments()).isEqualTo(1); // the old format of configuration, one doc migration.upgrade(); Asser...
@SuppressWarnings("MethodDoesntCallSuperMethod") @Override public DataSchema clone() { return new DataSchema(_columnNames.clone(), _columnDataTypes.clone()); }
@Test public void testClone() { DataSchema dataSchema = new DataSchema(COLUMN_NAMES, COLUMN_DATA_TYPES); DataSchema dataSchemaClone = dataSchema.clone(); Assert.assertEquals(dataSchema, dataSchemaClone); Assert.assertEquals(dataSchema.hashCode(), dataSchemaClone.hashCode()); }
public void removeByInstanceIdAndIdNot(String instanceId, String appSessionId) { repository.findAllByInstanceFlow(AuthenticateLoginFlow.NAME + instanceId ).stream() .filter(s -> !s.getId().equals(appSessionId)) .forEach(s -> removeById(s.getId())); }
@Test void removeByInstanceIdAndIdNotTest() { // persist app session AppSession session = new AppSession(); session.setId(T_APP_SESSION_ID); session.setFlow(AuthenticateLoginFlow.NAME); session.setState("AUTHENTICATED"); session.setUserAppId(T_USER_APP_ID); se...
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) { SourceConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!ex...
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Function Names differ") public void testMergeDifferentName() { SourceConfig sourceConfig = createSourceConfig(); SourceConfig newSourceConfig = createUpdatedSourceConfig("name", "Different"); Source...
@Override public String getMessage() { if (!logPhi) { return super.getMessage(); } String answer; if (hasHl7MessageBytes() || hasHl7AcknowledgementBytes()) { String parentMessage = super.getMessage(); StringBuilder messageBuilder = new StringBuil...
@Test public void testNullHl7Acknowledgement() { instance = new MllpException(EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, NULL_BYTE_ARRAY, LOG_PHI_TRUE); assertEquals(expectedMessage(HL7_MESSAGE, null), instance.getMessage()); }
public static void mergeCacheProperties(JSONObject properties) { if (properties == null || mCacheProperties == null || mCacheProperties.length() == 0) { return; } JSONUtils.mergeJSONObject(mCacheProperties, properties); mCacheProperties = null; }
@Test public void mergeCacheProperties() { DeepLinkManager.mergeCacheProperties(null); }
public void validateUrl(String serverUrl) { HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos"); doGet("", url, body -> buildGson().fromJson(body, RepositoryList.class)); }
@Test public void fail_validate_url_when_validate_url_return_non_json_payload() { server.enqueue(new MockResponse().setResponseCode(400) .setBody("this is not a json payload")); String serverUrl = server.url("/").toString(); assertThatThrownBy(() -> underTest.validateUrl(serverUrl)) .isInstan...
@Override public DevOpsProjectCreationContext create(AlmSettingDto almSettingDto, DevOpsProjectDescriptor devOpsProjectDescriptor) { String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); Long gitlabProjectId = getGitlabProjectId(devOpsProjectDescriptor); String pat = f...
@Test void create_whenGitlabProjectIdIsInvalid_throws() { DevOpsProjectDescriptor devOpsProjectDescriptor = mock(); when(devOpsProjectDescriptor.repositoryIdentifier()).thenReturn("invalid"); assertThatIllegalArgumentException() .isThrownBy(() -> gitlabDevOpsProjectService.create(ALM_SETTING_DTO, d...
public static <T> void forward(CompletableFuture<T> source, CompletableFuture<T> target) { source.whenComplete(forwardTo(target)); }
@Test void testForwardNormal() throws Exception { final CompletableFuture<String> source = new CompletableFuture<>(); final CompletableFuture<String> target = new CompletableFuture<>(); FutureUtils.forward(source, target); assertThat(source).isNotDone(); assertThat(target)....
@Override public ConfigHistoryInfo detailPreviousConfigHistory(Long id) { HistoryConfigInfoMapper historyConfigInfoMapper = mapperManager.findMapper( dataSourceService.getDataSourceType(), TableConstant.HIS_CONFIG_INFO); MapperContext context = new MapperContext(); context.pu...
@Test void testDetailPreviousConfigHistory() { long nid = 256789; //mock query ConfigHistoryInfo mockConfigHistoryInfo = createMockConfigHistoryInfo(0); Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {nid}), eq(HISTORY_DETAIL_ROW_MAPPER))) .then...
@VisibleForTesting Object[] callHttpService( RowMetaInterface rowMeta, Object[] rowData ) throws KettleException { HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder(); if ( data.realConnectionTimeout > -1 ) { clientBuilder.setConnectionTimeout( data...
@Test public void testCallHttpServiceWasCalledWithContext() throws Exception { try ( MockedStatic<HttpClientManager> httpClientManagerMockedStatic = mockStatic( HttpClientManager.class ) ) { httpClientManagerMockedStatic.when( HttpClientManager::getInstance ).thenReturn( manager ); doReturn( null ).wh...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void testBuildWithIllegalMaxConcurrent() { BulkheadConfig.custom() .maxConcurrentCalls(-1) .build(); }
@Override public long remaining() { return mLength - mPosition; }
@Test public void remaining() throws IOException, AlluxioException { AlluxioURI ufsPath = getUfsPath(); createFile(ufsPath, CHUNK_SIZE); try (FileInStream inStream = getStream(ufsPath)) { assertEquals(CHUNK_SIZE, inStream.remaining()); assertEquals(0, inStream.read()); assertEquals(CHUNK...
@Override public OFAgent removeAgent(NetworkId networkId) { checkNotNull(networkId, ERR_NULL_NETID); synchronized (this) { OFAgent existing = ofAgentStore.ofAgent(networkId); if (existing == null) { final String error = String.format(MSG_OFAGENT, networkId, ER...
@Test(expected = NullPointerException.class) public void testRemoveNullAgent() { target.removeAgent(null); }
public Set<String> getMatchKeys() { return routerConfig.isUseRequestRouter() ? requestTags : RuleUtils.getMatchKeys(); }
@Test public void testGetMatchKeysWhenUseRequestRouter() { config.setUseRequestRouter(true); Match match = new Match(); match.setHeaders(Collections.singletonMap("bar", Collections.singletonList(new MatchRule()))); Rule rule = new Rule(); rule.setMatch(match); Entire...
public String render(Object o) { StringBuilder result = new StringBuilder(template.length()); render(o, result); return result.toString(); }
@Test public void canSubstituteMultipleValuesFromLists() { Template template = new Template( "Hello {{#getValues}}{{toString}},{{/getValues}} {{getPrivateNonStringValue}} " + "{{#getValues}}{{toString}}.{{/getValues}} {{getPrivateValue}} "); assertEquals("Hello 1,2,3, 3 1.2.3...
public static Map<String, Object> toValueMap(ReferenceMap m, Map<String, ValueReference> parameters) { final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.builder(); for (Map.Entry<String, Reference> entry : m.entrySet()) { final Object value = valueOf(entry.getValue(), para...
@Test public void toValueMap() { final Map<String, ValueReference> parameters = ImmutableMap.<String, ValueReference>builder() .put("BOOLEAN", ValueReference.of(true)) .put("FLOAT", ValueReference.of(1.0f)) .put("INTEGER", ValueReference.of(42)) ...
@Override public CRTask deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN); }
@Test public void shouldInstantiateATaskForTypeNant() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("type", "nant"); taskTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext); verify(jsonDeserializationContext).deserialize(jsonObject, CRNantTask....