focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public final void writeByte(final int v) throws IOException { write(v); }
@Test public void testWriteByteForPositionV() throws Exception { out.writeByte(0, 10); assertEquals(10, out.buffer[0]); }
@Override public boolean skip(final ServerWebExchange exchange) { return skipExceptHttpLike(exchange); }
@Test public void testSkip() { ServerWebExchange exchangeNormal = generateServerWebExchange(); assertTrue(webClientPlugin.skip(exchangeNormal)); ServerWebExchange exchangeHttp = generateServerWebExchange(); when(((ShenyuContext) exchangeHttp.getAttributes().get(Constants.CONTEXT)).g...
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: ret...
@Test public void testConvertTypeCaseArray() { TypeInfo elementTypeInfo = TypeInfoFactory.INT; ArrayTypeInfo arrayTypeInfo = TypeInfoFactory.getArrayTypeInfo(elementTypeInfo); Type result = EntityConvertUtils.convertType(arrayTypeInfo); Type expectedType = new ArrayType(Type.INT); ...
@Override public void incIteration() { throw new UnsupportedOperationException(); }
@Test public void testIncIteration() { assertThrowsUnsupportedOperation(unmodifiables::incIteration); }
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void kGroupedStreamZeroArgCountShouldPreserveTopologyStructure() { final StreamsBuilder builder = new StreamsBuilder(); builder.stream("input-topic") .groupByKey() .count(); final Topology topology = builder.build(); final TopologyDescription des...
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testDeterminismHasGenericRecord() { assertDeterministic(AvroCoder.of(HasGenericRecord.class)); }
public abstract byte[] encode(MutableSpan input);
@Test void span_minimum_JSON_V2() { MutableSpan span = new MutableSpan(); span.traceId("7180c278b62e8f6a216a2aea45d08fc9"); span.id("5b4185666d50f68b"); assertThat(new String(encoder.encode(span), UTF_8)) .isEqualTo( "{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"id\":\"5b4185...
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not f...
@Test public void testStaticMemberFenceDuplicateSyncingFollowerAfterMemberIdChanged() throws Exception { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMemb...
public void edge(T from, T to) { if (from == null || to == null) throw new IllegalArgumentException("Null vertices are not allowed, edge: " + from + "->" + to); adjMap.computeIfAbsent(from, k -> new LinkedHashSet<>()).add(to); adjMap.computeIfAbsent(to, k -> new LinkedHashSet<>()); ...
@Test void null_vertices_are_not_allowed() { var graph = new Graph<Vertices>(); try { graph.edge(A, null); fail(); } catch (IllegalArgumentException e) { assertEquals("Null vertices are not allowed, edge: A->null", e.getMessage()); } }
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testNodeLocalAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().allocationReq...
static List<ClassLoader> selectClassLoaders(ClassLoader classLoader) { // list prevents reordering! List<ClassLoader> classLoaders = new ArrayList<>(); if (classLoader != null) { classLoaders.add(classLoader); } // check if TCCL is same as given classLoader ...
@Test public void selectingSimpleDifferentThreadContextClassLoader() { Thread currentThread = Thread.currentThread(); ClassLoader tccl = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(new URLClassLoader(new URL[0])); List<ClassLoader> classLoaders = Servic...
public void execute() { Profiler stepProfiler = Profiler.create(LOGGER).logTimeLast(true); boolean allStepsExecuted = false; try { executeSteps(stepProfiler); allStepsExecuted = true; } finally { if (listener != null) { executeListener(allStepsExecuted); } } }
@Test public void execute_throws_IAE_if_step_adds_statistic_multiple_times() { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "foo", "20"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { assertThatThrownBy(() -> new Computati...
public static boolean shouldEnablePushdownForTable(ConnectorSession session, Table table, String path, Optional<Partition> optionalPartition) { if (!isS3SelectPushdownEnabled(session)) { return false; } if (path == null) { return false; } // Hive tab...
@Test public void testShouldNotEnableSelectPushdownWhenColumnTypesAreNotSupported() { Column newColumn = new Column("column", HIVE_BINARY, Optional.empty(), Optional.empty()); Table newTable = new Table( "db", "table", "owner", EXTE...
public DoubleArrayAsIterable usingExactEquality() { return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsAtLeast_primitiveDoubleArray_success() { assertThat(array(1.1, 2.2, 3.3)).usingExactEquality().containsAtLeast(array(2.2, 1.1)); }
@Override @CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理 public void deleteNotifyTemplate(Long id) { // 校验存在 validateNotifyTemplateExists(id); // 删除 notifyTemplateMapper.deleteById(id); }
@Test public void testDeleteNotifyTemplate_success() { // mock 数据 NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); notifyTemplateMapper.insert(dbNotifyTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbNotifyTemplate.getId(); // 调用 noti...
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenCellSchemaFieldMismatch_throws() { String boolTrue = "true"; Schema schema = Schema.builder().addBooleanField("a_boolean").addFloatField("a_float").build(); IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> CsvIOParseHel...
@Override public ConfigOperateResult insertOrUpdateCas(String srcIp, String srcUser, ConfigInfo configInfo, Map<String, Object> configAdvanceInfo) { try { ConfigInfoStateWrapper configInfoState = findConfigInfoState(configInfo.getDataId(), configInfo.getGroup(), c...
@Test void testInsertOrUpdateCasOfInsertConfigSuccess() { Map<String, Object> configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); String dataId = "dataId"; String group = "group"; String tenant = "tenant"; String appName = ...
public static Builder builder() { return new Builder(); }
@TestTemplate public void rewriteWithDuplicateFiles() { assertThat(listManifestFiles()).isEmpty(); table.newAppend().appendFile(FILE_A2).appendFile(FILE_A2).appendFile(FILE_A2).commit(); table .newRewrite() .deleteFile(FILE_A2) .deleteFile(DataFiles.builder(SPEC).copy(FILE_A2).bu...
@Scheduled(initialDelayString = "#{T(org.apache.commons.lang3.RandomUtils).nextLong(0, ${sql.ttl.alarms.checking_interval})}", fixedDelayString = "${sql.ttl.alarms.checking_interval}") public void cleanUp() { PageDataIterable<TenantId> tenants = new PageDataIterable<>(tenantService::findTenantsIds, 10_000);...
@Test public void testAlarmsCleanUp() throws Exception { int ttlDays = 1; updateDefaultTenantProfileConfig(profileConfiguration -> { profileConfiguration.setAlarmsTtlDays(ttlDays); }); loginTenantAdmin(); Device device = createDevice("device_0", "device_0"); ...
@Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ // do something }
@Test void whenInputIsInvalidForUpdate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(null); assertThrows(ConstraintViolationException.class, () -> { service.validateForUpdate(input); }); }
public void putValue(String fieldName, @Nullable Object value) { _fieldToValueMap.put(fieldName, value); }
@Test public void testEmptyRowNotEqualToNonEmptyRow() { GenericRow first = new GenericRow(); GenericRow second = new GenericRow(); second.putValue("one", 1); Assert.assertNotEquals(first, second); }
private long getLastInsertId(final Collection<UpdateResult> updateResults, final Collection<Comparable<?>> autoIncrementGeneratedValues) { List<Long> lastInsertIds = new ArrayList<>(updateResults.size() + autoIncrementGeneratedValues.size()); for (UpdateResult each : updateResults) { if (eac...
@Test void assertGetLastInsertIdWhenAutoGeneratedIdIsNotEmpty() { UpdateResponseHeader actual = new UpdateResponseHeader(mock(SQLStatement.class), Collections.emptyList(), createAutoIncrementGeneratedValues()); assertThat(actual.getLastInsertId(), is(1L)); }
@Override public Map<String, HivePartitionStats> getPartitionStatistics(Table table, List<String> partitionNames) { String dbName = ((HiveMetaStoreTable) table).getDbName(); String tblName = ((HiveMetaStoreTable) table).getTableName(); List<HivePartitionName> hivePartitionNames = partitionN...
@Test public void testGetPartitionStatistics() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); com.starrocks.catalog.Table hiveTable = cachingHiveMetastore.getTable("db1", "table1");...
protected void close() { if (ctx != null) { ctx.close(); } }
@Test(timeOut = 30000) public void testDuplicateConcurrentSubscribeCommand() throws Exception { resetChannel(); setChannelConnected(); CompletableFuture<Topic> delayFuture = new CompletableFuture<>(); doReturn(delayFuture).when(brokerService).getOrCreateTopic(any(String.class)); ...
static void autoAddHttpExtractor(Connection c, String name, ChannelHandler handler) { if (handler instanceof ByteToMessageDecoder || handler instanceof ByteToMessageCodec || handler instanceof CombinedChannelDuplexHandler) { String extractorName = name + "$extractor"; if (c.channel().pipeline().contex...
@Test void httpAndJsonDecoders() { EmbeddedChannel channel = new EmbeddedChannel(); Connection testContext = () -> channel; ChannelHandler handler = new JsonObjectDecoder(true); testContext.addHandlerLast("foo", handler); HttpOperations.autoAddHttpExtractor(testContext, "foo", handler); String json1 = ...
public ProcessingMode getMode() { return mode; }
@Test public void testParse_mode() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--mode=packaged", "my-app.jar"); assertThat(jarCommand.getMode()).isEqualTo(ProcessingMode.packaged); }
@Override public Deserializer<AvroWrapper<T>> getDeserializer(Class<AvroWrapper<T>> c) { Configuration conf = getConf(); GenericData dataModel = createDataModel(conf); if (AvroKey.class.isAssignableFrom(c)) { Schema writerSchema = getKeyWriterSchema(conf); Schema readerSchema = getKeyReaderSch...
@Test void classPath() throws Exception { Configuration conf = new Configuration(); ClassLoader loader = conf.getClass().getClassLoader(); AvroSerialization serialization = new AvroSerialization(); serialization.setConf(conf); AvroDeserializer des = (AvroDeserializer) serialization.getDeserializer...
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testAvroCoderCyclicRecords() { // Recursive record assertNonDeterministic( AvroCoder.of( SchemaBuilder.record("cyclicRecord") .fields() .name("cycle") .type("cyclicRecord") .noDefault() .endRe...
@Override public int compareTo(SegmentPointer other) { if (idPage == other.idPage) { return Long.compare(offset, other.offset); } else { return Integer.compare(idPage, other.idPage); } }
@Test public void testCompareInSameSegment() { final SegmentPointer minor = new SegmentPointer(1, 10); final SegmentPointer otherMinor = new SegmentPointer(1, 10); final SegmentPointer major = new SegmentPointer(1, 12); assertEquals(-1, minor.compareTo(major), "minor is less than ma...
public Collection<SQLException> closeConnections(final boolean forceRollback) { Collection<SQLException> result = new LinkedList<>(); synchronized (cachedConnections) { resetSessionVariablesIfNecessary(cachedConnections.values(), result); for (Connection each : cachedConnections....
@Test void assertCloseConnectionsCorrectlyWhenForceRollbackAndInTransaction() throws SQLException { connectionSession.getTransactionStatus().setInTransaction(true); Connection connection = prepareCachedConnections(); databaseConnectionManager.closeConnections(true); verify(connection...
public static String processPattern(String pattern, TbMsg tbMsg) { try { String result = processPattern(pattern, tbMsg.getMetaData()); JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData()); if (json.isObject()) { Matcher matcher = DATA_PATTERN.matcher(result...
@Test public void testNoReplacement() { String pattern = "ABC ${metadata_key} $[data_key]"; TbMsgMetaData md = new TbMsgMetaData(); md.putValue("key", "metadata_value"); ObjectNode node = JacksonUtil.newObjectNode(); node.put("key", "data_value"); TbMsg msg = TbMsg....
@Override public AppResponse process(Flow flow, AppRequest params) { var result = digidClient.getWidstatus(appSession.getWidRequestId()); switch(result.get("status").toString()){ case "NO_DOCUMENTS": appSession.setRdaSessionStatus("NO_DOCUMENTS"); appSess...
@Test void processWidstatusValidRdaSessionEmpty(){ when(digidClientMock.getWidstatus(mockedAppSession.getWidRequestId())).thenReturn(validDigidClientResponse); when(rdaClientMock.startSession(anyString(), anyString(), anyString(), any(), any())).thenReturn(rdaResponseNoSession); AppRespons...
@Override public long remove(long key) { final long valueAddr = hsa.get(key); if (valueAddr == NULL_ADDRESS) { return nullValue; } final long oldValue = mem.getLong(valueAddr); hsa.remove(key); return oldValue; }
@Test public void testRemove() { long key = newKey(); assertEqualsKV(MISSING_VALUE, map.remove(key), key, 0); long value = newValue(); map.put(key, value); long oldValue = map.remove(key); assertEqualsKV(value, oldValue, key, value); }
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedForwardWildCard() { String[] forwardedFields = {"f1->*"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsSingleFromString( ...
private QueryParamsDataMap() { }
@Test public void testNumericKeyIndicesWithHoles() throws Exception { DataMap queryParamDataMap = queryParamsDataMap("ids[4]=1&ids[1]=0&ids[8]=2"); Object idsObj = queryParamDataMap.get("ids"); Assert.assertTrue(idsObj instanceof DataList); DataList ids = (DataList) idsObj; Assert.assertEquals(i...
public static StreamExecutionEnvironment getExecutionEnvironment() { return getExecutionEnvironment(new Configuration()); }
@Test void testUserDefinedJobName() { String jobName = "MyTestJob"; Configuration config = new Configuration(); config.set(PipelineOptions.NAME, jobName); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(config); testJobName(jobName, env); ...
public static Sensor throttleTimeSensor(SenderMetricsRegistry metrics) { Sensor produceThrottleTimeSensor = metrics.sensor("produce-throttle-time"); produceThrottleTimeSensor.add(metrics.produceThrottleTimeAvg, new Avg()); produceThrottleTimeSensor.add(metrics.produceThrottleTimeMax, new Max());...
@Test public void testQuotaMetrics() { MockSelector selector = new MockSelector(time); Sensor throttleTimeSensor = Sender.throttleTimeSensor(this.senderMetricsRegistry); Cluster cluster = TestUtils.singletonCluster("test", 1); Node node = cluster.nodes().get(0); NetworkClient...
@Override public void register(JobManagerRunner jobManagerRunner) { Preconditions.checkArgument( !isRegistered(jobManagerRunner.getJobID()), "A job with the ID %s is already registered.", jobManagerRunner.getJobID()); this.jobManagerRunners.put(jobMana...
@Test void testRegister() { final JobID jobId = new JobID(); testInstance.register(TestingJobManagerRunner.newBuilder().setJobId(jobId).build()); assertThat(testInstance.isRegistered(jobId)).isTrue(); }
public void shutdown(final Duration duration) { for (final TaskExecutor t: taskExecutors) { t.requestShutdown(); } signalTaskExecutors(); for (final TaskExecutor t: taskExecutors) { t.awaitShutdown(duration); } }
@Test public void shouldBlockOnAwait() throws InterruptedException { final AwaitingRunnable awaitingRunnable = new AwaitingRunnable(); final Thread awaitingThread = new Thread(awaitingRunnable); awaitingThread.start(); assertFalse(awaitingRunnable.awaitDone.await(100, TimeUnit.MILLI...
@Override public boolean equals(final Object o) { if(this == o) { return true; } if(!(o instanceof Distribution)) { return false; } final Distribution that = (Distribution) o; return Objects.equals(method, that.method); }
@Test public void testEquals() { assertEquals(new Distribution(Distribution.DOWNLOAD, URI.create("o"), false), new Distribution(Distribution.DOWNLOAD, URI.create("o"), false)); assertEquals(new Distribution(Distribution.DOWNLOAD, URI.create("o"), true), new Distribution(Distribution.DOWNLOAD, URI.cr...
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testPkcs1AesEncryptedDsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_aes_encrypted.key") .getFile()), "example"); assertNotNull(key); }
public static String generate(String command, CommandType type) { return generate(Lists.newArrayList(command), type); }
@Test public void manyRequestsTest() throws IOException { InputStream streamOrig = getClass().getResourceAsStream(REQ_FILE2); ObjectMapper om = new ObjectMapper(); JsonNode node1 = om.readTree(streamOrig); ArrayList<String> cmds = new ArrayList<>(); cmds.add("show interface"...
public InputStream getBody() throws IOException { return httpResponse.getContent(); }
@Test public void testGetContent() throws IOException { byte[] expectedResponse = "crepecake\nis\ngood!".getBytes(StandardCharsets.UTF_8); ByteArrayInputStream responseInputStream = new ByteArrayInputStream(expectedResponse); Mockito.when(httpResponseMock.getContent()).thenReturn(responseInputStream); ...
private IcebergFixedObjectInspector() { super(TypeInfoFactory.binaryTypeInfo); }
@Test public void testIcebergFixedObjectInspector() { IcebergFixedObjectInspector oi = IcebergFixedObjectInspector.get(); assertThat(oi.getCategory()).isEqualTo(ObjectInspector.Category.PRIMITIVE); assertThat(oi.getPrimitiveCategory()) .isEqualTo(PrimitiveObjectInspector.PrimitiveCategory.BINARY)...
@Override public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) { File[] allFiles = getFiles(configRepoCheckoutDirectory, context); // if context had changed files list then we could parse only new content PartialConfig[] allFragments = parseFiles(al...
@Test public void shouldLoadDirectoryWithOnePipeline() throws Exception { GoConfigMother mother = new GoConfigMother(); PipelineConfig pipe1 = mother.cruiseConfigWithOnePipelineGroup().getAllPipelineConfigs().get(0); helper.addFileWithPipeline("pipe1.gocd.xml", pipe1); PartialConfi...
public static HttpRequest newJDiscRequest(CurrentContainer container, HttpServletRequest servletRequest) { try { var jettyRequest = (Request) servletRequest; var jdiscHttpReq = HttpRequest.newServerRequest( container, getUri(servletRequest), ...
@Test final void illegal_host_throws_requestexception2() { try { HttpRequestFactory.newJDiscRequest( new MockContainer(), createMockRequest("http", ".", "/foo", "")); fail("Above statement should throw"); } catch (RequestException e) { ...
@VisibleForTesting CompletableFuture<Acknowledge> getBootstrapCompletionFuture() { return bootstrapCompletionFuture; }
@Test void testClusterShutdownWhenApplicationGetsCancelled() throws Exception { // we're "listening" on this to be completed to verify that the cluster // is being shut down from the ApplicationDispatcherBootstrap final CompletableFuture<ApplicationStatus> externalShutdownFuture = ...
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); }
@Test public void scheduleAtFixedRate() { underTest.scheduleAtFixedRate(runnable, initialDelay, period, SECONDS); verify(executorService).scheduleAtFixedRate(runnable, initialDelay, period, SECONDS); }
public boolean isAvailable() { return type == Type.available; }
@Test public void isPresenceAvailableTest() { PresenceBuilder presence = getNewPresence(); presence.ofType(Presence.Type.available); assertTrue(presence.build().isAvailable()); presence.ofType(Presence.Type.unavailable); assertFalse(presence.build().isAvailable()); }
static boolean shouldStoreMessage(final Message message) { // XEP-0334: Implement the <no-store/> hint to override offline storage if (message.getChildElement("no-store", "urn:xmpp:hints") != null) { return false; } // OF-2083: Prevent storing offline message that is already...
@Test public void shouldNotStoreHeadlineMessages() { // XEP-0160: "headline" message types SHOULD NOT be stored offline Message message = new Message(); message.setType(Message.Type.headline); assertFalse(OfflineMessageStore.shouldStoreMessage(message)); }
public static String getOwner(FileDescriptor fd) throws IOException { ensureInitialized(); if (Shell.WINDOWS) { String owner = Windows.getOwner(fd); owner = stripDomain(owner); return owner; } else { long uid = POSIX.getUIDforFDOwnerforOwner(fd); CachedUid cUid = uidCache.get(u...
@Test (timeout = 30000) public void testFstat() throws Exception { FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testfstat")); NativeIO.POSIX.Stat stat = NativeIO.POSIX.getFstat(fos.getFD()); fos.close(); LOG.info("Stat: " + String.valueOf(stat)); String owner = stat.getO...
@Udf public <T> List<T> intersect( @UdfParameter(description = "First array of values") final List<T> left, @UdfParameter(description = "Second array of values") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> intersection = Sets.newLinkedHashSet(l...
@Test public void shouldReturnNullForArraysOfOnlyNulls() { final List<String> input1 = Arrays.asList(null, null); final List<String> input2 = Arrays.asList(null, null, null); final List<String> result = udf.intersect(input1, input2); assertThat(result.get(0), is(nullValue())); }
@Override public void validTenant(Long id) { TenantDO tenant = getTenant(id); if (tenant == null) { throw exception(TENANT_NOT_EXISTS); } if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) { throw exception(TENANT_DISABLE, tenant.getName()); ...
@Test public void testValidTenant_expired() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(buildTime(2020, 2, 2))); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServ...
@Override public void write(Record<GenericObject> record) throws Exception { // kpl-thread captures publish-failure. fail the publish on main pulsar-io-thread to maintain the ordering if (kinesisSinkConfig.isRetainOrdering() && previousPublishFailed == TRUE) { LOG.warn("Skip acking messa...
@Test public void testWrite() throws Exception { AtomicBoolean ackCalled = new AtomicBoolean(); AtomicLong sequenceCounter = new AtomicLong(0); Message<GenericObject> message = mock(Message.class); when(message.getData()).thenReturn("hello".getBytes(StandardCharsets.UTF_8)); ...
public final void performDispatch(Notification notification, Context context) { if (StringUtils.equals(notification.getType(), notificationType) || StringUtils.equals("", notificationType)) { dispatch(notification, context); } }
@Test public void shouldAlwaysRunDispatchForGenericDispatcher() { NotificationDispatcher dispatcher = new FakeGenericNotificationDispatcher(); dispatcher.performDispatch(notification, context); verify(context, times(1)).addUser("user1", channel); }
@SuppressWarnings("unchecked") @Override public void configure(final Map<String, ?> configs, final boolean isKey) { final String windowedInnerClassSerdeConfig = (String) configs.get(StreamsConfig.WINDOWED_INNER_CLASS_SERDE); Serde<T> windowInnerClassSerde = null; if (windowedInnerClass...
@Test public void shouldThrowConfigExceptionWhenInvalidWindowInnerClassDeserialiserSupplied() { props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class"); assertThrows(ConfigException.class, () -> sessionWindowedDeserializer.configure(props, false)); }
@Override public void addInput(Page page) { checkState(!finishing, "Operator is already finishing"); boolean done = topNBuilder.processPage(requireNonNull(page, "page is null")).process(); // there is no grouping so work will always be done verify(done); topNBuilder.updat...
@Test public void testExceedMemoryLimit() throws Exception { List<Page> input = rowPagesBuilder(BIGINT) .row(1L) .build(); DriverContext smallDiverContext = createTaskContext(executor, scheduledExecutor, TEST_SESSION, new DataSize(1, BYTE)) ...
public void transitionTo(ClassicGroupState groupState) { assertValidTransition(groupState); previousState = state; state = groupState; currentStateTimestamp = Optional.of(time.milliseconds()); metrics.onClassicGroupStateTransition(previousState, state); }
@Test public void testDeadToDeadIllegalTransition() { group.transitionTo(PREPARING_REBALANCE); group.transitionTo(DEAD); group.transitionTo(DEAD); assertState(group, DEAD); }
@Override public void validate(Context context) { if (!context.deployState().isHosted() || context.deployState().zone().system().isPublic()) return; if (context.deployState().getProperties().allowDisableMtls()) return; context.model().getContainerClusters().forEach((id, cluster) -> { ...
@Test public void validator_accepts_when_allowed_to_exclude() throws IOException, SAXException { DeployState deployState = createDeployState(zone(CloudName.AWS, SystemName.main), new StringBuffer(), true); VespaModel model = new VespaModel( MapConfigModelRegistry.createFromList(new M...
static CommandLineOptions parse(Iterable<String> options) { CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); List<String> expandedOptions = new ArrayList<>(); expandParamsFiles(options, expandedOptions); Iterator<String> it = expandedOptions.iterator(); while (it.hasNext()) ...
@Test public void setExitIfChanged() { assertThat( CommandLineOptionsParser.parse(Arrays.asList("--set-exit-if-changed")) .setExitIfChanged()) .isTrue(); }
@Override public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) { Objects.requireNonNull(intentOperationContext); Optional<IntentData> toUninstall = intentOperationContext.toUninstall(); Optional<IntentData> toInstall = intentOperationContext.toInstall(); ...
@Test public void testGroupInstallationFailedError() { // Group install failed, and retry threshold exceed intentInstallCoordinator = new TestIntentInstallCoordinator(); installer.intentInstallCoordinator = intentInstallCoordinator; errors = ImmutableList.of(GROUPINSTALLATIONFAILED, ...
@Override public SnippetType getSnippetType() { return configurationParameters .get(SNIPPET_TYPE_PROPERTY_NAME, SnippetTypeParser::parseSnippetType) .orElse(SnippetType.UNDERSCORE); }
@Test void getSnippetType() { ConfigurationParameters underscore = new MapConfigurationParameters( Constants.SNIPPET_TYPE_PROPERTY_NAME, "underscore"); assertThat(new CucumberEngineOptions(underscore).getSnippetType(), is(SnippetType.UNDERSCORE)); ConfigurationParam...
@Override public void truncate() { truncateToEntries(0); }
@Test public void testTruncate() { appendEntries(maxEntries - 1); idx.truncate(); assertEquals(0, idx.entries()); appendEntries(maxEntries - 1); idx.truncateTo(10 + baseOffset); assertEquals(0, idx.entries()); }
public ResourceID getResourceID() { return unresolvedTaskManagerLocation.getResourceID(); }
@Test void testInitialSlotReport() throws Exception { final TaskExecutor taskExecutor = createTaskExecutor(1); taskExecutor.start(); try { final TestingResourceManagerGateway testingResourceManagerGateway = new TestingResourceManagerGateway(); fi...
public static Patch<String> diffInline(String original, String revised) { List<String> origList = new ArrayList<>(); List<String> revList = new ArrayList<>(); for (Character character : original.toCharArray()) { origList.add(character.toString()); } for (Character cha...
@Test public void testDiffInline2() { final Patch<String> patch = DiffUtils.diffInline("es", "fest"); assertEquals(2, patch.getDeltas().size()); assertTrue(patch.getDeltas().get(0) instanceof InsertDelta); assertEquals(0, patch.getDeltas().get(0).getSource().getPosition()); a...
static final String generateForFragment(RuleBuilderStep step, Configuration configuration) { final String fragmentName = step.function(); try { Template template = configuration.getTemplate(fragmentName); StringWriter writer = new StringWriter(); Map<String, Object> f...
@Test public void generateForFragmentThrowsException_WhenParameterNotSet() { RuleBuilderStep step = mock(RuleBuilderStep.class); when(step.function()).thenReturn("test_fragment1"); assertThatThrownBy(() -> ParserUtil.generateForFragment(step, configuration)) .isInstanceOf(Ill...
public static Map<String, String> convertSubscribe(Map<String, String> subscribe) { Map<String, String> newSubscribe = new HashMap<>(); for (Map.Entry<String, String> entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); ...
@Test void testSubscribe2() { String key = "dubbo.test.api.HelloService"; Map<String, String> subscribe = new HashMap<String, String>(); subscribe.put(key, "version=1.0.0&group=test&dubbo.version=2.0.0"); Map<String, String> newSubscribe = UrlUtils.convertSubscribe(subscribe); ...
@Override public long getTokenTtlInSeconds(String token) throws AccessException { if (!authConfigs.isAuthEnabled()) { return tokenValidityInSeconds; } return jwtParser.getExpireTimeInSeconds(token) - TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); }
@Test void testGetTokenTtlInSeconds() throws AccessException { assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0); }
public Result waitForConditionAndFinish(Config config, Supplier<Boolean> conditionCheck) throws IOException { return waitForConditionsAndFinish(config, conditionCheck); }
@Test public void testFinishAfterCondition() throws IOException { // Arrange AtomicInteger callCount = new AtomicInteger(); int totalCalls = 3; Supplier<Boolean> checker = () -> callCount.incrementAndGet() >= totalCalls; when(client.getJobStatus(any(), any(), any())) .thenReturn(JobState....
public void install(String [] names) { for (String name : names) { install(name); } }
@Test void install() { assertEquals(0, interpreterBaseDir.listFiles().length); installer.install("intp1"); assertTrue(new File(interpreterBaseDir, "intp1").isDirectory()); }
public Schema find(String name, String namespace) { Schema.Type type = PRIMITIVES.get(name); if (type != null) { return Schema.create(type); } String fullName = fullName(name, namespace); Schema schema = getNamedSchema(fullName); if (schema == null) { schema = getNamedSchema(name); ...
@Test public void validateSchemaRetrievalByFullName() { assertSame(fooRecord, fooBarBaz.find(fooRecord.getFullName(), null)); }
public void addValueProviders(final String segmentName, final RocksDB db, final Cache cache, final Statistics statistics) { if (storeToValueProviders.isEmpty()) { logger.debug("Adding metrics record...
@Test public void shouldThrowIfCacheToAddIsNullButExistingCacheIsNotNull() { recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, null, statisticsToAdd1); final Throwable exception = assertThrows( IllegalStateException.class, () -> recorder.addValueProviders(SEGMENT_ST...
static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean rejectMessageOnError, AcknowledgeType acknowledgeType) { while (messageCount < maxMessages || maxMessages == -1) { ConsumerRecord<byte[], byte[]> msg; ...
@Test public void shouldStopWhenOutputCheckErrorFails() { ConsoleShareConsumer.ConsumerWrapper consumer = mock(ConsoleShareConsumer.ConsumerWrapper.class); MessageFormatter formatter = mock(MessageFormatter.class); PrintStream printStream = mock(PrintStream.class); ConsumerRecord<by...
public static String trim(String input) { if (input == null) { return null; } return input.strip(); }
@Test void testTrim() { // Test with null input assertNull(StringUtil.trim(null)); // Test with an empty string assertEquals("", StringUtil.trim("")); // Test with spaces assertEquals("Hello, World!", StringUtil.trim(" Hello, World! ")); // Test with Unic...
public static StreamDecoder create(Decoder iteratorDecoder) { return new StreamDecoder(iteratorDecoder, null); }
@Test void simpleStreamTest() { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo\nbar")); StreamInterface api = Feign.builder() .decoder(StreamDecoder.create( (response, type) -> new BufferedReader(response.body().asReader(UTF_8)).lines() ...
@Override public void loadPartitions(List<String> partitionPaths) { execute( () -> { preferredView.loadPartitions(partitionPaths); return null; }, () -> { getSecondaryView().loadPartitions(partitionPaths); return null; }); }
@Test public void testLoadPartitions() { String partitionPath = "/table2"; fsView.loadPartitions(Collections.singletonList(partitionPath)); verify(primary, times(1)).loadPartitions(Collections.singletonList(partitionPath)); verify(secondary, never()).loadPartitions(any()); verify(secondaryViewSup...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefin...
@Test public void testConvertTime() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("time") .dataType("time") .scale(3) .build();...
public EvictionConfig getEvictionConfig() { return evictionConfig; }
@Test public void testMaxSize_whenValueIsPositive_thenSetValue() { config.getEvictionConfig().setSize(4531); assertEquals(4531, config.getEvictionConfig().getSize()); }
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) { if (statsEnabled) { stats.log(deviceStateServiceMsg); } stateService.onQueueMsg(deviceStateServiceMsg, callback); }
@Test public void givenProcessingSuccess_whenForwardingDisconnectMsgToStateService_thenOnSuccessCallbackIsCalled() { // GIVEN var disconnectMsg = TransportProtos.DeviceDisconnectProto.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantId...
public static FailoverStrategy.Factory loadFailoverStrategyFactory(final Configuration config) { checkNotNull(config); final String strategyParam = config.get(JobManagerOptions.EXECUTION_FAILOVER_STRATEGY); switch (strategyParam.toLowerCase()) { case FULL_RESTART_STRATEGY_NAME: ...
@Test void testLoadRestartAllStrategyFactory() { final Configuration config = new Configuration(); config.set( JobManagerOptions.EXECUTION_FAILOVER_STRATEGY, FailoverStrategyFactoryLoader.FULL_RESTART_STRATEGY_NAME); assertThat(FailoverStrategyFactoryLoader.lo...
public static ObjectMapper createObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); registerModules(objectMapper); return objectMapper; }
@Test void testObjectMappeDateTimeSupportedEnabled() throws Exception { final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper(); final String instantString = "2022-08-07T12:00:33.107787800Z"; final Instant instant = Instant.parse(instantString); final String instantJso...
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 testRestartDoneWithFailedStep() { Map<String, Boolean> idStatusMap = new LinkedHashMap<>(); idStatusMap.put("job_3", Boolean.FALSE); idStatusMap.put("job_9", Boolean.TRUE); idStatusMap.put("job_8", Boolean.TRUE); Assert.assertTrue( DagHelper.isDone( runtimeDag...
public static String lastElement(List<String> strings) { checkArgument(!strings.isEmpty(), "empty list"); return strings.get(strings.size() - 1); }
@Test public void testLastElementDouble() { assertEquals("2", lastElement(l("first", "2"))); }
@Override public boolean putIfAbsent(K key, V value) { return cache.putIfAbsent(key, value); }
@Test public void testPutIfAbsent() { cache.put(42, "oldValue"); assertTrue(adapter.putIfAbsent(23, "newValue")); assertFalse(adapter.putIfAbsent(42, "newValue")); assertEquals("newValue", cache.get(23)); assertEquals("oldValue", cache.get(42)); }
public long computeMemorySize(double fraction) { validateFraction(fraction); return (long) Math.floor(memoryBudget.getTotalMemorySize() * fraction); }
@Test void testComputeMemorySizeFailForTooLargeFraction() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> memoryManager.computeMemorySize(1.1)); }
@Override public Object apply(Object input) { return PropertyOrFieldSupport.EXTRACTION.getValueOf(propertyOrFieldName, input); }
@Test void should_ignore_property_with_bare_name_method_when_disabled() { try { // GIVEN Introspection.setExtractBareNamePropertyMethods(false); BareOptionalIntHolder holder = new BareOptionalIntHolder(42); ByNameSingleExtractor underTest = new ByNameSingleExtractor("value"); // WHEN...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize")); }
@Test(expected = NotfoundException.class) public void testListNotfound() throws Exception { final Path container = new Path("notfound.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); new SpectraObjectListService(session).list(container, new DisabledListProgressListener()); }
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) { // Set of Visited Schemas IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>(); // Stack that contains the Schemas to process and afterVisitNonTerminal // functions. // Deque<Either<Schema, Supplier<SchemaVi...
@Test public void testVisit13() { String s12 = "{\"type\": \"int\"}"; Assert.assertEquals("\"int\".", Schemas.visit(new Schema.Parser().parse(s12), new TestVisitor() { @Override public SchemaVisitorAction visitTerminal(Schema terminal) { sb.append(terminal).append('.'); return Sche...
@Override public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) { if (response.errorCode() != Errors.NONE.code()) { String errorMessage = String.format( "Unexpected error in Heartbeat response. Expected no error, but received: %s", Er...
@Test public void testTransitionToReconcilingIfEmptyAssignmentReceived() { ConsumerMembershipManager membershipManager = createMembershipManagerJoiningGroup(); assertEquals(MemberState.JOINING, membershipManager.state()); ConsumerGroupHeartbeatResponse responseWithoutAssignment = ...
@Override @SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:MethodLength"}) protected IdentifiedDataSerializable getConfig() { MapConfig config = new MapConfig(parameters.name); config.setAsyncBackupCount(parameters.asyncBackupCount); config....
@Test public void testPartitioningAttributeConfigsTransmittedCorrectly() { MapConfig mapConfig = new MapConfig("my-map"); mapConfig.setPartitioningAttributeConfigs(Arrays.asList( new PartitioningAttributeConfig("attr1"), new PartitioningAttributeConfig("attr2") ...
public static ApplicationContextInitializer<ConfigurableApplicationContext> dynamicConfigPropertiesInitializer() { return appCtx -> new DynamicConfigOperations(appCtx) .loadDynamicPropertySource() .ifPresent(source -> appCtx.getEnvironment().getPropertySources().addFirst(source)); ...
@Test void initializerAddsDynamicPropertySourceIfAllEnvVarsAreSet() throws Exception { Path propsFilePath = tmpDir.resolve("props.yaml"); Files.writeString(propsFilePath, SAMPLE_YAML_CONFIG, StandardOpenOption.CREATE); MutablePropertySources propertySources = new MutablePropertySources(); propertySou...
@Override /** * Parses the given text to transform it to the desired target type. * @param text The LLM output in string format. * @return The parsed output in the desired target type. */ public T convert(@NonNull String text) { try { // Remove leading and trailing whitespace text = text.trim(); /...
@Test public void convertClassTypeWithJsonAnnotations() { var converter = new BeanOutputConverter<>(TestClassWithJsonAnnotations.class); var testClass = converter.convert("{ \"string_property\": \"some value\" }"); assertThat(testClass.getSomeString()).isEqualTo("some value"); }
@Override public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) { if (client.getId() != null) { // if it's not null, it's already been saved, this is an error throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId()); } if (client.getRegisteredRedi...
@Test(expected = IllegalArgumentException.class) public void saveNewClient_blacklisted() { ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); Mockito.when(client.getId()).thenReturn(null); String badUri = "badplace.xxx"; Mockito.when(blacklistedSiteService.isBlacklisted(badUri)).thenRetur...
public File getDatabaseFile(String filename) { File dbFile = null; if (filename != null && filename.trim().length() > 0) { dbFile = new File(filename); } if (dbFile == null || dbFile.isDirectory()) { dbFile = new File(new AndroidContextUtil().getDatabasePath("logback.db")); } return ...
@Test public void dirAsFilenameResultsInDefault() throws IOException { final File file = appender.getDatabaseFile(tmp.newFolder().getAbsolutePath()); assertThat(file, is(notNullValue())); assertThat(file.getName(), is("logback.db")); }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatMap() { final SqlMap map = SqlTypes.map(SqlTypes.INTEGER, SqlTypes.BIGINT); assertThat(ExpressionFormatter.formatExpression(new Type(map)), equalTo("MAP<INTEGER, BIGINT>")); }
public static Token of(TokenDomain domain, String secretTokenString) { return new Token(domain, secretTokenString); }
@Test void tokens_are_equality_comparable() { var td1 = TokenDomain.of("hash 1"); var td2 = TokenDomain.of("hash 2"); var td1_t1 = Token.of(td1, "foo"); var td1_t2 = Token.of(td1, "foo"); var td1_t3 = Token.of(td1, "bar"); var td2_t1 = Token.of(td2, "foo"); /...
public static Validator validUrl() { return (name, val) -> { if (!(val instanceof String)) { throw new IllegalArgumentException("validator should only be used with STRING defs"); } try { new URL((String)val); } catch (final Exception e) { throw new ConfigException(nam...
@Test public void shouldNotThrowOnValidURL() { // Given: final Validator validator = ConfigValidators.validUrl(); // When: validator.ensureValid("propName", "http://valid:25896/somePath"); // Then: did not throw. }
static URITypes findURIType(final StringReader reader) { final StringReader copy = reader.copy(); if(!copy.endOfString()) { char c = (char) copy.read(); if(c == '/') { reader.skip(1); if(!copy.endOfString()) { c = (char) copy.re...
@Test public void testFindUriType() { final Map<String, HostParser.URITypes> tests = ImmutableMap.<String, HostParser.URITypes>builder() .put("/path", HostParser.URITypes.Absolute) .put("user@domain/path", HostParser.URITypes.Rootless) .put("//user@domain.tld:port/path", ...
public static OffsetBasedPagination forOffset(int offset, int pageSize) { checkArgument(offset >= 0, "offset must be >= 0"); checkArgument(pageSize >= 1, "page size must be >= 1"); return new OffsetBasedPagination(offset, pageSize); }
@Test void forOffset_whenNegativePageSize_shouldfailsWithIAE() { assertThatThrownBy(() -> OffsetBasedPagination.forOffset(1, -1)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("page size must be >= 1"); }
@Udf public String trim( @UdfParameter( description = "The string to trim") final String input) { if (input == null) { return null; } return input.trim(); }
@Test public void shouldReturnEmptyForWhitespaceInput() { final String result = udf.trim(" \t "); assertThat(result, is("")); }