focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public String getProgram() { return program; }
@Test public void testRpcCallCacheConstructor(){ RpcCallCache cache = new RpcCallCache("test", 100); assertEquals("test", cache.getProgram()); }
@VisibleForTesting void validateOldPassword(Long id, String oldPassword) { AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); } if (!isPasswordMatch(oldPassword, user.getPassword())) { throw exception(USER_PASSW...
@Test public void testValidateOldPassword_passwordFailed() { // mock 数据 AdminUserDO user = randomAdminUserDO(); userMapper.insert(user); // 准备参数 Long id = user.getId(); String oldPassword = user.getPassword(); // 调用,校验异常 assertServiceException(() -> u...
@VisibleForTesting ExportResult<PhotosContainerResource> exportAlbums( TokensAndUrlAuthData authData, Optional<PaginationData> paginationData, UUID jobId) throws IOException, InvalidTokenException, PermissionDeniedException { Optional<String> paginationToken = Optional.empty(); if (paginationData....
@Test public void exportAlbumFirstSet() throws IOException, InvalidTokenException, PermissionDeniedException { setUpSingleAlbum(); when(albumListResponse.getNextPageToken()).thenReturn(ALBUM_TOKEN); // Run test ExportResult<PhotosContainerResource> result = googlePhotosExporter.exportAlbums(n...
public int generate(Class<? extends CustomResource> crdClass, Writer out) throws IOException { ObjectNode node = nf.objectNode(); Crd crd = crdClass.getAnnotation(Crd.class); if (crd == null) { err(crdClass + " is not annotated with @Crd"); } else { node.put("apiV...
@Test void simpleTestWithErrors() throws IOException { CrdGenerator crdGenerator = new CrdGenerator(KubeVersion.V1_16_PLUS, ApiVersion.V1, CrdGenerator.YAML_MAPPER, emptyMap(), crdGeneratorReporter, emptyList(), null, null, new CrdGenerator.NoneConversionStrategy(), null); ...
public Message createMessage(String messageString) { Message message; try { Map<String, Object> map = objectMapper.readValue(messageString, Map.class); if (!map.containsKey("_id")) { map.put("_id", UUID.randomUUID().toString()); } final Str...
@Test void createMessage() { String notAJsonMessage = "{Not a json message}"; Message result = ruleSimulator.createMessage(notAJsonMessage); Assertions.assertEquals(result.getMessage(), notAJsonMessage); }
public CodegenTableDO buildTable(TableInfo tableInfo) { CodegenTableDO table = CodegenConvert.INSTANCE.convert(tableInfo); initTableDefault(table); return table; }
@Test public void testBuildTable() { // 准备参数 TableInfo tableInfo = mock(TableInfo.class); // mock 方法 when(tableInfo.getName()).thenReturn("system_user"); when(tableInfo.getComment()).thenReturn("用户"); // 调用 CodegenTableDO table = codegenBuilder.buildTable(tab...
public List<PluginInfo> getExtensionInfos() { return new ArrayList<>(this); }
@Test public void shouldGetAllIndividualExtensionInfos() { NotificationPluginInfo notificationPluginInfo = new NotificationPluginInfo(null, null); PluggableTaskPluginInfo pluggableTaskPluginInfo = new PluggableTaskPluginInfo(null, null, null); CombinedPluginInfo pluginInfo = new CombinedPlu...
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { metadata.set(Metadata.CONTENT_TYPE, XLF_CONTENT_TYPE.toString()); final XHTMLContentHandler xhtml = new XHTMLCont...
@Test public void testXLIFF12() throws Exception { try (InputStream input = getResourceAsStream("/test-documents/testXLIFF12.xlf")) { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); new XLIFF12Parser().parse(input, handler, metadata,...
@Override public String getContextName() { return contextName; }
@Test public void testGetContextName() { assertEquals(contextName, defaultSnmpv3Device.getContextName()); }
@Override public boolean supportsSubqueriesInQuantifieds() { return false; }
@Test void assertSupportsSubqueriesInQuantifieds() { assertFalse(metaData.supportsSubqueriesInQuantifieds()); }
public RuntimeOptionsBuilder parse(Class<?> clazz) { RuntimeOptionsBuilder args = new RuntimeOptionsBuilder(); for (Class<?> classWithOptions = clazz; hasSuperClass( classWithOptions); classWithOptions = classWithOptions.getSuperclass()) { CucumberOptions options = requireNonNul...
@Test void create_with_glue() { RuntimeOptions runtimeOptions = parser().parse(ClassWithGlue.class).build(); assertThat(runtimeOptions.getGlue(), contains(uri("classpath:/app/features/user/registration"), uri("classpath:/app/features/hooks"))); }
static ByteBuffer fromEncodedKey(ByteString encodedKey) { return ByteBuffer.wrap(encodedKey.toByteArray()); }
@Test @SuppressWarnings("ByteBufferBackingArray") public void testFromEncodedKey() { ByteString input = ByteString.copyFrom("hello world".getBytes(StandardCharsets.UTF_8)); ByteBuffer encodedKey = FlinkKeyUtils.fromEncodedKey(input); assertThat(encodedKey.array(), is(input.toByteArray())); }
@Override public Object getConfig(String key) { return SOURCE.get(key); }
@Test public void getConfig() { final Object config = source.getConfig(OriginConfigDisableSource.ZK_CONFIG_CENTER_ENABLED); Assert.assertNotNull(config); Assert.assertTrue(config instanceof Boolean); Assert.assertEquals(config, false); }
@Override protected Object createObject(ValueWrapper<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) { return fillBean(initialInstance, className, params, classLoader); }
@Test public void createObject() { Map<List<String>, Object> params = new HashMap<>(); params.put(List.of("firstName"), "TestName"); params.put(List.of("age"), 10); ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params); Object objectRaw = runnerHelper....
public void isInStrictOrder() { isInStrictOrder(Ordering.natural()); }
@Test public void isInStrictOrderFailure() { expectFailureWhenTestingThat(asList(1, 2, 2, 4)).isInStrictOrder(); assertFailureKeys( "expected to be in strict order", "but contained", "followed by", "full contents"); assertFailureValue("but contained", "2"); assertFailureValue("followed by", "2...
public static <V> Read<V> read() { return new AutoValue_SparkReceiverIO_Read.Builder<V>().build(); }
@Test public void testReadFromReceiverByteBufferData() { ReceiverBuilder<String, ByteBufferDataReceiver> receiverBuilder = new ReceiverBuilder<>(ByteBufferDataReceiver.class).withConstructorArgs(); SparkReceiverIO.Read<String> reader = SparkReceiverIO.<String>read() .withGetOffsetF...
public static DNMappingAddress dnMappingAddress(String dn) { return new DNMappingAddress(dn); }
@Test public void testDnMappingAddressMethod() { String dn = "1"; MappingAddress mappingAddress = MappingAddresses.dnMappingAddress(dn); DNMappingAddress dnMappingAddress = checkAndConvert(mappingAddress, MappingAddress.Type.DN, ...
@VisibleForTesting static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) { return createStreamExecutionEnvironment( options, MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()), options.getFlinkConfDir()); }
@Test public void shouldSetMaxParallelismStreaming() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setRunner(TestFlinkRunner.class); options.setMaxParallelism(42); StreamExecutionEnvironment sev = FlinkExecutionEnvironments.createStreamExecutionEnvironment(options); ...
@Override public Object getValue(final int columnIndex, final Class<?> type) throws SQLException { if (boolean.class == type) { return resultSet.getBoolean(columnIndex); } if (byte.class == type) { return resultSet.getByte(columnIndex); } if (short.cla...
@Test void assertGetValueByBigDecimal() throws SQLException { ResultSet resultSet = mock(ResultSet.class); when(resultSet.getBigDecimal(1)).thenReturn(new BigDecimal("0")); assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, BigDecimal.class), is(new BigDecimal("0"))); }
public final long getServerId() { return serverId; }
@Test public void getServerIdOutputZero() { // Arrange final LogHeader objectUnderTest = new LogHeader(0); // Act final long actual = objectUnderTest.getServerId(); // Assert result Assert.assertEquals(0L, actual); }
@Override public void onCreating(AbstractJob job) { JobDetails jobDetails = job.getJobDetails(); Optional<Job> jobAnnotation = getJobAnnotation(jobDetails); setJobName(job, jobAnnotation); setAmountOfRetries(job, jobAnnotation); setLabels(job, jobAnnotation); }
@Test void testDisplayNameWithAnnotationUsingJobParametersAndMDCVariablesThatDoNotExist() { MDC.put("key-not-used-in-annotation", "1"); Job job = anEnqueuedJob() .withoutName() .withJobDetails(jobDetails() .withClassName(TestService.class) ...
public abstract Map<String, String> properties(final Map<String, String> defaultProperties, final long additionalRetentionMs);
@Test public void shouldAugmentRetentionMsWithWindowedChangelog() { final WindowedChangelogTopicConfig topicConfig = new WindowedChangelogTopicConfig("name", Collections.emptyMap(), 10); assertEquals("30", topicConfig.properties(Collections.emptyMap(), 20).get(TopicConfig.RETENTION_MS_CONFIG)); ...
static void populateJavaParserDTOAndSourcesMap(final JavaParserDTO toPopulate, final Map<String, String> sourcesMap, final NodeNamesDTO nodeNamesDTO, final List<Field<...
@Test void populateJavaParserDTOAndSourcesMap() { boolean isRoot = true; Map<String, String> sourcesMap = new HashMap<>(); KiePMMLNodeFactory.NodeNamesDTO nodeNamesDTO = new KiePMMLNodeFactory.NodeNamesDTO(nodeRoot, createNodeClassName(), null, 1.0); K...
public synchronized void reload(long checkpointId) { this.accCkp += 1; if (this.accCkp > 1) { // do not clean the new file assignment state for the first checkpoint, // this #reload calling is triggered by checkpoint success event, the coordinator // also relies on the checkpoint success event...
@Test public void testWriteProfileReload() throws Exception { WriteProfile writeProfile = new WriteProfile(writeConfig, context); List<SmallFile> smallFiles1 = writeProfile.getSmallFiles("par1"); assertTrue(smallFiles1.isEmpty(), "Should have no small files"); TestData.writeData(TestData.DATA_SET_INS...
@Override public AppTimeoutsInfo getAppTimeouts(HttpServletRequest hsr, String appId) throws AuthorizationException { try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); AppTimeoutsInfo appTimeoutsInfo = interceptor.get...
@Test public void testGetAppTimeouts() throws IOException, InterruptedException { // Generate ApplicationId information ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId(appId.toS...
@Override public BaseCombineOperator run() { try (InvocationScope ignored = Tracing.getTracer().createScope(CombinePlanNode.class)) { return getCombineOperator(); } }
@Test public void testPlanNodeThrowException() { List<PlanNode> planNodes = new ArrayList<>(); for (int i = 0; i < 20; i++) { planNodes.add(() -> { throw new RuntimeException("Inner exception message."); }); } _queryContext.setEndTimeMs(System.currentTimeMillis() + Server.DEFAULT_Q...
@Override public long get(long key) { return super.get0(key, 0); }
@Test(expected = AssertionError.class) @RequireAssertEnabled public void testGet_whenDisposed() { hsa.dispose(); hsa.get(1); }
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldCreateUdfFactoryWithInternalPathWhenInternal() { final UdfFactory substring = FUNC_REG.getUdfFactory(FunctionName.of("substring")); assertThat(substring.getMetadata().getPath(), equalTo(KsqlScalarFunction.INTERNAL_PATH)); }
public static StateRequestHandler delegateBasedUponType( EnumMap<StateKey.TypeCase, StateRequestHandler> handlers) { return new StateKeyTypeDelegatingStateRequestHandler(handlers); }
@Test public void testDelegatingStateHandlerDelegates() throws Exception { StateRequestHandler mockHandler = Mockito.mock(StateRequestHandler.class); StateRequestHandler mockHandler2 = Mockito.mock(StateRequestHandler.class); EnumMap<StateKey.TypeCase, StateRequestHandler> handlers = new EnumMap<>...
public JsonNode resolve(JsonNode tree, String path, String refFragmentPathDelimiters) { return resolve(tree, new ArrayList<>(asList(split(path, refFragmentPathDelimiters)))); }
@Test(expected = IllegalArgumentException.class) public void missingPathThrowsIllegalArgumentException() { ObjectNode root = new ObjectMapper().createObjectNode(); resolver.resolve(root, "#/a/b/c", "#/."); }
@Override public void deleteRewardActivity(Long id) { // 校验存在 RewardActivityDO dbRewardActivity = validateRewardActivityExists(id); if (!dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 未关闭的活动,不能删除噢 throw exception(REWARD_ACTIVITY_DELETE_FA...
@Test public void testDeleteRewardActivity_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> rewardActivityService.deleteRewardActivity(id), REWARD_ACTIVITY_NOT_EXISTS); }
@Override public ByteBuf asReadOnly() { return newSharedLeakAwareByteBuf(super.asReadOnly()); }
@Test public void testWrapReadOnly() { assertWrapped(newBuffer(8).asReadOnly()); }
public Connection connection(Connection connection) { // It is common to implement both interfaces if (connection instanceof XAConnection) { return xaConnection((XAConnection) connection); } return TracingConnection.create(connection, this); }
@Test void connection_wrapsInput() { assertThat(jmsTracing.connection(mock(Connection.class))) .isInstanceOf(TracingConnection.class); }
@Override public SchemaResult getValueSchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, false); }
@Test public void shouldReturnSchemaFromGetValueSchemaIfFound() { // When: final SchemaResult result = supplier.getValueSchema(Optional.of(TOPIC_NAME), Optional.empty(), expectedFormat, SerdeFeatures.of()); // Then: assertThat(result.schemaAndId, is(not(Optional.empty()))); assertThat(res...
@Override public void handle(Callback[] callbacks) throws UnsupportedCallbackException, IOException { for (Callback callBack : callbacks) { if (callBack instanceof NameCallback nameCallback) { // Handles username callback nameCallback.setName(name); } else if (callBack instanceof Passw...
@Test public void unsupportedCallback() { assertThatThrownBy(() -> { new CallbackHandlerImpl("tester", "secret").handle(new Callback[] {mock(Callback.class)}); }) .isInstanceOf(UnsupportedCallbackException.class); }
public static void generateNodeTableMapping(Set<NodeDetails> nodeDetails, String filePath) throws IOException { List<String> entries = new ArrayList<>(); for (NodeDetails nodeDetail : nodeDetails) { if (nodeDetail.getHostname().contains("/")) { String hostname = nodeDetail.getHostname(); ...
@Test public void testGenerateNodeTableMapping() throws Exception { Set<NodeDetails> nodes = SLSUtils.generateNodes(3, 3); File tempFile = File.createTempFile("testslsutils", ".tmp"); tempFile.deleteOnExit(); String fileName = tempFile.getAbsolutePath(); SLSUtils.generateNodeTableMapping(nodes, fi...
@SuppressWarnings("unchecked") public Future<Void> executeRunnable(final Runnable r) { return (Future<Void>) executor.submit(r::run); }
@Test public void testRunnableFails() throws Exception { ExecutorServiceFuturePool futurePool = new ExecutorServiceFuturePool(executorService); Future<Void> future = futurePool.executeRunnable(() -> { throw new IllegalStateException("deliberate"); }); interceptFuture(IllegalStateExceptio...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Search State"); try { setAttribute(protobuf, "State", getStateAsEnum().name()); completeNodeAttributes(protobuf); } catch (Exc...
@Test public void attributes_displays_exception_message_when_cause_null_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsStateSection underTest = new EsStateSection(esClientMock); when(esClientMock.clusterHealth(any())).thenThrow(new RuntimeException("RuntimeException with no cause"))...
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowCreateExternalCatalogWithMask() throws AnalysisException, DdlException { // More mask logic please write in CredentialUtilTest new MockUp<CatalogMgr>() { @Mock public Catalog getCatalogByName(String name) { Map<String, String> propert...
@Override public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) { if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) { return resolveRequestConfig(propertyName); } else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX) && !propertyName.starts...
@Test public void shouldFindUnknownProducerPropertyIfNotStrict() { // Given: final String configName = StreamsConfig.PRODUCER_PREFIX + "custom.interceptor.config"; // Then: assertThat(resolver.resolve(configName, false), is(unresolvedItem(configName))); }
void restoreBatch(final Collection<ConsumerRecord<byte[], byte[]>> records) { // compute the observed stream time at the end of the restore batch, in order to speed up // restore by not bothering to read from/write to segments which will have expired by the // time the restoration process is co...
@Test public void shouldNotRestoreExpired() { final List<DataRecord> records = new ArrayList<>(); records.add(new DataRecord("k", "v", HISTORY_RETENTION + 10)); records.add(new DataRecord("k1", "v1", HISTORY_RETENTION + 10 - GRACE_PERIOD)); // grace period has not elapsed records.add...
public static ResolvedSchema removeTimeAttributeFromResolvedSchema( ResolvedSchema resolvedSchema) { return new ResolvedSchema( resolvedSchema.getColumns().stream() .map(col -> col.copy(DataTypeUtils.removeTimeAttribute(col.getDataType()))) ...
@Test void testRemoveTimeAttribute() { DataType rowTimeType = DataTypeUtils.replaceLogicalType( DataTypes.TIMESTAMP(3), new TimestampType(true, TimestampKind.ROWTIME, 3)); ResolvedSchema schema = new ResolvedSchema( Arra...
@Deprecated @NonNull public static WriteRequest newWriteRequest( @Nullable final BluetoothGattCharacteristic characteristic, @Nullable final byte[] value) { return new WriteRequest(Type.WRITE, characteristic, value, 0, value != null ? value.length : 0, characteristic != null ? characteristic.get...
@Test public void split_basic() { final WriteRequest request = Request.newWriteRequest(characteristic, text.getBytes(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) .split(); chunk = request.getData(MTU); // Verify the chunk assertNotNull(chunk); assertEquals(MTU - 3, chunk.length); final String ex...
void handleSegmentWithCopySegmentFinishedState(Long startOffset, RemoteLogSegmentId remoteLogSegmentId, Long leaderEpochEndOffset) { // If there are duplicate segments uploaded due to leader-election, then mark them as unreferenced. // Duplicate segment...
@Test void handleSegmentWithCopySegmentFinishedState() { RemoteLogSegmentId segmentId1 = new RemoteLogSegmentId(tpId, Uuid.randomUuid()); RemoteLogSegmentId segmentId2 = new RemoteLogSegmentId(tpId, Uuid.randomUuid()); epochState.handleSegmentWithCopySegmentFinishedState(10L, segmentId1, 100...
@Override public List<Node> sniff(List<Node> nodes) { if (attribute == null || value == null) { return nodes; } return nodes.stream() .filter(node -> nodeMatchesFilter(node, attribute, value)) .collect(Collectors.toList()); }
@Test void worksWithEmptyNodesListIfFilterIsSet() throws Exception { final List<Node> nodes = Collections.emptyList(); final NodesSniffer nodesSniffer = new FilteredOpenSearchNodesSniffer("rack", "42"); assertThat(nodesSniffer.sniff(nodes)).isEqualTo(nodes); }
@Override public UpdateFeaturesResponse getErrorResponse(int throttleTimeMs, Throwable e) { return UpdateFeaturesResponse.createWithErrors( ApiError.fromThrowable(e), Collections.emptyMap(), throttleTimeMs ); }
@Test public void testGetErrorResponse() { UpdateFeaturesRequestData.FeatureUpdateKeyCollection features = new UpdateFeaturesRequestData.FeatureUpdateKeyCollection(); features.add(new UpdateFeaturesRequestData.FeatureUpdateKey() .setFeature("foo") .setMaxVersionL...
@Override public RestLiResponseData<CreateResponseEnvelope> buildRestLiResponseData(Request request, RoutingResult routingResult, Object result, Map<String, Strin...
@Test(dataProvider = "returnEntityData") public void testReturnEntityInBuildRestLiResponseData(CreateResponse createResponse, boolean isReturnEntityRequested, boolean expectEntityReturned) throws URISyntaxException { ServerResourceContext mockContext = EasyMock.createMock(ServerResourceContext.class); EasyM...
@Override public Size.Output run(RunContext runContext) throws Exception { StorageInterface storageInterface = ((DefaultRunContext)runContext).getApplicationContext().getBean(StorageInterface.class); URI render = URI.create(runContext.render(this.uri)); Long size = storageInterface.getAttri...
@Test void run() throws Exception { RunContext runContext = runContextFactory.of(); final Long size = 42L; byte[] randomBytes = new byte[size.intValue()]; new Random().nextBytes(randomBytes); URI put = storageInterface.put( null, new URI("/file/stora...
public List<String> getUuids() { return this.stream().map(EnvironmentAgentConfig::getUuid).collect(toList()); }
@Test void shouldGetAllAgentUUIDs(){ EnvironmentAgentConfig envAgentConfig1 = new EnvironmentAgentConfig("uuid1"); EnvironmentAgentConfig envAgentConfig2 = new EnvironmentAgentConfig("uuid2"); EnvironmentAgentConfig envAgentConfig3 = new EnvironmentAgentConfig("uuid3"); envAgentsConf...
@Override public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) { if (notificationExtension.canHandlePlugin(pluginDescriptor.id())) { notificationPluginRegistry.deregisterPlugin(pluginDescriptor.id()); notificationPluginRegistry.removePluginInterests(pluginDescriptor.id());...
@Test public void shouldUnregisterPluginOnPluginUnLoad() { NotificationPluginRegistrar notificationPluginRegistrar = new NotificationPluginRegistrar(pluginManager, notificationExtension, notificationPluginRegistry); notificationPluginRegistrar.pluginUnLoaded(GoPluginDescriptor.builder().id(PLUGIN_I...
@Override public void start() { if (realm != null) { try { LOG.info("Security realm: {}", realm.getName()); realm.init(); LOG.info("Security realm started"); } catch (RuntimeException e) { if (ignoreStartupFailure) { LOG.error("IGNORED - Security realm fails t...
@Test public void should_fail() { SecurityRealm realm = spy(new AlwaysFailsRealm()); settings.setProperty("sonar.security.realm", realm.getName()); try { new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}).start(); fail(); } catch (SonarException e) { assertTh...
@Override public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) { String taskType = MergeRollupTask.TASK_TYPE; List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>(); for (TableConfig tableConfig : tableConfigs) { if (!validate(tableConfig, taskType)) { continue; ...
@Test public void testSegmentSelectionMultiLevels() { Map<String, Map<String, String>> taskConfigsMap = new HashMap<>(); Map<String, String> tableTaskConfigs = new HashMap<>(); tableTaskConfigs.put("daily.mergeType", "concat"); tableTaskConfigs.put("daily.bufferTimePeriod", "2d"); tableTaskConfigs...
@Override public PageResult<LoginLogDO> getLoginLogPage(LoginLogPageReqVO pageReqVO) { return loginLogMapper.selectPage(pageReqVO); }
@Test public void testGetLoginLogPage() { // mock 数据 LoginLogDO loginLogDO = randomPojo(LoginLogDO.class, o -> { o.setUserIp("192.168.199.16"); o.setUsername("wang"); o.setResult(SUCCESS.getResult()); o.setCreateTime(buildTime(2021, 3, 6)); });...
private void setMode(Request req) { dispatchRpcRequest(req, () -> { String suppliedMode = req.parameters().get(0).asString(); String[] s = new String[2]; try { proxyServer.setMode(suppliedMode); s[0] = "0"; s[1] = "success"; ...
@Test void testRpcMethodUpdateSources() throws ListenFailedException { reset(); Request req = new Request("updateSources"); String spec1 = "tcp/a:19070"; String spec2 = "tcp/b:19070"; req.parameters().add(new StringValue(spec1 + "," + spec2)); client.invoke(req); ...
@Override public String toString() { return url.toString(); }
@Test void testToString() { Statistics statistics = new Statistics(new ServiceConfigURL("dubbo", "10.20.153.10", 0)); statistics.setApplication("demo"); statistics.setMethod("findPerson"); statistics.setServer("10.20.153.10"); statistics.setGroup("unit-test"); statist...
@Override public PullResult pull(MessageQueue mq, String subExpression, long offset, int maxNums) throws MQClientException, RemotingException, MQBrokerException, InterruptedException { return this.defaultMQPullConsumerImpl.pull(queueWithNamespace(mq), subExpression, offset, maxNums); }
@Test public void testPullMessage_Success() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock mock) throws Throwable { PullMessageRequestHeader requestHeader = mock.getArgument(1); return createPullResult(reques...
@Override public void close() throws IOException { if (closed) { return; } super.close(); this.closed = true; if (stream != null) { stream.close(); } }
@Test public void testMultipleClose() throws IOException { DataLakeFileClient fileClient = AZURITE_CONTAINER.fileClient(randomPath()); ADLSOutputStream stream = new ADLSOutputStream(fileClient, azureProperties, MetricsContext.nullMetrics()); stream.close(); stream.close(); }
@Override @Transactional(rollbackFor = Exception.class) public void updateJob(JobSaveReqVO updateReqVO) throws SchedulerException { validateCronExpression(updateReqVO.getCronExpression()); // 1.1 校验存在 JobDO job = validateJobExists(updateReqVO.getId()); // 1.2 只有开启状态,才可以修改.原因是,如果出...
@Test public void testUpdateJob_jobNotExists(){ // 准备参数 JobSaveReqVO reqVO = randomPojo(JobSaveReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); // 调用,并断言异常 assertServiceException(() -> jobService.updateJob(reqVO), JOB_NOT_EXISTS); }
@VisibleForTesting void checkMaxEligible() { // If we have too many eligible apps, remove the newest ones first if (maxEligible > 0 && eligibleApplications.size() > maxEligible) { if (verbose) { LOG.info("Too many applications (" + eligibleApplications .size() + "...
@Test(timeout = 10000) public void testCheckMaxEligible() throws Exception { Configuration conf = new Configuration(); HadoopArchiveLogs.AppInfo app1 = new HadoopArchiveLogs.AppInfo( ApplicationId.newInstance(CLUSTER_TIMESTAMP, 1).toString(), USER); app1.setFinishTime(CLUSTER_TIMESTAMP - 5); H...
public static FunctionTypeInfo getFunctionTypeInfo( final ExpressionTypeManager expressionTypeManager, final FunctionCall functionCall, final UdfFactory udfFactory, final Map<String, SqlType> lambdaMapping ) { // CHECKSTYLE_RULES.ON: CyclomaticComplexity final List<Expression> argument...
@Test public void shouldResolveFunctionWithoutLambdas() { // Given: givenUdfWithNameAndReturnType("NoLambdas", SqlTypes.STRING); when(function.parameters()).thenReturn( ImmutableList.of(ParamTypes.STRING)); final FunctionCall expression = new FunctionCall(FunctionName.of("NoLambdas"), Immutab...
@Override public Object evaluate(final ProcessingDTO processingDTO) { return getFromPossibleSources(name, processingDTO) .orElse(mapMissingTo); }
@Test void evaluateFromKiePMMLNameValues() { final Object value = 234.45; final List<KiePMMLNameValue> kiePMMLNameValues = Collections.singletonList(new KiePMMLNameValue(FIELD_NAME, value)); ...
@Override public Integer call() throws Exception { super.call(); if (this.pluginsPath == null) { throw new CommandLine.ParameterException(this.spec.commandLine(), "Missing required options '--plugins' " + "or environment variable 'KESTRA_PLUGINS_PATH" ); ...
@Test void rangeVersion() throws IOException { Path pluginsPath = Files.createTempDirectory(PluginInstallCommandTest.class.getSimpleName()); pluginsPath.toFile().deleteOnExit(); try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { // SNAPSHO...
@Override public void batchRegisterInstance(Service service, List<Instance> instances, String clientId) { Service singleton = ServiceManager.getInstance().getSingleton(service); if (!singleton.isEphemeral()) { throw new NacosRuntimeException(NacosException.INVALID_PARAM, ...
@Test void testBatchRegisterAndDeregisterInstance() throws Exception { // test Batch register instance Instance instance1 = new Instance(); instance1.setEphemeral(true); instance1.setIp("127.0.0.1"); instance1.setPort(9087); instance1.setHealthy(true); ...
public Optional<PushEventDto> raiseEventOnIssue(String projectUuid, DefaultIssue currentIssue) { var currentIssueComponentUuid = currentIssue.componentUuid(); if (currentIssueComponentUuid == null) { return Optional.empty(); } var component = treeRootHolder.getComponentByUuid(currentIssueComponen...
@Test public void raiseEventOnIssue_whenComponentUuidNull_shouldSkipEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setComponentUuid(null); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); }
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testOutlineCsv() { run("outline-csv.feature"); }
static RuntimeException handleException(Throwable e) { if (e instanceof OutOfMemoryError error) { OutOfMemoryErrorDispatcher.onOutOfMemory(error); throw error; } if (e instanceof Error error) { throw error; } if (e instanceof HazelcastSerializa...
@Test(expected = Error.class) public void testHandleException_otherError() { SerializationUtil.handleException(new UnknownError()); }
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STATE: handleLiteralState(c,...
@Test public void testEscapedParanteheses() throws ScanException { { List<Token> tl = new TokenStream("\\(%h\\)").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(new Token(Token.LITERAL, "(")); witness.add(Token.PERCENT_TOKEN); witness.add(new Token(Token.SIMPLE...
@Override public E putIfAbsent(String key, E value) { return entryMap.putIfAbsent(key, value); }
@Test(expected = NullPointerException.class) public void shouldThrowNPEWhenKeyIsNull() { inMemoryRegistryStore.putIfAbsent(null, DEFAULT_CONFIG_VALUE); }
public PaginationContext createPaginationContext(final Collection<ExpressionSegment> expressions, final ProjectionsContext projectionsContext, final List<Object> params) { Optional<String> rowNumberAlias = findRowNumberAlias(projectionsContext); if (!rowNumberAlias.isPresent()) { return new ...
@Test void assertCreatePaginationContextWhenRowNumberAliasIsPresentAndRowNumberPredicatesIsEmpty() { Projection projectionWithRowNumberAlias = new ColumnProjection(null, ROW_NUMBER_COLUMN_NAME, ROW_NUMBER_COLUMN_ALIAS, mock(DatabaseType.class)); ProjectionsContext projectionsContext = new Projection...
public static <T> boolean isNotEmpty(T[] array) { return null != array && array.length > 0; }
@Test public void isNotEmpty() { final Object[] array = {}; Assert.assertFalse(CollectionKit.isNotEmpty(array)); final Object[] array2 = {null}; Assert.assertTrue(CollectionKit.isNotEmpty(array2)); final Object[] array3 = null; Assert.assertFalse(CollectionKit.isNotEmpty(array3)); final...
@Override public String execute(CommandContext commandContext, String[] args) { StringBuilder result = new StringBuilder(); result.append(listProvider()); result.append(listConsumer()); return result.toString(); }
@Test void testExecute() { Ls ls = new Ls(frameworkModel); String result = ls.execute(Mockito.mock(CommandContext.class), new String[0]); System.out.println(result); /** * As Provider side: * +--------------------------------+---+ * | Provider Service ...
@Override public boolean supportsColumnAliasing() { return false; }
@Test void assertSupportsColumnAliasing() { assertFalse(metaData.supportsColumnAliasing()); }
@Override public void checkBeforeUpdate(final AlterReadwriteSplittingRuleStatement sqlStatement) { ReadwriteSplittingRuleStatementChecker.checkAlteration(database, sqlStatement.getRules(), rule.getConfiguration()); }
@Test void assertCheckSQLStatementWithoutExistedResources() { when(resourceMetaData.getNotExistedDataSources(any())).thenReturn(Collections.singleton("read_ds_0")); ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class); when(rule.getConfiguration()).thenReturn(createCurrentRuleCon...
@PublicAPI(usage = ACCESS) public JavaClasses importUrl(URL url) { return importUrls(singletonList(url)); }
@Test public void imports_simple_class_details() { JavaClasses classes = new ClassFileImporter().importUrl(getClass().getResource("testexamples/simpleimport")); assertThat(classes.get(ClassToImportOne.class)) .isFullyImported(true) .matches(ClassToImportOne.class) ...
@Override public Address translate(Address address) throws Exception { if (address == null) { return null; } // if it is inside cloud, return private address otherwise we need to translate it. if (!usePublic) { return address; } Address publi...
@Test public void testTranslate_dontUsePublic() throws Exception { Address privateAddress = new Address("10.0.0.1", 5701); Address publicAddress = new Address("198.51.100.1", 5701); RemoteAddressProvider provider = new RemoteAddressProvider(() -> Collections.singletonMap(privateAddress, publ...
public EventWithContext addEventContext(Event event) { return toBuilder().eventContext(event).build(); }
@Test public void addEventContext() { final Event event = new TestEvent(); final Event eventContext = new TestEvent(); final EventWithContext withContext = EventWithContext.builder() .event(event) .build(); final EventWithContext withContext1 = withCo...
public static boolean isFileNameValid(String fileName) { // Trim the trailing slash if there is one. if (fileName.endsWith("/")) fileName = fileName.substring(0, fileName.lastIndexOf('/') - 1); // Trim the leading slashes if there is any. if (fileName.contains("/")) fileName = fileName.substring(fileNa...
@Test public void testIsFileNameValid() { assertTrue(Operations.isFileNameValid("file.txt")); assertTrue(Operations.isFileNameValid("/storage/emulated/0/Documents/file.txt")); assertTrue(Operations.isFileNameValid("/system/etc/file.txt")); assertTrue(Operations.isFileNameValid("smb://127.0.0.1/trancel...
@Override public void apply(Project project) { checkGradleVersion(project); project.getPlugins().apply(JavaPlugin.class); // this HashMap will have a PegasusOptions per sourceSet project.getExtensions().getExtraProperties().set("pegasus", new HashMap<>()); // this map will extract PegasusOptio...
@Test public void testTaskTypes() { // Given/When: Pegasus Plugin is applied to a project. Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(PegasusPlugin.class); // Then: Validate the Copy/Sync Schema tasks are of the correct type. assertTrue(project.getTasks().getBy...
@VisibleForTesting protected List<UserDefinedJavaClassDef> orderDefinitions( List<UserDefinedJavaClassDef> definitions ) { List<UserDefinedJavaClassDef> orderedDefinitions = new ArrayList<>( definitions.size() ); List<UserDefinedJavaClassDef> transactions = definitions.stream() .filter( def -> d...
@Test public void oderDefinitionTest() throws Exception { String codeBlock1 = "public boolean processRow() {\n" + " return true;\n" + "}\n\n"; String codeBlock2 = "public boolean extraClassA() {\n" + " // Random comment\n" + " return true;\n" + "}\n\n"; String codeBl...
public static <T> T execute(Single<T> apiCall) { try { return apiCall.blockingGet(); } catch (HttpException e) { try { if (e.response() == null || e.response().errorBody() == null) { throw e; } String errorBody =...
@Test void executeParseUnknownProperties() { // error body contains one unknown property and no message String errorBody = "{\"error\":{\"unknown\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; HttpException httpException = createException(errorBody, 401)...
@Override @Nonnull public ProgressState call() { assert state != END : "already in terminal state"; progTracker.reset(); progTracker.notDone(); outbox.reset(); stateMachineStep(); return progTracker.toProgressState(); }
@Test public void when_closeBlocked_then_waitUntilDone() { processor.doneLatch = new CountDownLatch(1); ProcessorTasklet tasklet = createTasklet(ForkJoinPool.commonPool()); callUntil(tasklet, NO_PROGRESS); processor.doneLatch.countDown(); assertTrueEventually(() -> assertEqua...
@Override public ShardingAuditStrategyConfiguration swapToObject(final YamlShardingAuditStrategyConfiguration yamlConfig) { return new ShardingAuditStrategyConfiguration(yamlConfig.getAuditorNames(), yamlConfig.isAllowHintDisable()); }
@Test void assertSwapToObject() { YamlShardingAuditStrategyConfiguration yamlConfig = new YamlShardingAuditStrategyConfiguration(); yamlConfig.setAuditorNames(Collections.singletonList("audit_algorithm")); yamlConfig.setAllowHintDisable(false); YamlShardingAuditStrategyConfigurationS...
public byte[] generateAtRequest(DocumentType documentType, PolymorphType authorization, String sequenceNo, String reference) { final Certificate dvca = getDvca(documentType); final String subject = getAtSubject(documentType, dvca.getSubject(), sequenceNo); if ...
@Test public void shouldGenerateFirstATRequest() throws Exception { final HsmClient.KeyInfo keyInfo = new HsmClient.KeyInfo(); keyInfo.setPublicKey(Hex.decode("04" + "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS" + "SSSSSSSSSSSSSSSSSSSSSSSS...
@Override protected Release findLatestActiveRelease(String appId, String clusterName, String namespaceName, ApolloNotificationMessages clientMessages) { String messageKey = ReleaseMessageKeyGenerator.generate(appId, clusterName, namespaceName); String cacheKey = mes...
@Test public void testFindLatestActiveRelease() throws Exception { when(releaseMessageService.findLatestReleaseMessageForMessages(Lists.newArrayList(someKey))).thenReturn (someReleaseMessage); when(releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName)).thenReturn ...
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 validateSchemaRetrievalFailure() { Schema unknown = Schema.createFixed("unknown", null, null, 0); Schema unresolved = fooBarBaz.find("unknown", null); assertTrue(SchemaResolver.isUnresolvedSchema(unresolved)); assertEquals(unknown.getFullName(), SchemaResolver.getUnresolvedSchemaNam...
@Override public CreateTopicsResult createTopics(final Collection<NewTopic> newTopics, final CreateTopicsOptions options) { final Map<String, KafkaFutureImpl<TopicMetadataAndConfig>> topicFutures = new HashMap<>(newTopics.size()); final CreatableTopicCollec...
@Test public void testUnreachableBootstrapServer() throws Exception { // This tests the scenario in which the bootstrap server is unreachable for a short while, // which prevents AdminClient from being able to send the initial metadata request Cluster cluster = Cluster.bootstrap(singletonLi...
@Override public Num calculate(BarSeries series, Position position) { Num stdDevPnl = standardDeviationCriterion.calculate(series, position); if (stdDevPnl.isZero()) { return series.zero(); } // SQN = (Average (PnL) / StdDev(PnL)) * SquareRoot(NumberOfTrades) Num ...
@Test public void calculateWithLosingShortPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 110, 100, 105, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(1, series), Trade.sellAt(2, series), Trade.buyAt(3, ser...
@Deprecated public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) { return prune(segments, query, new SegmentPrunerStatistics()); }
@Test public void segmentsWithoutColumnAreInvalid() { SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf); IndexSegment indexSegment = mockIndexSegment(10, "col1", "col2"); SegmentPrunerStatistics stats = new SegmentPrunerStatistics(); List<IndexSegment> indexes = new ArrayList...
public static TableSchema toTableSchema(Schema schema) { return new TableSchema().setFields(toTableFieldSchema(schema)); }
@Test public void testToTableSchema_flat() { TableSchema schema = toTableSchema(FLAT_TYPE); assertThat( schema.getFields(), containsInAnyOrder( ID, VALUE, NAME, TIMESTAMP_VARIANT1, TIMESTAMP_VARIANT2, TIMESTAMP_VARIANT3, ...
@Override public Object toConnectRow(final Object ksqlData) { if (!(ksqlData instanceof Struct)) { return ksqlData; } final Schema schema = getSchema(); final Struct struct = new Struct(schema); Struct originalData = (Struct) ksqlData; Schema originalSchema = originalData.schema(); ...
@Test public void shouldTransformStructWithMapOfStructs() { // Given: final Schema innerStructSchemaWithoutOptional = getInnerStructSchema(false); final Schema innerStructSchemaWithOptional = getInnerStructSchema(true); // Physical Schema retrieved from SR final Schema schema = SchemaBuilder.stru...
public int lower(int v) { return Boundary.LOWER.apply(find(v)); }
@Test public void testLower() { SortedIntList l = new SortedIntList(5); l.add(0); l.add(5); l.add(10); assertEquals(2, l.lower(Integer.MAX_VALUE)); }
public String getQueueName(AsyncMockDefinition definition, EventMessage eventMessage) { // Produce service name part of topic name. String serviceName = definition.getOwnerService().getName().replace(" ", ""); serviceName = serviceName.replace("-", ""); // Produce version name part of topic nam...
@Test void testGetQueueNameWithPart() { AmazonSQSProducerManager producerManager = new AmazonSQSProducerManager(); Service service = new Service(); service.setName("Pastry orders API"); service.setVersion("0.1.0"); Operation operation = new Operation(); operation.setName("SUBSCR...
@Override public String toString() { return "AttributeConfig{" + "name='" + name + '\'' + "extractorClassName='" + extractorClassName + '\'' + '}'; }
@Test public void validToString() { AttributeConfig config = new AttributeConfig("iq", "com.test.IqExtractor"); String toString = config.toString(); assertThat(toString).contains("iq"); assertThat(toString).contains("com.test.IqExtractor"); }
@Deprecated public RequestTemplate method(String method) { checkNotNull(method, "method"); try { this.method = HttpMethod.valueOf(method); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("Invalid HTTP Method: " + method); } return this; }
@SuppressWarnings("deprecation") @Test void uriStuffedIntoMethod() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> new RequestTemplate().method("/path?queryParam={queryParam}")); assertThat(exception.getMessage()) .contains("Invalid HTTP Method: /path?queryParam={q...
public static <T> T execute(Single<T> apiCall) { try { return apiCall.blockingGet(); } catch (HttpException e) { try { if (e.response() == null || e.response().errorBody() == null) { throw e; } String errorBody =...
@Test void executeHappyPath() { CompletionResult expected = new CompletionResult(); Single<CompletionResult> single = Single.just(expected); CompletionResult actual = OpenAiService.execute(single); assertEquals(expected, actual); }
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> targetInvokers; if (routerConfig.isUseRequest...
@Test public void testGetTargetInvokersByGlobalRules() { // initialize the routing rule RuleInitializationUtils.initGlobalFlowMatchRules(); List<Object> invokers = new ArrayList<>(); ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0"); invokers.add(invoker1); ...
public static Map<String, ShardingSphereSchema> build(final GenericSchemaBuilderMaterial material) throws SQLException { return build(getAllTableNames(material.getRules()), material); }
@Test void assertLoadAllTables() throws SQLException { Collection<String> tableNames = Arrays.asList("data_node_routed_table1", "data_node_routed_table2"); when(MetaDataLoader.load(any())).thenReturn(createSchemaMetaDataMap(tableNames, material)); Map<String, ShardingSphereSchema> actual = G...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testRequestBodyEncoding() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(UrlEncodedResourceWithEncodings.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /things/search:\n" + " post:\n...
@Override public Set<Long> loadAllKeys() { long startNanos = Timer.nanos(); try { return delegate.loadAllKeys(); } finally { loadAllKeysProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void loadAllKeys() { Set<Long> keys = Set.of(1L, 2L); when(delegate.loadAllKeys()).thenReturn(keys); Set<Long> result = queueStore.loadAllKeys(); assertEquals(keys, result); assertProbeCalledOnce("loadAllKeys"); }
public static boolean equalContentsIgnoreOrder(Collection<?> c1, Collection<?> c2) { return c1.size() == c2.size() && c1.containsAll(c2); }
@Test public void testEqualContentsIgnoreOrder() { List<Integer> l2Copy = new ArrayList<>(); l2Copy.addAll(l2); shuffle(); assertTrue(CollectionUtil.equalContentsIgnoreOrder(l2, l2Copy)); assertFalse(CollectionUtil.equalContentsIgnoreOrder(l1, l2)); }