focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean appliesTo(Component project, @Nullable MetricEvaluationResult metricEvaluationResult) { return metricEvaluationResult != null && metricEvaluationResult.evaluationResult.level() != Measure.Level.OK && METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricEvaluationResult.condition.getMetric...
@Test public void should_not_change_quality_gate_if_new_lines_is_not_defined() { QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR); Component project = generateNewRootProject(); boolean result = underTest.appliesTo(project, metricEva...
@Override public int hashCode() { int result = type.hashCode(); result = 31 * result + newState.hashCode(); return result; }
@Test public void testHashCode() { assertEquals(clusterStateChange.hashCode(), clusterStateChange.hashCode()); assertEquals(clusterStateChange.hashCode(), clusterStateChangeSameAttributes.hashCode()); assumeDifferentHashCodes(); assertNotEquals(clusterStateChange.hashCode(), cluster...
public TrueTypeFont parse(RandomAccessRead randomAccessRead) throws IOException { RandomAccessReadDataStream dataStream = new RandomAccessReadDataStream(randomAccessRead); try (randomAccessRead) { return parse(dataStream); } catch (IOException ex) { ...
@Test void testPostTable() throws IOException { InputStream input = TestTTFParser.class.getResourceAsStream( "/ttf/LiberationSans-Regular.ttf"); assertNotNull(input); TTFParser parser = new TTFParser(); TrueTypeFont font = parser.parse(new RandomAccessReadBuffer(...
@Restricted(NoExternalUse.class) public boolean hasSymlink(OpenOption... openOptions) throws IOException { return false; }
@Test public void hasSymlink_AbstractBase() throws IOException { // This test checks the method's behavior in the abstract base class, // which generally does nothing. VirtualFile virtualRoot = new VirtualFileMinimalImplementation(tmp.getRoot()); assertFalse(virtualRoot.hasSymlink(Li...
public long higherFrameTs(long timestamp) { long tsPlusFrame = timestamp + frameSize; return sumHadOverflow(timestamp, frameSize, tsPlusFrame) ? addClamped(floorFrameTs(timestamp), frameSize) : floorFrameTs(tsPlusFrame); }
@Test public void when_higherOutOfRange_then_maxValue() { definition = new SlidingWindowPolicy(4, 2, 10); assertEquals(Long.MAX_VALUE, definition.higherFrameTs(Long.MAX_VALUE - 1)); assertEquals(Long.MIN_VALUE + 2, definition.higherFrameTs(Long.MIN_VALUE)); }
@Override public Graph toGraph(ConfigVariableExpander cve) throws InvalidIRException { Graph trueGraph = getTrueStatement().toGraph(cve); Graph falseGraph = getFalseStatement().toGraph(cve); // If there is nothing in the true or false sections of this if statement, // we can omit th...
@Test public void testIfWithOneTrueOneFalseStatement() throws InvalidIRException { ConfigVariableExpander cve = ConfigVariableExpander.withoutSecret(EnvironmentVariableProvider.defaultProvider()); PluginDefinition pluginDef = testPluginDefinition(); Statement trueStatement = new PluginStatem...
@Override public void lock() { try { lockInterruptibly(-1, null); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testIsLockedOtherThread() throws InterruptedException { RLock lock = redisson.getSpinLock("lock"); lock.lock(); Thread t = new Thread() { public void run() { RLock lock = redisson.getSpinLock("lock"); Assertions.assertTrue(lock.i...
protected double convertDuration(double duration) { return duration / durationFactor; }
@Test public void shouldConvertDurationToMillisecondsPrecisely() { assertEquals(2.0E-5, reporter.convertDuration(20), 0.0); }
@Bean("GlobalTempFolder") public TempFolder provide(ScannerProperties scannerProps, SonarUserHome userHome) { var workingPathName = StringUtils.defaultIfBlank(scannerProps.property(CoreProperties.GLOBAL_WORKING_DIRECTORY), CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE); var workingPath = Paths.get(wor...
@Test void createTempFolderFromSonarHome(@TempDir Path sonarUserHomePath) { // with sonar home, it will be in {sonar.home}/.sonartmp when(sonarUserHome.getPath()).thenReturn(sonarUserHomePath); var expectedWorkingDir = sonarUserHomePath.resolve(CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE); ...
public void sendRequests(Callback<None> callback) { LOG.info("Event Bus Requests throttler started for {} keys at a {} load rate", _keysToFetch.size(), _maxConcurrentRequests); if (_keysToFetch.size() == 0) { callback.onSuccess(None.none()); return; } _callback = callback; ma...
@Test(timeOut = 10000) public void testAllowZeroRequests() throws InterruptedException, ExecutionException, TimeoutException { TestSubscriber testSubscriber = new TestSubscriber(); TestEventBus testEventBus = new TestEventBus(testSubscriber); PropertyEventBusRequestsThrottler<String> propertyEventBusReq...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_nullExpected() { float[] actual = array(1.0f, 2.0f, 3.0f); expectFailureWhenTestingThat(actual).usingExactEquality().contains(null); assertFailureKeys( "value of", "expected to contain", "testing whether", "but was", "ad...
public Optional<UserDto> authenticate(Credentials credentials, HttpRequest request, AuthenticationEvent.Method method) { if (isLdapAuthActivated) { return Optional.of(doAuthenticate(fixCase(credentials), request, method)); } return Optional.empty(); }
@Test public void return_empty_user_when_ldap_not_activated() { reset(ldapRealm); when(ldapRealm.isLdapAuthActivated()).thenReturn(false); underTest = new LdapCredentialsAuthentication(settings.asConfig(), userRegistrar, authenticationEvent, ldapRealm); assertThat(underTest.authenticate(new Credentia...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindOneArgWithCast() { // Given: final KsqlScalarFunction[] functions = new KsqlScalarFunction[]{ function(EXPECTED, -1, LONG)}; Arrays.stream(functions).forEach(udfIndex::addFunction); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(S...
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator382() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("ftp://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose")); }
@Override public Message postProcessMessage(Message message) { MessageProducerRequest request = new MessageProducerRequest(message); TraceContext maybeParent = currentTraceContext.get(); // Unlike message consumers, we try current span before trying extraction. This is the proper // order because the s...
@Test void should_set_remote_service() { Message message = MessageBuilder.withBody(new byte[0]).build(); tracingMessagePostProcessor.postProcessMessage(message); assertThat(spans.get(0).remoteServiceName()) .isEqualTo("my-exchange"); }
public List<JobMessage> getJobMessages(String jobId, long startTimestampMs) throws IOException { // TODO: Allow filtering messages by importance Instant startTimestamp = new Instant(startTimestampMs); ArrayList<JobMessage> allMessages = new ArrayList<>(); String pageToken = null; while (true) { ...
@Test public void testGetJobMessages() throws IOException { DataflowClient dataflowClient = mock(DataflowClient.class); ListJobMessagesResponse firstResponse = new ListJobMessagesResponse(); firstResponse.setJobMessages(new ArrayList<>()); for (long i = 0; i < 100; ++i) { JobMessage message = n...
public Searcher searcher() { return new Searcher(); }
@Test void requireThatPredicateIndexCanSearchWithEmptyDocuments() { PredicateIndexBuilder builder = new PredicateIndexBuilder(10); builder.indexDocument(1, Predicate.fromString("true")); builder.indexDocument(2, Predicate.fromString("false")); PredicateIndex index = builder.build(); ...
public static <T> PaginatedResponse<T> create(String listKey, PaginatedList<T> paginatedList) { return new PaginatedResponse<>(listKey, paginatedList, null, null); }
@Test public void serializeWithQuery() throws Exception { final ImmutableList<String> values = ImmutableList.of("hello", "world"); final PaginatedList<String> paginatedList = new PaginatedList<>(values, values.size(), 1, 10); final PaginatedResponse<String> response = PaginatedResponse.creat...
@Override public CompletableFuture<Acknowledge> submitJob(JobGraph jobGraph, Time timeout) { final JobID jobID = jobGraph.getJobID(); try (MdcCloseable ignored = MdcUtils.withContext(MdcUtils.asContextData(jobID))) { log.info("Received JobGraph submission '{}' ({}).", jobGraph.getName(),...
@Test public void testJobSubmissionWithPartialResourceConfigured() throws Exception { ResourceSpec resourceSpec = ResourceSpec.newBuilder(2.0, 10).build(); final JobVertex firstVertex = new JobVertex("firstVertex"); firstVertex.setInvokableClass(NoOpInvokable.class); firstVertex.set...
private Map<String, StorageUnit> getStorageUnits(final Map<String, StorageNode> storageUnitNodeMap, final Map<StorageNode, DataSource> storageNodeDataSources, final Map<String, DataSourcePoolProperties> dataSourcePoolPropsMap) { Map<String, StorageUnit> resul...
@Test void assertGetDataSourcePoolProperties() { DataSourceProvidedDatabaseConfiguration databaseConfig = createDataSourceProvidedDatabaseConfiguration(); DataSourcePoolProperties props = databaseConfig.getStorageUnits().get("foo_ds").getDataSourcePoolProperties(); Map<String, Object> poolSt...
@Override public String generateSqlType(Dialect dialect) { switch (dialect.getId()) { case MsSql.ID: return "NVARCHAR (MAX)"; case Oracle.ID, H2.ID: return "CLOB"; case PostgreSql.ID: return "TEXT"; default: throw new IllegalArgumentException("Unsupported di...
@Test public void generate_sql_type_on_h2() { assertThat(underTest.generateSqlType(new H2())).isEqualTo("CLOB"); }
public static <T> T readStaticFieldOrNull(String className, String fieldName) { try { Class<?> clazz = Class.forName(className); return readStaticField(clazz, fieldName); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | SecurityException e) { ...
@Test public void readStaticFieldOrNull_whenClassDoesNotExist_thenReturnNull() { Object field = ReflectionUtils.readStaticFieldOrNull("foo.bar.nonExistingClass", "field"); assertNull(field); }
@Override public DescribeClusterResult describeCluster(DescribeClusterOptions options) { final KafkaFutureImpl<Collection<Node>> describeClusterFuture = new KafkaFutureImpl<>(); final KafkaFutureImpl<Node> controllerFuture = new KafkaFutureImpl<>(); final KafkaFutureImpl<String> clusterIdFut...
@Test public void testDescribeClusterHandleError() { try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(4, 0), AdminClientConfig.RETRIES_CONFIG, "2")) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); // Prepare the describe cluster ...
@Bean public ShenyuPlugin springCloudPlugin(final ObjectProvider<ShenyuSpringCloudServiceChooser> serviceChooser) { return new SpringCloudPlugin(serviceChooser.getIfAvailable()); }
@Test public void testSpringCloudPlugin() { applicationContextRunner.run(context -> { ShenyuPlugin plugin = context.getBean("springCloudPlugin", ShenyuPlugin.class); assertNotNull(plugin); assertThat(plugin.named()).isEqualTo(PluginEnum.SPRING_CLOUD.getName())...
@Udf public Integer least(@UdfParameter final Integer val, @UdfParameter final Integer... vals) { return (vals == null) ? null : Stream.concat(Stream.of(val), Arrays.stream(vals)) .filter(Objects::nonNull) .min(Integer::compareTo) .orElse(null); }
@Test public void shouldHandleAllNullColumns() { assertThat(leastUDF.least((Integer) null, null, null), is(nullValue())); assertThat(leastUDF.least((Double) null, null, null), is(nullValue())); assertThat(leastUDF.least((Long) null, null, null), is(nullValue())); assertThat(leastUDF.least((BigDecimal)...
public static HivePartitionStats merge(HivePartitionStats current, HivePartitionStats update) { if (current.getCommonStats().getRowNums() == -1 || update.getCommonStats().getRowNums() <= 0) { return current; } else if (current.getCommonStats().getRowNums() == 0 && update.getCommonStats().get...
@Test public void testMerge() { HivePartitionStats current = HivePartitionStats.empty(); HivePartitionStats update = HivePartitionStats.empty(); Assert.assertEquals(current, HivePartitionStats.merge(current, update)); current = HivePartitionStats.fromCommonStats(5, 100); upd...
@Override @SuppressWarnings("unchecked") public void processElement(Object untypedElem) throws Exception { if (fnRunner == null) { // If we need to run reallyStartBundle in here, we need to make sure to switch the state // sampler into the start state. try (Closeable start = operationContext.e...
@Test public void testStateTracking() throws Exception { ExecutionStateTracker tracker = ExecutionStateTracker.newForTest(); TestOperationContext operationContext = TestOperationContext.create( new CounterSet(), NameContextsForTests.nameContextForTest(), new Metric...
@Override public ServerConfiguration getServerConfiguration(String issuer) { ServerConfiguration server = staticServerService.getServerConfiguration(issuer); if (server != null) { return server; } else { return dynamicServerService.getServerConfiguration(issuer); } }
@Test public void getServerConfiguration_noIssuer() { Mockito.when(mockStaticService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); Mockito.when(mockDynamicService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); String badIssuer = "www.badexample.com"; ServerConfiguration result...
public static Optional<MaximumLagFilter> create( final Optional<LagReportingAgent> lagReportingAgent, final RoutingOptions routingOptions, final List<KsqlHostInfo> hosts, final String queryId, final String storeName, final int partition ) { if (!lagReportingAgent.isPresent()) {...
@Test public void filter_lagReportingDisabled() { // When: Optional<MaximumLagFilter> filterOptional = MaximumLagFilter.create( Optional.empty(), routingOptions, HOSTS, APPLICATION_ID, STATE_STORE, PARTITION); // Then: assertFalse(filterOptional.isPresent()); }
public DescribeTopicPartitionsResponseData handleDescribeTopicPartitionsRequest(RequestChannel.Request abstractRequest) { DescribeTopicPartitionsRequestData request = ((DescribeTopicPartitionsRequest) abstractRequest.loggableRequest()).data(); Set<String> topics = new HashSet<>(); boolean fetchA...
@Test void testDescribeTopicPartitionsRequest() { // 1. Set up authorizer Authorizer authorizer = mock(Authorizer.class); String unauthorizedTopic = "unauthorized-topic"; String authorizedTopic = "authorized-topic"; String authorizedNonExistTopic = "authorized-non-exist"; ...
public void cleanControllerBrokerData(String controllerAddr, String clusterName, String brokerName, String brokerControllerIdsToClean, boolean isCleanLivingBroker) throws RemotingException, InterruptedException, MQBrokerException { //get controller leader address final GetMetaDataRespon...
@Test public void testCleanControllerBrokerData() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); GetMetaDataResponseHeader responseHeader = new GetMetaDataResponseHeader(); responseHeader.setControllerLeaderAddress(defaultBrokerAddr); setRespons...
@Restricted(NoExternalUse.class) @VisibleForTesting public static Set<String> getAutoCompletionCandidates(List<String> loggerNamesList) { Set<String> loggerNames = new HashSet<>(loggerNamesList); // now look for package prefixes that make sense to offer for autocompletion: // Only prefi...
@Test public void autocompletionTest() { List<String> loggers = Arrays.asList( "com.company.whatever.Foo", "com.foo.Bar", "com.foo.Baz", "org.example.app.Main", "org.example.app.impl.xml.Parser", "org.example.app.impl.xml.Validator"); Set<String> candidates = LogReco...
@Override public void execute(Exchange exchange) throws SmppException { SubmitSm[] submitSms = createSubmitSm(exchange); List<String> messageIDs = new ArrayList<>(submitSms.length); String messageID = null; for (int i = 0; i < submitSms.length; i++) { SubmitSm submitSm =...
@Test public void executeWithOptionalParameter() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.ge...
@Override public ObjectNode encode(DelayMeasurementEntry dm, CodecContext context) { checkNotNull(dm, "DM cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(DM_ID, dm.dmId().toString()); if (dm.sessionStatus() != null) { result.put(SES...
@Test public void testEncodeDelayMeasurementEntryCodecContext() throws JsonProcessingException, IOException { ObjectNode node = mapper.createObjectNode(); node.set("dm", context.codec(DelayMeasurementEntry.class) .encode(dmEntry1, context)); assertEquals(12, node...
@Override public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) { return delegates.stream() .flatMap(delegate -> delegate.getDevOpsProjectCreator(dbSession, characteristics).stream()) .findFirst(); }
@Test public void getDevOpsProjectDescriptor_whenOneDelegatesReturningACreator_shouldDelegate() { DevOpsProjectCreatorFactory successfulDelegate = mock(); DevOpsProjectCreator devOpsProjectCreator = mock(); when(successfulDelegate.getDevOpsProjectCreator(DB_SESSION, CHARACTERISTICS)).thenReturn(Optional.o...
@Deprecated public static SegwitAddress fromBech32(@Nullable NetworkParameters params, String bech32) throws AddressFormatException { return (SegwitAddress) AddressParser.getLegacy(params).parseAddress(bech32); }
@Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBech32m_taprootTooLong() { // Taproot, valid bech32m encoding, checksum ok, padding ok, but no valid Segwit v1 program // (this program is 40 bytes long, but only 32 bytes program length are valid for Segwit v1/Taproot)...
public static Duration minutes(long count) { return new Duration(count, TimeUnit.MINUTES); }
@Test void testSerialization() throws IOException, ClassNotFoundException { final Duration duration = Duration.minutes(42L); final byte[] bytes; try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectOutputStream = new ObjectO...
public CreateTableCommand createTableCommand( final KsqlStructuredDataOutputNode outputNode, final Optional<RefinementInfo> emitStrategy ) { Optional<WindowInfo> windowInfo = outputNode.getKsqlTopic().getKeyFormat().getWindowInfo(); if (windowInfo.isPresent() && emitStrategy.isPresent()) ...
@Test public void shouldCreateTableCommandWithSingleValueWrappingFromPropertiesNotConfig() { // Given: ksqlConfig = new KsqlConfig(ImmutableMap.of( KsqlConfig.KSQL_WRAP_SINGLE_VALUES, true )); final ImmutableMap<String, Object> overrides = ImmutableMap.of( KsqlConfig.KSQL_WRAP_SINGLE_...
@Override public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup(KieSession.class); Collection<?> objects = ksession.getObjects(new ConditionFilter(factToCheck)); if (!objects.isEmpty()) { factToCheck.forEach(fact -> fact.getScenarioResult...
@Test public void execute_setResultIsNotCalled() { when(kieSession.getObjects(any(ObjectFilter.class))).thenReturn(List.of()); when(scenarioResult.getFactMappingValue()).thenReturn(factMappingValue); validateFactCommand.execute(registryContext); verify(scenarioResult, times...
public void build(@Nullable SegmentVersion segmentVersion, ServerMetrics serverMetrics) throws Exception { SegmentGeneratorConfig genConfig = new SegmentGeneratorConfig(_tableConfig, _dataSchema); // The segment generation code in SegmentColumnarIndexCreator will throw // exception if start and end t...
@Test public void testNoRecordsIndexedColumnMajorSegmentBuilder() throws Exception { File tmpDir = new File(TMP_DIR, "tmp_" + System.currentTimeMillis()); TableConfig tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName("testTable").setTimeColumnName(DATE_TIME_COLUMN) ...
public static <T> T createInstance(String userClassName, Class<T> xface, ClassLoader classLoader) { Class<?> theCls; try { theCls = Class.forName(userClassName, true, classLoader); } catch (ClassNotFoundExc...
@Test public void testCreateTypedInstanceNoNoArgConstructor() { try { createInstance(OneArgClass.class.getName(), aInterface.class, classLoader); fail("Should fail to load class doesn't have no-arg constructor"); } catch (RuntimeException re) { assertTrue(re.getCa...
@Override protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { try (final BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) { Host current = null; String line; wh...
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new WinScpBookmarkCollection().parse(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f")); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testAbsoluteMemoryNegativeWithSpaces() throws Exception { expectNegativeValueOfResource("memory"); parseResourceConfigValue("2 vcores, -5120 mb"); }
@Override public RLock readLock() { return new RedissonReadLock(commandExecutor, getName()); }
@Test public void testReentrancy() throws InterruptedException { RReadWriteLock rwlock = redisson.getReadWriteLock("lock"); RLock lock = rwlock.readLock(); Assertions.assertTrue(lock.tryLock()); Assertions.assertTrue(lock.tryLock()); lock.unlock(); // next row for t...
void snapshotSession(final ClientSession session) { final String responseChannel = session.responseChannel(); final byte[] encodedPrincipal = session.encodedPrincipal(); final int length = MessageHeaderEncoder.ENCODED_LENGTH + ClientSessionEncoder.BLOCK_LENGTH + ClientSessionEnco...
@Test void snapshotSessionUsesTryClaimIfDataFitIntoMaxPayloadSize() { final int offset = 40; final String responseChannel = "aeron:udp?endpoint=localhost:8080"; final byte[] encodedPrincipal = new byte[100]; ThreadLocalRandom.current().nextBytes(encodedPrincipal); final C...
public void observeComputeEngineTaskDuration(long durationInSeconds, String taskType, String projectKey) { ceTasksRunningDuration.labels(taskType, projectKey).observe(durationInSeconds); }
@Test public void observeComputeEngineTaskDurationTest() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); String[] labelNames = {"task_type", "project_key"}; String[] labelValues = {"REPORT", "projectKey"}; metrics.observeComputeEngineTaskDuration(10, labelValues[0], labelValues[1])...
public boolean eval(ContentFile<?> file) { // TODO: detect the case where a column is missing from the file using file's max field id. return new MetricsEvalVisitor().eval(file); }
@Test public void testRequiredColumn() { boolean shouldRead = new InclusiveMetricsEvaluator(SCHEMA, notNull("required")).eval(FILE); assertThat(shouldRead).as("Should read: required columns are always non-null").isTrue(); shouldRead = new InclusiveMetricsEvaluator(SCHEMA, isNull("required")).eval(FILE); ...
@Override public void addStaticImport(String staticImport) { staticImports.add(staticImport); }
@Test void testAddStaticImport() { Interface interfaze = new Interface("com.foo.UserInterface"); interfaze.addStaticImport("com.foo.StaticUtil"); assertNotNull(interfaze.getStaticImports()); assertEquals(1, interfaze.getStaticImports().size()); assertTrue(interfaze.getStatic...
@Override public URI getLocation(FileResource resource) { var blobName = getBlobName(resource); if (StringUtils.isEmpty(serviceEndpoint)) { throw new IllegalStateException("Cannot determine location of file " + blobName + ": missing Azure blob service endpoint"); ...
@Test public void testGetLocation() { service.serviceEndpoint = "http://azure.blob.storage/"; service.blobContainer = "blob-container"; var namespace = new Namespace(); namespace.setName("abelfubu"); var extension = new Extension(); extension.setName("abelfubu-dark")...
public static <T> Match<T> ifNotNull() { return NOT_NULL; }
@Test public void testIfNotNull() { Match<String> m = Match.ifNotNull(); assertFalse(m.matches(null)); assertTrue(m.matches("foo")); }
@Override public void createOrUpdate(final String path, final Object data) { zkClient.createOrUpdate(path, data, CreateMode.PERSISTENT); }
@Test public void testOnMetaDataChangedUpdate() throws UnsupportedEncodingException { MetaData metaData = MetaData.builder().id(MOCK_ID).path(MOCK_PATH).appName(MOCK_APP_NAME).build(); String metaDataPath = DefaultPathConstants.buildMetaDataPath(URLEncoder.encode(metaData.getPath(), StandardCharsets...
public Collection<String> getSharedWaitersAndHolders() { return Collections.unmodifiableSet(mSharedLockHolders.keySet()); }
@Test // TODO(jiacheng): run this test before committing public void testGetStateLockSharedWaitersAndHolders() throws Throwable { final StateLockManager stateLockManager = new StateLockManager(); assertEquals(0, stateLockManager.getSharedWaitersAndHolders().size()); for (int i = 1; i < 10; i++) { ...
public static void main(String[] args) { createAndSaveGraph(); useContractionHierarchiesToMakeQueriesFaster(); }
@Test public void main() { LowLevelAPIExample.main(null); }
@Override public void onMsg(TbContext ctx, TbMsg msg) { JsonObject json = JsonParser.parseString(msg.getData()).getAsJsonObject(); String tmp; if (msg.getOriginator().getEntityType() != EntityType.DEVICE) { ctx.tellFailure(msg, new RuntimeException("Message originator is not a de...
@Test public void givenOriginServiceId_whenOnMsg_thenVerifyRequest() { given(ctxMock.getRpcService()).willReturn(rpcServiceMock); given(ctxMock.getTenantId()).willReturn(TENANT_ID); String originServiceId = "service-id-123"; TbMsgMetaData metadata = new TbMsgMetaData(); meta...
@Operation(summary = "get", description = "Get a component") @GetMapping("/{id}") public ResponseEntity<ComponentVO> get(@PathVariable Long id) { return ResponseEntity.success(componentService.get(id)); }
@Test void getReturnsNotFoundForInvalidId() { Long id = 999L; when(componentService.get(id)).thenReturn(null); ResponseEntity<ComponentVO> response = componentController.get(id); assertTrue(response.isSuccess()); assertNull(response.getData()); }
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<>(); if(replies.isEmpty()) { return children; } // At least one entry successfully parsed...
@Test(expected = FTPInvalidListException.class) public void testBrokenMlsd() throws Exception { Path path = new Path( "/Dummies_Infoblaetter", EnumSet.of(Path.Type.directory)); String[] replies = new String[]{ "Type=dir;Modify=20101209140859;Win32.ea=0x00000010; Dummi...
public void patchLike(final Long boardId, final boolean isIncreaseLike) { Board board = findByIdUsingPessimisticLock(boardId); board.patchLike(isIncreaseLike); }
@Test void 게시글_좋아요_처리를_한다() { // given Board savedBoard = boardRepository.save(게시글_생성_사진없음()); // when boardService.patchLike(savedBoard.getId(), true); // then assertThat(savedBoard.getLikeCount().getLikeCount()).isEqualTo(1); }
@Override public CompletableFuture<Void> setRole(NodeId nodeId, DeviceId deviceId, MastershipRole role) { checkNotNull(nodeId, NODE_ID_NULL); checkNotNull(deviceId, DEVICE_ID_NULL); checkNotNull(role, ROLE_NULL); CompletableFuture<Mastershi...
@Test public void setRole() { mastershipMgr1.setRole(NID_OTHER, VDID1, MASTER); assertEquals("wrong local role:", NONE, mastershipMgr1.getLocalRole(VDID1)); assertEquals("wrong obtained role:", STANDBY, Futures.getUnchecked(mastershipMgr1.requestRoleFor(VDID1))); //set to master ...
Collection<AzureAddress> getAddresses() { LOGGER.finest("Fetching OAuth Access Token"); final String accessToken = fetchAccessToken(); LOGGER.finest("Fetching instances for subscription '%s' and resourceGroup '%s'", subscriptionId, resourceGroup); Collection<AzureAddress>...
@Test public void getAddressesCurrentSubscriptionCurrentResourceGroupCurrentScaleSetWithTag() { // given given(azureComputeApi.instances(SUBSCRIPTION_ID, RESOURCE_GROUP, SCALE_SET, TAG, ACCESS_TOKEN)).willReturn(ADDRESSES); AzureConfig azureConfig = AzureConfig.builder().setInstanceMetadata...
public TimelineEvent kill(String workflowId, User caller) { return terminate(workflowId, Actions.WorkflowInstanceAction.KILL, caller); }
@Test public void testKill() { when(instanceDao.terminateQueuedInstances( eq("sample-minimal-wf"), eq(Constants.TERMINATE_BATCH_LIMIT), eq(WorkflowInstance.Status.FAILED), anyString())) .thenReturn(Constants.TERMINATE_BATCH_LIMIT) .thenReturn(Constan...
@InvokeOnHeader(CONTROL_ACTION_LIST) public void performList(final Exchange exchange, AsyncCallback callback) { Message message = exchange.getMessage(); Map<String, Object> headers = message.getHeaders(); String subscribeChannel = (String) headers.getOrDefault(CONTROL_SUBSCRIBE_CHANNEL, conf...
@Test void testPerformListActionWithException() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_LIST, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel); when(exchange.getMessage()).thenReturn(me...
@PostMapping(params = "import=true") @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) public RestResult<Map<String, Object>> importAndPublishConfig(HttpServletRequest request, @RequestParam(value = "src_user", required = false) String srcUser, @RequestParam(value = "names...
@Test void testImportAndPublishConfig() throws Exception { MockedStatic<ZipUtils> zipUtilsMockedStatic = Mockito.mockStatic(ZipUtils.class); List<ZipUtils.ZipItem> zipItems = new ArrayList<>(); ZipUtils.ZipItem zipItem = new ZipUtils.ZipItem("test/test", "test"); zipItems.add(zipItem...
@SuppressWarnings("unchecked") private void publishContainerPausedEvent( ContainerEvent event) { if (publishNMContainerEvents) { ContainerPauseEvent pauseEvent = (ContainerPauseEvent) event; ContainerId containerId = pauseEvent.getContainerID(); ContainerEntity entity = createContainerEnti...
@Test public void testPublishContainerPausedEvent() { ApplicationId appId = ApplicationId.newInstance(0, 1); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ContainerId cId = ContainerId.newContainerId(appAttemptId, 1); ContainerEvent containerEvent = n...
public static Date parseDateLenient(String text) { if (text == null) { return null; } String normalized = normalize(text); for (DateTimeFormatter dateTimeFormatter : DATE_TIME_FORMATTERS) { try { ZonedDateTime zonedDateTime = ZonedDateTime.parse(no...
@Test public void testTrickyDates() throws Exception { DateFormat df = new SimpleDateFormat("yyyy-MM-dd", new DateFormatSymbols(Locale.US)); //make sure there are no mis-parses of e.g. 90 = year 90 A.D, not 1990 Date date1980 = df.parse("1980-01-01"); Date date2010 = df.parse("2010-0...
public static int[] generateRandomNumber(int begin, int end, int size) { // 种子你可以随意生成,但不能重复 final int[] seed = ArrayUtil.range(begin, end); return generateRandomNumber(begin, end, size, seed); }
@Test public void generateRandomNumberTest(){ final int[] ints = NumberUtil.generateRandomNumber(10, 20, 5); assertEquals(5, ints.length); final Set<?> set = Convert.convert(Set.class, ints); assertEquals(5, set.size()); }
public void heartbeat(final String appName, final String id, final InstanceInfo info, final InstanceStatus overriddenStatus, boolean primeConnection) throws Throwable { if (primeConnection) { // We do not care about the result for priming request. ...
@Test public void testHeartbeatReplicationFailure() throws Throwable { httpReplicationClient.withNetworkStatusCode(200, 200); httpReplicationClient.withBatchReply(404); // Not found, to trigger registration createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), ins...
@ShellMethod(key = "compactions show all", value = "Shows all compactions that are in active timeline") public String compactionsAll( @ShellOption(value = {"--includeExtraMetadata"}, help = "Include extra metadata", defaultValue = "false") final boolean includeExtraMetadata, @ShellOption(value =...
@Test public void testCompactionsAll() throws IOException { // create MOR table. new TableCommand().createTable( tablePath, tableName, HoodieTableType.MERGE_ON_READ.name(), "", TimelineLayoutVersion.VERSION_1, HoodieAvroPayload.class.getName()); CompactionTestUtils.setupAndValidateCompact...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindVarargWithSomeNullValues() { // Given: givenFunctions( function(EXPECTED, 0, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(Arrays.asList(null, SqlArgument.of(SqlTypes.STRING), null)); // Then: assertThat(fun.name(), eq...
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); LongColumnStatsDataInspector aggregateData = longInspectorFromStats(aggregateColStats); LongColum...
@Test public void testMergeNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(long.class) .low(null) .high(null) .numNulls(1) .numDVs(0) .build()); merger.merge(aggrObj, aggrObj); ColumnStatisticsData expectedColumnStatisti...
@Bean public OpenAPI apiInfo() { return new OpenAPI() .info(new Info() .title(TITLE).description(DESCRIPTION) .version(VersionUtils.getVersion(getClass(), DEFAULT_SWAGGER_API_VERSION)) .contact(new Contact().name(CONTACT...
@Test public void testApiInfo() { OpenAPI actual = swaggerConfiguration.apiInfo(); assertNotNull(actual); Assertions.assertEquals(1, actual.getSecurity().size()); Assertions.assertEquals(1, actual.getSecurity().get(0).size()); Assertions.assertTrue(actual.getSecurity().get(0)...
static void closeStateManager(final Logger log, final String logPrefix, final boolean closeClean, final boolean eosEnabled, final ProcessorStateManager stateMgr, ...
@Test public void testCloseStateManagerThrowsExceptionWhenDirty() { when(stateManager.taskId()).thenReturn(taskId); when(stateDirectory.lock(taskId)).thenReturn(true); doThrow(new ProcessorStateException("state manager failed to close")).when(stateManager).close(); assertThrows( ...
static int parseInt(String key, @Nullable String value) { requireArgument((value != null) && !value.isEmpty(), "value of key %s was omitted", key); try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format(US, "key %s val...
@Test public void parseInt_exception() { assertThrows(IllegalArgumentException.class, () -> CaffeineSpec.parseInt("key", "value")); }
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test public void testSourceSplitAtFraction() throws Exception { List<Integer> elements = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 25; i++) { elements.add(random.nextInt()); } CreateSource<Integer> source = CreateSource.fromIterable(elements, VarIntCoder.of()); ...
@SuppressWarnings("nullness") @VisibleForTesting public ProcessContinuation run( PartitionMetadata partition, RestrictionTracker<TimestampRange, Timestamp> tracker, OutputReceiver<DataChangeRecord> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, BundleFinalizer bundleFi...
@Test public void testQueryChangeStreamWithDataChangeRecord() { final Struct rowAsStruct = mock(Struct.class); final ChangeStreamResultSetMetadata resultSetMetadata = mock(ChangeStreamResultSetMetadata.class); final ChangeStreamResultSet resultSet = mock(ChangeStreamResultSet.class); final Dat...
@Override public Properties getConfig(RedisClusterNode node, String pattern) { RedisClient entry = getEntry(node); RFuture<List<String>> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_GET, pattern); List<String> r = syncFuture(f); if (r != null) { ...
@Test public void testGetConfig() { RedisClusterNode master = getFirstMaster(); Properties config = connection.getConfig(master, "*"); assertThat(config.size()).isGreaterThan(20); }
@Override public String toString() { // we can't use uri.toString(), which escapes everything, because we want // illegal characters unescaped in the string, for glob processing, etc. StringBuilder buffer = new StringBuilder(); if (uri.getScheme() != null) { buffer.append(uri.getScheme()) ...
@Test (timeout = 30000) public void testNormalize() throws URISyntaxException { assertEquals("", new Path(".").toString()); assertEquals("..", new Path("..").toString()); assertEquals("/", new Path("/").toString()); assertEquals("/", new Path("//").toString()); assertEquals("/", new Path("///").to...
public static PTransformMatcher parDoWithFnType(final Class<? extends DoFn> fnType) { return new PTransformMatcher() { @Override public boolean matches(AppliedPTransform<?, ?, ?> application) { DoFn<?, ?> fn; if (application.getTransform() instanceof ParDo.SingleOutput) { fn = ...
@Test public void parDoWithFnTypeWithMatchingType() { DoFn<Object, Object> fn = new DoFn<Object, Object>() { @ProcessElement public void process(ProcessContext ctxt) {} }; AppliedPTransform<?, ?, ?> parDoSingle = getAppliedTransform(ParDo.of(fn)); AppliedPTransform<?, ?...
public static DynamicVoter parse(String input) { input = input.trim(); int atIndex = input.indexOf("@"); if (atIndex < 0) { throw new IllegalArgumentException("No @ found in dynamic voter string."); } if (atIndex == 0) { throw new IllegalArgumentException(...
@Test public void testPortSectionMustStartWithAColon() { assertEquals("Port section must start with a colon.", assertThrows(IllegalArgumentException.class, () -> DynamicVoter.parse("5@[2001:4860:4860::8888]8020:__0IZ-0DRNazJ49kCZ1EMQ")). getMessage()); }
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) { Objects.requireNonNull(metric); if (batchMeasure == null) { return Optional.empty(); } Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder(); switch (metric.getType().getValueType()) { ...
@Test public void toMeasure_for_LEVEL_Metric_maps_QualityGateStatus() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setStringValue(StringValue.newBuilder().setValue(Measure.Level.OK.name())) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_...
@Override public List<PartitionInfo> getRemotePartitions(Table table, List<String> partitionNames) { ImmutableList.Builder<Partition> partitionBuilder = ImmutableList.builder(); Map<String, Partition> existingPartitions = hmsOps.getPartitionByNames(table, partitionNames); partitionBuilder.ad...
@Test public void testGetRemotePartitions( @Mocked HiveTable table, @Mocked HiveMetastoreOperations hmsOps) { List<String> partitionNames = Lists.newArrayList("dt=20200101", "dt=20200102", "dt=20200103"); Map<String, Partition> partitionMap = Maps.newHashMap(); for (S...
public static String hashpw(String password, String salt) throws IllegalArgumentException { BCrypt B; String real_salt; byte passwordb[], saltb[], hashed[]; char minor = (char) 0; int rounds, off = 0; StringBuilder rs = new StringBuilder(); if (salt == null) { ...
@Test public void testHashpwTooLittleRounds() throws IllegalArgumentException { thrown.expect(IllegalArgumentException.class); BCrypt.hashpw("foo", "$2a$03$......................"); }
public static <T> T convert(Class<T> type, Object value) throws ConvertException { return convert((Type) type, value); }
@Test public void toAtomicIntegerArrayTest() { final String str = "1,2"; final AtomicIntegerArray atomicIntegerArray = Convert.convert(AtomicIntegerArray.class, str); assertEquals("[1, 2]", atomicIntegerArray.toString()); }
public CMap parse(RandomAccessRead randomAcccessRead) throws IOException { CMap result = new CMap(); Object previousToken = null; Object token = parseNextToken(randomAcccessRead); while (token != null) { if (token instanceof Operator) { ...
@Test void testIdentitybfrange() throws IOException { // use strict mode CMap cMap = new CMapParser(true) .parse(new RandomAccessReadBufferedFile( new File("src/test/resources/cmap", "Identitybfrange"))); assertEquals("Adobe-Identity-UCS", cMap.get...
@Override public String pathPattern() { return buildExtensionPathPattern(scheme); }
@Test void shouldBuildPathPatternCorrectly() { var scheme = Scheme.buildFromType(FakeExtension.class); var listHandler = new ExtensionListHandler(scheme, client); var pathPattern = listHandler.pathPattern(); assertEquals("/apis/fake.halo.run/v1alpha1/fakes", pathPattern); }
@Override public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context) throws KeySourceException { var jwksUrl = discoverJwksUrl(); try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) { return jwkSetSource.getJWKSet(null...
@Test void getJWKSet_noJwksUri(WireMockRuntimeInfo wm) { var discoveryUrl = URI.create(wm.getHttpBaseUrl()).resolve(DISCOVERY_PATH); stubFor(get(DISCOVERY_PATH).willReturn(okJson("{\"jwks_uri\": null}"))); var sut = new DiscoveryJwkSetSource<>(HttpClient.newHttpClient(), discoveryUrl); assertThrow...
public static double estimateNumberOfHashCollisions(int numberOfValues, int hashSize) { checkState(0 <= numberOfValues && numberOfValues <= hashSize); if (hashSize == 0) { return 0d; } double estimateRescaleFactor = (double) numberOfValues / NUMBER_OF_VALUES; do...
@Test public void hashEstimatesShouldIncrease() { assertEquals(estimateNumberOfHashCollisions(0, 100), 0d); for (int i = 1; i <= HASH_TABLE_SIZE; ++i) { assertTrue(estimateNumberOfHashCollisions(i - 1, HASH_TABLE_SIZE) < estimateNumberOfHashCollisions(i, HASH_TABLE_SIZE)); } ...
public static String getExactlyValue(final String value) { return null == value ? null : tryGetRealContentInBackticks(CharMatcher.anyOf(EXCLUDED_CHARACTERS).removeFrom(value)); }
@Test void assertGetExactlyValueWithReservedCharacters() { assertThat(SQLUtils.getExactlyValue("`xxx`", "`"), is("`xxx`")); assertThat(SQLUtils.getExactlyValue("[xxx]", "[]"), is("[xxx]")); assertThat(SQLUtils.getExactlyValue("\"xxx\"", "\""), is("\"xxx\"")); assertThat(SQLUtils.getE...
List<String> liveKeysAsOrderedList() { return new ArrayList<String>(liveMap.keySet()); }
@Test public void empty1() { long now = 3000; assertNotNull(tracker.getOrCreate(key, now++)); now += ComponentTracker.DEFAULT_TIMEOUT + 1000; tracker.removeStaleComponents(now); assertEquals(0, tracker.liveKeysAsOrderedList().size()); assertEquals(0, tracker.getComponentCount()); assertNo...
public boolean isValidatedPath(final String path) { return pathPattern.matcher(path).find(); }
@Test void assertIsNotValidPathWithNullParentNode() { UniqueRuleItemNodePath uniqueRuleItemNodePath = new UniqueRuleItemNodePath(new RuleRootNodePath("foo"), "test_path"); assertFalse(uniqueRuleItemNodePath.isValidatedPath("/word1/word2/rules/test_foo/test_path/versions/1234")); assertFalse(...
@Override public boolean equals(@Nullable Object obj) { if (!(obj instanceof LocalResourceId)) { return false; } LocalResourceId other = (LocalResourceId) obj; return this.pathString.equals(other.pathString); }
@Test public void testEquals() { // TODO: Java core test failing on windows, https://github.com/apache/beam/issues/20475 assumeFalse(SystemUtils.IS_OS_WINDOWS); assertEquals(toResourceIdentifier("/root/tmp/"), toResourceIdentifier("/root/tmp/")); assertNotEquals(toResourceIdentifier("/root/tmp"), toR...
static void checkValidIndexName(String indexName) { if (indexName.length() > MAX_INDEX_NAME_LENGTH) { throw new IllegalArgumentException( "Index name " + indexName + " cannot be longer than " + MAX_INDEX_NAME_LENGTH + " characters."); } ...
@Test public void testCheckValidIndexNameThrowsErrorWhenNameIsTooLong() { assertThrows( IllegalArgumentException.class, () -> checkValidIndexName(StringUtils.repeat("a", 300))); }
public static <T> T readVersionAndDeSerialize( SimpleVersionedSerializer<T> serializer, DataInputView in) throws IOException { checkNotNull(serializer, "serializer"); checkNotNull(in, "in"); final int version = in.readInt(); final int length = in.readInt(); final byt...
@Test void testUnderflow() throws Exception { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy( () -> SimpleVersionedSerialization.readVersionAndDeSerialize( new TestStringSer...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseSpecificOverMultipleVarArgs() { // Given: givenFunctions( function(EXPECTED, -1, STRING), function(OTHER, 0, STRING_VARARGS), function("two", 1, STRING, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableL...
public void hasAllRequiredFields() { if (!actual.isInitialized()) { // MessageLite doesn't support reflection so this is the best we can do. failWithoutActual( simpleFact("expected to have all required fields set"), fact("but was", actualCustomStringRepresentationForProtoPackageMembe...
@Test public void testHasAllRequiredFields_failures() { if (!config.messageWithoutRequiredFields().isPresent()) { return; } AssertionError e = expectFailure( whenTesting -> whenTesting .that(config.messageWithoutRequiredFields().get()) ...
@Override public void define(Context context) { NewController controller = context.createController("api/sources") .setSince("4.2") .setDescription("Get details on source files. See also api/tests."); for (SourcesWsAction action : actions) { action.define(controller); } controller.do...
@Test public void define_ws() { SourcesWsAction[] actions = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> { SourcesWsAction wsAction = mock(SourcesWsAction.class); doAnswer(invocation -> { WebService.NewController controller = invocation.getArgument(0); ...
@Override public void handlerRule(final RuleData ruleData) { super.getWasmExtern(HANDLER_RULE_METHOD_NAME) .ifPresent(handlerPlugin -> callWASI(ruleData, handlerPlugin)); }
@Test public void handlerRuleTest() { pluginDataHandler.handlerRule(ruleData); testWasmPluginDataHandler.handlerRule(ruleData); }
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void testValueIgnoreNonNumber() throws Exception { JmxCollector jc = new JmxCollector( "\n---\nrules:\n- pattern: `.*`\n name: foo\n value: a" .replace('`', '"')) .register(promethe...
public CoercedExpressionResult coerce() { final Class<?> leftClass = left.getRawClass(); final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass); final Class<?> rightClass = right.getRawClass(); final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass); ...
@Test public void testStringToBooleanTrue() { final TypedExpression left = expr(THIS_PLACEHOLDER + ".getBooleanValue", Boolean.class); final TypedExpression right = expr("\"true\"", String.class); final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, fal...
@VisibleForTesting static int checkJar(Path file) throws Exception { final URI uri = file.toUri(); int numSevereIssues = 0; try (final FileSystem fileSystem = FileSystems.newFileSystem( new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment...
@Test void testRejectedOnInvalidLicenseFile(@TempDir Path tempDir) throws Exception { assertThat( JarFileChecker.checkJar( createJar( tempDir, Entry.fileEntry(VALID_NOTICE_...
public SecureRandom createSecureRandom() throws NoSuchProviderException, NoSuchAlgorithmException { try { return getProvider() != null ? SecureRandom.getInstance(getAlgorithm(), getProvider()) : SecureRandom.getInstance(getAlgorithm()); } catch (NoSuchProviderException ex...
@Test public void testDefaults() throws Exception { Assertions.assertNotNull(factoryBean.createSecureRandom()); }