focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@PostMapping("") @RequiresPermissions("system:manager:add") public ShenyuAdminResult createDashboardUser(@Valid @RequestBody final DashboardUserDTO dashboardUserDTO) { return Optional.ofNullable(dashboardUserDTO) .map(item -> { item.setPassword(DigestUtils.sha512Hex(i...
@Test public void createDashboardUser() throws Exception { final String url = "/dashboardUser"; given(dashboardUserService.createOrUpdate(any())).willReturn(1); mockMvc.perform(post(url, dashboardUserDTO) .content(GsonUtils.getInstance().toJson(dashboardUserDTO)) ...
public static String sha1Hex(byte[] input) { return hashBytesToHex(Hashing.sha1(), input); }
@Test void sha1Hex() { Assertions.assertEquals("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", Digests.sha1Hex("hello")); }
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowRulesUsedStorageUnitStatement sqlStatement, final ContextManager contextManager) { String resourceName = sqlStatement.getStorageUnitName().orElse(null); return database.getResourceMetaData().getStorageUnits().containsKey(resource...
@Test void assertGetRowData() { executor.setDatabase(mockDatabase()); ShowRulesUsedStorageUnitStatement sqlStatement = new ShowRulesUsedStorageUnitStatement("foo_ds", mock(DatabaseSegment.class)); Collection<LocalDataQueryResultRow> rowData = executor.getRows(sqlStatement, mock(ContextManage...
public static boolean isBearerToken(final String authorizationHeader) { return StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith(TOKEN_PREFIX); }
@Test void testIsBearerToken_WithInvalidBearerToken() { // Given String authorizationHeader = "sampleAccessToken"; // When boolean result = Token.isBearerToken(authorizationHeader); // Then assertFalse(result); }
protected Credentials parse(final InputStream in) throws IOException { final JsonReader reader = new JsonReader(new InputStreamReader(in, StandardCharsets.UTF_8)); reader.beginObject(); String key = null; String secret = null; String token = null; Date expiration = null; ...
@Test public void testParse() throws Exception { final Credentials c = new AWSSessionCredentialsRetriever(new DisabledX509TrustManager(), new DefaultX509KeyManager(), "http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access") .parse(IOUtils.toInputStream("{\...
@Override public void collect(OUT outputRecord) { output.collect(reuse.replace(outputRecord)); }
@Test void testCollect() { List<StreamElement> list = new ArrayList<>(); CollectorOutput<Integer> collectorOutput = new CollectorOutput<>(list); OutputCollector<Integer> collector = new OutputCollector<>(collectorOutput); collector.collect(1); collector.collect(2); as...
public static boolean isKafkaInvokeBySermant(StackTraceElement[] stackTrace) { return isInvokeBySermant(KAFKA_CONSUMER_CLASS_NAME, KAFKA_CONSUMER_CONTROLLER_CLASS_NAME, stackTrace); }
@Test public void testNotInvokeBySermantWithoutInvoker() { StackTraceElement[] stackTrace = new StackTraceElement[3]; stackTrace[0] = new StackTraceElement("testClass0", "testMethod0", "testFileName0", 0); stackTrace[1] = new StackTraceElement("testClass1", "testMethod1", "testFileName1", 1)...
@Override public boolean supportsUnion() { return false; }
@Test void assertSupportsUnion() { assertFalse(metaData.supportsUnion()); }
public static List<FieldInfo> buildSourceSchemaEntity(final LogicalSchema schema) { final List<FieldInfo> allFields = schema.columns().stream() .map(EntityUtil::toFieldInfo) .collect(Collectors.toList()); if (allFields.isEmpty()) { throw new IllegalArgumentException("Root schema should co...
@Test public void shouldSupportSchemasWithAllHeadersColumn() { // Given: final LogicalSchema schema = LogicalSchema.builder() .headerColumn(ColumnName.of("field1"), Optional.empty()) .build(); // When: final List<FieldInfo> fields = EntityUtil.buildSourceSchemaEntity(schema); // ...
public ArrayListTotal<Template> find( Pageable pageable, @Nullable String query, @Nullable String tenantId, @Nullable String namespace ) { return this.jdbcRepository .getDslContextWrapper() .transactionResult(configuration -> { DSLConte...
@Test void find() { templateRepository.create(builder("io.kestra.unitest").build()); templateRepository.create(builder("com.kestra.test").build()); List<Template> save = templateRepository.find(Pageable.from(1, 10, Sort.UNSORTED), null, null, null); assertThat(save.size(), is(2)); ...
public String resolve(String ensName) { if (Strings.isBlank(ensName) || (ensName.trim().length() == 1 && ensName.contains("."))) { return null; } try { if (isValidEnsName(ensName, addressLength)) { OffchainResolverContract resolver = obtainOffchainResolve...
@Test public void testResolveWildCardSuccess() throws Exception { String resolvedAddress = "0x41563129cdbbd0c5d3e1c86cf9563926b243834d"; EnsResolverForTest ensResolverForTest = new EnsResolverForTest(web3j); OffchainResolverContract resolverMock = mock(OffchainResolverContract.class); ...
public Optional<Measure> toMeasure(@Nullable LiveMeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getDataAsString(); switch (metric.getType().getValueType()) {...
@Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
public static NotControllerException newPreMigrationException(OptionalInt controllerId) { if (controllerId.isPresent()) { return new NotControllerException("The controller is in pre-migration mode."); } else { return new NotControllerException("No controller appears to be active....
@Test public void testNewPreMigrationExceptionWithActiveController() { assertExceptionsMatch(new NotControllerException("The controller is in pre-migration mode."), newPreMigrationException(OptionalInt.of(1))); }
@Override public String convert(final SingleRuleConfiguration ruleConfig) { if (ruleConfig.getTables().isEmpty() && !ruleConfig.getDefaultDataSource().isPresent()) { return ""; } StringBuilder result = new StringBuilder(); if (!ruleConfig.getTables().isEmpty()) { ...
@Test void assertConvert() { SingleRuleConfiguration singleRuleConfig = new SingleRuleConfiguration(new LinkedList<>(Arrays.asList("t_0", "t_1")), "foo_ds"); SingleRuleConfigurationToDistSQLConverter singleRuleConfigurationToDistSQLConverter = new SingleRuleConfigurationToDistSQLConverter(); ...
public static <V> TimestampedValue<V> of(V value, Instant timestamp) { return new TimestampedValue<>(value, timestamp); }
@Test public void testNullTimestamp() { thrown.expect(NullPointerException.class); thrown.expectMessage("timestamp"); TimestampedValue.of("foobar", null); }
public static CoderProvider getCoderProvider() { return new ProtoCoderProvider(); }
@Test public void testProviderCannotProvideCoder() throws Exception { thrown.expect(CannotProvideCoderException.class); thrown.expectMessage("java.lang.Integer is not a subclass of com.google.protobuf.Message"); ProtoCoder.getCoderProvider() .coderFor(new TypeDescriptor<Integer>() {}, Collections...
public String siteUrlFor(String givenUrl) throws URISyntaxException { return siteUrlFor(givenUrl, false); }
@Test public void shouldGenerateSiteUrlForGivenPath() throws URISyntaxException { ServerSiteUrlConfig url = new SiteUrl("http://someurl.com"); assertThat(url.siteUrlFor("/foo/bar"), is("/foo/bar")); assertThat(url.siteUrlFor("http/bar"), is("http/bar")); }
@Override public int partition() { if (recordContext == null) { // This is only exposed via the deprecated ProcessorContext, // in which case, we're preserving the pre-existing behavior // of returning dummy values when the record context is undefined. // For ...
@Test public void shouldReturnPartitionFromRecordContext() { assertThat(context.partition(), equalTo(recordContext.partition())); }
@DELETE @Path("{id}") @Timed @ApiOperation(value = "Delete index set") @AuditEvent(type = AuditEventTypes.INDEX_SET_DELETE) @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), @ApiResponse(code = 404, message = "Index set not found"), }) public...
@Test public void delete() throws Exception { final IndexSet indexSet = mock(IndexSet.class); final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class); when(indexSet.getConfig()).thenReturn(indexSetConfig); when(indexSetRegistry.get("id")).thenReturn(Optional.of(indexSet)); ...
public RunResponse start( @NotNull String workflowId, @NotNull String version, @NotNull RunRequest runRequest) { WorkflowDefinition definition = workflowDao.getWorkflowDefinition(workflowId, version); validateRequest(version, definition, runRequest); RunProperties runProperties = RunProperti...
@Test public void testStartWithInvalidStepRunParams() { RunRequest request = RunRequest.builder() .initiator(new ManualInitiator()) .currentPolicy(RunPolicy.START_FRESH_NEW_RUN) .requestId(UUID.fromString("41f0281e-41a2-468d-b830-56141b2f768b")) .stepRunPara...
protected String convertHeaderValueToString(Exchange exchange, Object headerValue) { if ((headerValue instanceof Date || headerValue instanceof Locale) && convertDateAndLocaleLocally(exchange)) { if (headerValue instanceof Date) { return toHttpDate((Date) headerValue)...
@Test public void testConvertLocale() { DefaultHttpBinding binding = new DefaultHttpBinding(); Locale l = Locale.SIMPLIFIED_CHINESE; Exchange exchange = super.createExchangeWithBody(null); String value = binding.convertHeaderValueToString(exchange, l); assertNotEquals(value,...
boolean isInsideOpenClosed(Number toEvaluate) { if (leftMargin == null) { return toEvaluate.doubleValue() <= rightMargin.doubleValue(); } else if (rightMargin == null) { return toEvaluate.doubleValue() > leftMargin.doubleValue(); } else { return toEvaluate.dou...
@Test void isInsideOpenClosed() { KiePMMLInterval kiePMMLInterval = new KiePMMLInterval(null, 20, CLOSURE.OPEN_CLOSED); assertThat(kiePMMLInterval.isInsideOpenClosed(10)).isTrue(); assertThat(kiePMMLInterval.isInsideOpenClosed(20)).isTrue(); assertThat(kiePMMLInterval.isInsideOpenClo...
public String encode(String name, String value) { return encode(new DefaultCookie(name, value)); }
@Test public void illegalCharInWrappedValueAppearsInException() { try { ServerCookieEncoder.STRICT.encode(new DefaultCookie("name", "\"value,\"")); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), containsString("cookie value contains an invalid...
public DataVersion queryBrokerTopicConfig(final String clusterName, final String brokerAddr) { BrokerAddrInfo addrInfo = new BrokerAddrInfo(clusterName, brokerAddr); BrokerLiveInfo prev = this.brokerLiveTable.get(addrInfo); if (prev != null) { return prev.getDataVersion(); } ...
@Test public void testQueryBrokerTopicConfig() { { DataVersion targetVersion = new DataVersion(); targetVersion.setCounter(new AtomicLong(10L)); targetVersion.setTimestamp(100L); DataVersion dataVersion = routeInfoManager.queryBrokerTopicConfig("default-clust...
public static DefaultProcessCommands secondary(File directory, int processNumber) { return new DefaultProcessCommands(directory, processNumber, false); }
@Test public void secondary_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.secondary(temp.newFolder(), processNumber), processNumber); }
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { PDFParserConfig localConfig = defaultConfig; PDFParserConfig userConfig = context.get(PDFParserConfig.class); if (userCo...
@Test public void testProtectedPDF() throws Exception { XMLResult r = getXML("testPDF_protected.pdf"); Metadata metadata = r.metadata; assertEquals("true", metadata.get("pdf:encrypted")); assertEquals("application/pdf", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("The ...
@Override public void onAppVisible() { }
@Test public void onAppVisible_neverClearAllNotifications() throws Exception { createUUT().onAppVisible(); verify(mNotificationManager, never()).cancelAll(); }
String buildUrl( JmsDelegate delegate, boolean debug ) { StringBuilder finalUrl = new StringBuilder( delegate.amqUrl.trim() ); // verify user hit the checkbox on the dialogue *and* also has not specified these values on the URL already // end result: default to SSL settings in the URL if present, otherwise...
@Test public void testUseDefaultSslContext() { ActiveMQProvider provider = new ActiveMQProvider(); JmsDelegate delegate = new JmsDelegate( Collections.singletonList( provider ) ); delegate.amqUrl = AMQ_URL_BASE; delegate.sslEnabled = true; delegate.sslTruststorePath = TRUST_STORE_PATH_VAL; del...
@Override public void start() { DatabaseCharsetChecker.State state = DatabaseCharsetChecker.State.STARTUP; if (upgradeStatus.isUpgraded()) { state = DatabaseCharsetChecker.State.UPGRADE; } else if (upgradeStatus.isFreshInstall()) { state = DatabaseCharsetChecker.State.FRESH_INSTALL; } ...
@Test public void test_regular_startup() { when(upgradeStatus.isFreshInstall()).thenReturn(false); underTest.start(); verify(charsetChecker).check(DatabaseCharsetChecker.State.STARTUP); }
public void patchBoardById( final Long boardId, final Long memberId, final BoardUpdateRequest request ) { Board board = findBoardWithImages(boardId); board.validateWriter(memberId); BoardUpdateResult result = board.update(request.title(), request.content()...
@Test void ๊ฒŒ์‹œ๊ธ€์ด_์—†๋‹ค๋ฉด_์ˆ˜์ •ํ•˜์ง€_๋ชปํ•œ๋‹ค() { // given BoardUpdateRequest req = new BoardUpdateRequest("์ˆ˜์ •", "์ˆ˜์ •", new ArrayList<>(), new ArrayList<>()); // when & then assertThatThrownBy(() -> boardService.patchBoardById(1L, 1L, req)) .isInstanceOf(BoardNotFoundException.class);...
public SearchHits<ExtensionSearch> search(Options options) { var resultWindow = options.requestedOffset + options.requestedSize; if(resultWindow > getMaxResultWindow()) { return new SearchHitsImpl<>(0, TotalHitsRelation.OFF, 0f, null, null, Collections.emptyList(), null, null); } ...
@Test public void testSearchResultWindowTooLarge() { mockIndex(true); var options = new ISearchService.Options("foo", "bar", "universal", 50, 10000, null, null, false); var searchHits = search.search(options); assertThat(searchHits.getSearchHits()).isEmpty(); assertThat(sear...
@Override public List<Change> computeDiff(List<T> source, List<T> target, DiffAlgorithmListener progress) { Objects.requireNonNull(source, "source list must not be null"); Objects.requireNonNull(target, "target list must not be null"); if (progress != null) { progress.diffStart(...
@Test public void testDiffMyersExample1ForwardWithListener() { List<String> original = Arrays.asList("A", "B", "C", "A", "B", "B", "A"); List<String> revised = Arrays.asList("C", "B", "A", "B", "A", "C"); List<String> logdata = new ArrayList<>(); final Patch<String> patch = ...
@GET @Path("/{connector}/config") @Operation(summary = "Get the configuration for the specified connector") public Map<String, String> getConnectorConfig(final @PathParam("connector") String connector) throws Throwable { FutureCallback<Map<String, String>> cb = new FutureCallback<>(); herder...
@Test public void testGetConnectorConfigConnectorNotFound() { final ArgumentCaptor<Callback<Map<String, String>>> cb = ArgumentCaptor.forClass(Callback.class); expectAndCallbackException(cb, new NotFoundException("not found")) .when(herder).connectorConfig(eq(CONNECTOR_NAME), cb.capture(...
public MergePolicyConfig getMergePolicyConfig() { return mergePolicyConfig; }
@Test public void cacheConfigXmlTest_CustomMergePolicy() throws IOException { Config config = new XmlConfigBuilder(configUrl1).build(); CacheSimpleConfig cacheWithCustomMergePolicyConfig = config.getCacheConfig("cacheWithCustomMergePolicy"); assertNotNull(cacheWithCustomMergePolicyConfig);...
public <T> Future<Iterable<TimestampedValue<T>>> orderedListFuture( Range<Long> range, ByteString encodedTag, String stateFamily, Coder<T> elemCoder) { // First request has no continuation position. StateTag<ByteString> stateTag = StateTag.<ByteString>of(StateTag.Kind.ORDERED_LIST, encodedTag, sta...
@Test public void testReadSortedListRanges() throws Exception { Future<Iterable<TimestampedValue<Integer>>> future1 = underTest.orderedListFuture(Range.closedOpen(0L, 5L), STATE_KEY_1, STATE_FAMILY, INT_CODER); // Should be put into a subsequent batch as it has the same key and state family. Futur...
@GetMapping("/selector") public ShenyuAdminResult listPageSelectorDataPermissions(@RequestParam("currentPage") final Integer currentPage, @RequestParam("pageSize") final Integer pageSize, @Reque...
@Test public void listPageSelectorDataPermissions() throws Exception { Integer currentPage = 1; Integer pageSize = 10; String userId = "testUserId"; String pluginId = "testPluginId"; String name = "testName"; final PageParameter pageParameter = new PageParameter(curr...
@Override public void open() throws Exception { this.timerService = getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this); this.keySet = new HashSet<>(); super.open(); }
@Test void testCheckKey() throws Exception { KeyedTwoInputNonBroadcastProcessOperator<Long, Integer, Long, Long> processOperator = new KeyedTwoInputNonBroadcastProcessOperator<>( new TwoInputNonBroadcastStreamProcessFunction<Integer, Long, Long>() { ...
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokePositive() { FunctionTestUtil.assertResultBigDecimal(floorFunction.invoke(BigDecimal.valueOf(10.2)), BigDecimal.valueOf(10)); }
public static SegmentGenerationJobSpec getSegmentGenerationJobSpec(String jobSpecFilePath, String propertyFilePath, Map<String, Object> context, Map<String, String> environmentValues) { Properties properties = new Properties(); if (propertyFilePath != null) { try { properties.load(FileUtils....
@Test public void testIngestionJobLauncherWithJsonTemplate() { SegmentGenerationJobSpec spec = IngestionJobLauncher.getSegmentGenerationJobSpec( GroovyTemplateUtils.class.getClassLoader().getResource("ingestion_job_json_spec_template.json").getFile(), GroovyTemplateUtils.class.getClassLoader().get...
static long getPidJiffies(VespaService service) { int pid = service.getPid(); try { BufferedReader in = new BufferedReader(new FileReader("/proc/" + pid + "/stat")); return getPidJiffies(in); } catch (FileNotFoundException ex) { log.log(Level.FINE, () -> "Unab...
@Test public void testPerProcessJiffies() { assertEquals(PER_PROC_JIFFIES[0], SystemPoller.getPidJiffies(new BufferedReader(new StringReader(perProcStats[0])))); assertEquals(PER_PROC_JIFFIES[1], SystemPoller.getPidJiffies(new BufferedReader(new StringReader(perProcStats[1])))); }
public static List<LayoutLocation> fromCompactListString(String compactList) { List<LayoutLocation> locs = new ArrayList<>(); if (!Strings.isNullOrEmpty(compactList)) { String[] items = compactList.split(TILDE); for (String s : items) { locs.add(fromCompactString(...
@Test public void fromCompactListEmpty() { List<LayoutLocation> locs = fromCompactListString(""); assertEquals("non-empty list", 0, locs.size()); }
@Override public NetworkId networkId() { return networkId; }
@Test public void testEquality() { DefaultVirtualDevice device1 = new DefaultVirtualDevice(NetworkId.networkId(0), DID1); DefaultVirtualDevice device2 = new DefaultVirtualDevice(NetworkId.networkId(0), DID1); DefaultVirtualDevice device3 = new ...
static ConfigNode propsToNode(Map<String, String> properties) { String rootNode = findRootNode(properties); ConfigNode root = new ConfigNode(rootNode); for (Map.Entry<String, String> e : properties.entrySet()) { parseEntry(e.getKey().replaceFirst(rootNode + ".", ""), e.getValue(), r...
@Test(expected = InvalidConfigurationException.class) public void shouldThrowWhenNoSharedRootNode() { Map<String, String> m = new HashMap<>(); m.put("foo1.bar1", "1"); m.put("foo2.bar2", "2"); ConfigNode configNode = PropertiesToNodeConverter.propsToNode(m); }
public static synchronized void createMissingParents(File baseDir) { checkNotNull(baseDir, "Base dir has to be provided."); if (!baseDir.exists()) { try { FileUtils.forceMkdirParent(baseDir); LOG.info("Created parents for base dir: {}", baseDir); ...
@Test void testCreateMissingParents(@TempDir Path tempDir) { File targetDir = tempDir.resolve("p1").resolve("p2").resolve("base-dir").toFile(); assertThat(targetDir.getParentFile().getParentFile()).doesNotExist(); ArtifactUtils.createMissingParents(targetDir); assertThat(targetDir.g...
public RemotingCommand rewriteRequestForStaticTopic(final UpdateConsumerOffsetRequestHeader requestHeader, final TopicQueueMappingContext mappingContext) { try { if (mappingContext.getMappingDetail() == null) { return null; } TopicQueueMappingDetail ma...
@Test public void testRewriteRequestForStaticTopic() throws RpcException, ExecutionException, InterruptedException { UpdateConsumerOffsetRequestHeader requestHeader = new UpdateConsumerOffsetRequestHeader(); requestHeader.setConsumerGroup(group); requestHeader.setTopic(topic); reques...
@Override public int run(String[] args) throws Exception { if (args.length != 2) { return usage(args); } String action = args[0]; String name = args[1]; int result; if (A_LOAD.equals(action)) { result = loadClass(name); } else if (A_CREATE.equals(action)) { //first load t...
@Test public void testLoadWithErrorInStaticInit() throws Throwable { run(FindClass.E_LOAD_FAILED, FindClass.A_LOAD, "org.apache.hadoop.util.TestFindClass$FailInStaticInit"); }
public int merge(final int key, final int value, final IntIntFunction remappingFunction) { requireNonNull(remappingFunction); final int missingValue = this.missingValue; if (missingValue == value) { throw new IllegalArgumentException("cannot accept missingValue"); ...
@Test void mergeThrowsIllegalArgumentExceptionIfValueIsMissingValue() { final int missingValue = 42; final Int2IntHashMap map = new Int2IntHashMap(missingValue); final int key = -9; final IntIntFunction remappingFunction = mock(IntIntFunction.class); final IllegalArgumen...
@Override public boolean isAvailable() { return true; }
@Test public void testIsAvailable() { assertTrue(randomLoadBalancerProvider.isAvailable()); }
public List<String> getJvmFlags() { return jvmFlags; }
@Test public void testParse_jvmFlags() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--jvm-flags=jvm-flag1,jvm-flag2", "my-app.jar"); assertThat(jarCommand.getJvmFlags()).isEqualTo(ImmutableList.of("jvm-flag1", "jvm-flag2")); }
public SimpleRabbitListenerContainerFactory decorateSimpleRabbitListenerContainerFactory( SimpleRabbitListenerContainerFactory factory ) { return decorateRabbitListenerContainerFactory(factory); }
@Test void decorateSimpleRabbitListenerContainerFactory_appends_TracingMessagePostProcessor_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setBeforeSendReplyPostProcessors(new UnzipPostProcessor()); assertThat(rabbitTracing.decorateSimpleR...
@Retries.RetryTranslated public void retry(String action, String path, boolean idempotent, Retried retrying, InvocationRaisingIOE operation) throws IOException { retry(action, path, idempotent, retrying, () -> { operation.apply(); return null; }); ...
@Test public void testRetryAWSConnectivity() throws Throwable { final AtomicInteger counter = new AtomicInteger(0); invoker.retry("test", null, false, () -> { if (counter.incrementAndGet() < ACTIVE_RETRY_LIMIT) { throw CLIENT_TIMEOUT_EXCEPTION; } }); assertE...
public void set(int index, E value) { assert value != null; Storage32 newStorage = storage.set(index, value); if (newStorage != storage) { storage = newStorage; } }
@Test public void testSetSparseToDense32() { // add some sparse entries for (int i = 0; i < ARRAY_STORAGE_32_MAX_SPARSE_SIZE / 2; ++i) { set(i * 2); verify(); } // restore density for (int i = 0; i < ARRAY_STORAGE_32_MAX_SPARSE_SIZE / 2; ++i) { ...
public static JsonElement parseString(String json) throws JsonSyntaxException { return parseReader(new StringReader(json)); }
@Test public void testParseUnquotedSingleWordStringFails() { assertThat(JsonParser.parseString("Test").getAsString()).isEqualTo("Test"); }
@Override public Optional<Period> chooseBin(final List<Period> availablePeriods, final QueryExecutionStats stats) { return availablePeriods.stream() .filter(per -> matches(per, stats.effectiveTimeRange())) .findFirst(); }
@Test void testReturnsEmptyOptionalWhenRangeExceedsLongestPeriod() { assertTrue( toTest.chooseBin( List.of(Period.days(1), Period.days(2)), getQueryExecutionStats(13, AbsoluteRange.create( DateTime.now(DateTimeZo...
public LoggerContext apply(LogLevelConfig logLevelConfig, Props props) { if (!ROOT_LOGGER_NAME.equals(logLevelConfig.getRootLoggerName())) { throw new IllegalArgumentException("Value of LogLevelConfig#rootLoggerName must be \"" + ROOT_LOGGER_NAME + "\""); } LoggerContext rootContext = getRootContext(...
@Test public void apply_sets_logger_to_process_property_over_global_property_if_both_set() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(WEB_SERVER).build(); props.set("sonar.log.level", "DEBUG"); props.set("sonar.log.level.web", "TRACE"); LoggerContext context = underTest.apply(config, ...
@Override public ApplicationAttemptId getApplicationAttemptId() { return this.appAttemptId; }
@Test (timeout = 180000) public void testStoreAllContainerMetrics() throws Exception { Configuration conf = new Configuration(); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); conf.setBoolean( YarnConfiguration.APPLICATION_HISTORY_SAVE_NON_AM_CONTAINER_META_INFO, true); MockRM r...
public AssessmentResult verify( final Action expectedAction, final String input, final String ip) throws IOException { final String[] parts = input.split("\\" + SEPARATOR, 4); // we allow missing actions, if we're missing 1 part, assume it's the action if (parts.length < 4) { throw ...
@Test public void choose() throws IOException { String ainput = String.join(SEPARATOR, PREFIX_A, CHALLENGE_SITE_KEY, "challenge", TOKEN); String binput = String.join(SEPARATOR, PREFIX_B, CHALLENGE_SITE_KEY, "challenge", TOKEN); final CaptchaClient a = mockClient(PREFIX_A); final CaptchaClient b = mock...
@Override public void run() { if (backgroundJobServer.isNotReadyToProcessJobs()) return; try (PeriodicTaskRunInfo runInfo = taskStatistics.startRun(backgroundJobServerConfiguration())) { tasks.forEach(task -> task.run(runInfo)); runInfo.markRunAsSucceeded(); } catch ...
@Test void jobHandlersStopsBackgroundJobServerAndLogsStorageProviderExceptionIfTooManyStorageExceptions() { Task mockedTask = mockTaskThatThrows(new StorageException("a storage exception")); JobHandler jobHandler = createJobHandlerWithTask(mockedTask); for (int i = 0; i <= 5; i++) { ...
@Override public void upgrade() { if (hasBeenRunSuccessfully()) { LOG.debug("Migration already completed."); return; } final Set<String> dashboardIdToViewId = new HashSet<>(); final Consumer<String> recordMigratedDashboardIds = dashboardIdToViewId::add; ...
@Test @MongoDBFixtures("sample_dashboard_with_unknown_widget.json") public void migrateSampleDashboardWithUnknownWidget() { this.migration.upgrade(); final MigrationCompleted migrationCompleted = captureMigrationCompleted(); assertThat(migrationCompleted.migratedDashboardIds()).contains...
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testRemoveValueTTL() throws InterruptedException { RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simple"); map.put(new SimpleKey("1"), new SimpleValue("2"), Duration.ofSeconds(1)); boolean res = map.remove(new SimpleKey("1"), new SimpleValue("2"...
@Override public String toString() { var roles = Arrays.toString(this.roles.keySet().toArray()); return "Customer{roles=" + roles + "}"; }
@Test void toStringTest() { var core = new CustomerCore(); core.addRole(Role.BORROWER); assertEquals("Customer{roles=[BORROWER]}", core.toString()); core = new CustomerCore(); core.addRole(Role.INVESTOR); assertEquals("Customer{roles=[INVESTOR]}", core.toString()); core = new CustomerCor...
public RingbufferConfig setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount); return this; }
@Test public void setAsyncBackupCount() { RingbufferConfig config = new RingbufferConfig(NAME); config.setAsyncBackupCount(4); assertEquals(4, config.getAsyncBackupCount()); }
private String getEnv(String envName, InterpreterLaunchContext context) { String env = context.getProperties().getProperty(envName); if (StringUtils.isBlank(env)) { env = System.getenv(envName); } if (StringUtils.isBlank(env)) { LOGGER.warn("environment variable: {} is empty", envName); ...
@Test void testConnectTimeOut() throws IOException { SparkInterpreterLauncher launcher = new SparkInterpreterLauncher(zConf, null); Properties properties = new Properties(); properties.setProperty("SPARK_HOME", sparkHome); properties.setProperty( ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPR...
@Override @MethodNotAvailable public CompletionStage<Void> setAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testSetAsyncWithTtl() { adapter.setAsync(42, "value", 1, TimeUnit.MILLISECONDS); }
@Udf(description = "Splits a string into an array of substrings based on a delimiter.") public List<String> split( @UdfParameter( description = "The string to be split. If NULL, then function returns NULL.") final String string, @UdfParameter( description = "The delimiter to spli...
@Test public void shouldSplitBytesByGivenDelimiter() { assertThat( splitUdf.split( X_DASH_Y_BYTES, ByteBuffer.wrap(new byte[]{'-'})), contains( ByteBuffer.wrap(new byte[]{'x'}), ByteBuffer.wrap(new byte[]{'y'}))); assertThat( splitUdf.sp...
@SuppressWarnings("DataFlowIssue") public static CommandExecutor newInstance(final MySQLCommandPacketType commandPacketType, final CommandPacket commandPacket, final ConnectionSession connectionSession) throws SQLException { if (commandPacket instanceof SQLReceivedPacket) { log.debug("Execute pa...
@Test void assertNewInstanceWithComResetConnection() throws SQLException { assertThat(MySQLCommandExecutorFactory.newInstance(MySQLCommandPacketType.COM_RESET_CONNECTION, mock(MySQLComSetOptionPacket.class), connectionSession), instanceOf(MySQLComResetConnectionExecutor.class)); }
@Override public RENAME3Response rename(XDR xdr, RpcInfo info) { return rename(xdr, getSecurityHandler(info), info.remoteAddress()); }
@Test(timeout = 60000) public void testRename() throws Exception { HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir); long dirId = status.getFileId(); int namenodeId = Nfs3Utils.getNamenodeId(config); XDR xdr_req = new XDR(); FileHandle handle = new FileHandle(dirId, namenodeId); ...
@Nullable Integer getHttpTimeout() { return httpTimeout; }
@Test public void testGetHttpTimeout() { Request request = Request.builder().build(); Assert.assertNull(request.getHttpTimeout()); }
@Override public SqlRequest refactor(QueryParamEntity entity, Object... args) { if (injector == null) { initInjector(); } return injector.refactor(entity, args); }
@Test void testWith() { QueryAnalyzerImpl analyzer = new QueryAnalyzerImpl( database, "WITH RECURSIVE Tree AS (\n" + "\n" + " SELECT id\n" + " FROM s_test\n" + " WHERE id = ? \n" + "\t\n" + ...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testBraceletOfClayUseTrahaearn1FreeInvSlot() { // Equip bracelet of clay ItemContainer equipmentItemContainer = mock(ItemContainer.class); when(client.getItemContainer(InventoryID.EQUIPMENT)) .thenReturn(equipmentItemContainer); when(equipmentItemContainer.contains(ItemID.BRACELET_OF_CLAY...
public static void mergeMetrics(ClusterMetricsInfo metrics, ClusterMetricsInfo metricsResponse) { metrics.setAppsSubmitted( metrics.getAppsSubmitted() + metricsResponse.getAppsSubmitted()); metrics.setAppsCompleted( metrics.getAppsCompleted() + metricsResponse.getAppsCompleted()); metr...
@Test public void testMergeMetrics() { ClusterMetricsInfo metrics = new ClusterMetricsInfo(); ClusterMetricsInfo metricsResponse = new ClusterMetricsInfo(); long seed = System.currentTimeMillis(); setUpClusterMetrics(metrics, seed); // ensure that we don't reuse the same seed when setting up metr...
public void notify(PluginJarChangeListener listener, Collection<BundleOrPluginFileDetails> knowPluginFiles, Collection<BundleOrPluginFileDetails> currentPluginFiles) { List<BundleOrPluginFileDetails> oldPlugins = new ArrayList<>(knowPluginFiles); subtract(oldPlugins, currentPluginFiles).forEach(listene...
@Test void shouldNotifyWhenPluginIsRemoved() { final PluginJarChangeListener listener = mock(PluginJarChangeListener.class); BundleOrPluginFileDetails pluginOne = mock(BundleOrPluginFileDetails.class); BundleOrPluginFileDetails pluginTwo = mock(BundleOrPluginFileDetails.class); Bundl...
public static String readFile(String path, String fileName) { File file = openFile(path, fileName); if (file.exists()) { return readFile(file); } return null; }
@Test void testReadFileWithPath() { assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName())); }
public static IntrinsicMapTaskExecutor withSharedCounterSet( List<Operation> operations, CounterSet counters, ExecutionStateTracker executionStateTracker) { return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker); }
@Test public void testNoReadOperation() throws Exception { // Test MapTaskExecutor without ReadOperation. List<Operation> operations = Arrays.<Operation>asList(createOperation("o1", 1), createOperation("o2", 2)); ExecutionStateTracker stateTracker = ExecutionStateTracker.newForTest(); try (Int...
@Override public Optional<QueryId> chooseQueryToKill(List<QueryMemoryInfo> runningQueries, List<MemoryInfo> nodes) { QueryId biggestQuery = null; long maxMemory = 0; for (QueryMemoryInfo query : runningQueries) { long bytesUsed = query.getMemoryReservation(); if (...
@Test public void testGeneralPoolHasNoReservation() { int reservePool = 10; int generalPool = 12; Map<String, Map<String, Long>> queries = ImmutableMap.<String, Map<String, Long>>builder() .put("q_1", ImmutableMap.of("n1", 0L, "n2", 0L, "n3", 0L, "n4", 0L, "n5", 0L)) ...
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); }...
@Test public void bytesToConnect() { ByteBuffer reference = ByteBuffer.wrap(Utils.utf8("test-string")); String msg = "{ \"schema\": { \"type\": \"bytes\" }, \"payload\": \"dGVzdC1zdHJpbmc=\" }"; SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes()); ByteBuffe...
@Override public UpdateSchema requireColumn(String name) { internalUpdateColumnRequirement(name, false); return this; }
@Test public void testRequireColumn() { Schema schema = new Schema(optional(1, "id", Types.IntegerType.get())); Schema expected = new Schema(required(1, "id", Types.IntegerType.get())); assertThatThrownBy(() -> new SchemaUpdate(schema, 1).requireColumn("id")) .isInstanceOf(IllegalArgumentExceptio...
public RegistryBuilder subscribe(Boolean subscribe) { this.subscribe = subscribe; return getThis(); }
@Test void subscribe() { RegistryBuilder builder = new RegistryBuilder(); builder.subscribe(true); Assertions.assertTrue(builder.build().isSubscribe()); }
List<ParsedTerm> identifyUnknownFields(final Set<String> availableFields, final List<ParsedTerm> terms) { final Map<String, List<ParsedTerm>> groupedByField = terms.stream() .filter(t -> !t.isDefaultField()) .filter(term -> !SEARCHABLE_ES_FIELDS.contains(term.getRealFieldName()))...
@Test void testDoesNotIdentifyDefaultFieldAsUnknown() { final List<ParsedTerm> unknownFields = toTest.identifyUnknownFields( Set.of("some_normal_field"), List.of(ParsedTerm.create(ParsedTerm.DEFAULT_FIELD, "Haba, haba, haba!")) ); assertTrue(unknownFields.isEm...
@Bean public BulkheadRegistry bulkheadRegistry( BulkheadConfigurationProperties bulkheadConfigurationProperties, EventConsumerRegistry<BulkheadEvent> bulkheadEventConsumerRegistry, RegistryEventConsumer<Bulkhead> bulkheadRegistryEventConsumer, @Qualifier("compositeBulkheadCustomizer"...
@Test public void testCreateBulkHeadRegistryWithSharedConfigs() { //Given io.github.resilience4j.common.bulkhead.configuration.CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new io.github.resilience4j.common.bulkhead.configuration.CommonBulkheadConfigurationProperties.I...
public byte[] verifyMessage(ContentInfo signedMessage, Date date, String oid) { return encapsulatedData(verify(signedMessage, date), oid); }
@Test public void verifyValidCmsWithOid() throws Exception { final ContentInfo signedMessage = ContentInfo.getInstance(fixture()); final byte[] data = new CmsVerifier(new CertificateVerifier.None()).verifyMessage( signedMessage, LdsSecurityObject.OID ); assertEquals("SSSS...
public V get(K key) { V value = getNullable(key); if (value == null) { throw new IllegalStateException("No cache entry found for key: " + key); } return value; }
@Test public void get_throws_exception_if_not_exists() { when(loader.load("foo")).thenReturn("bar"); assertThat(cache.get("foo")).isEqualTo("bar"); assertThat(cache.get("foo")).isEqualTo("bar"); verify(loader, times(1)).load("foo"); assertThatThrownBy(() -> cache.get("not_exists")) .isInsta...
public void setAuthenticationTokenFactory(AuthenticationTokenFactory authenticationTokenFactory) { this.authenticationTokenFactory = authenticationTokenFactory; }
@Test public void testSetAuthenticationTokenFactory() { AuthenticationTokenFactory factory = new AuthenticationTokenFactory() { @Override public AuthenticationToken getAuthenticationToken(SubjectConnectionReference ref) throws Exception { return null; } ...
public void setField(String name, String value) { validateField(name, value); objectMap.put(name, new ConfigPayloadBuilder(value)); }
@Test public void require_that_simple_fields_can_be_overwritten() { ConfigPayloadBuilder builder = new ConfigPayloadBuilder(); builder.setField("foo", "bar"); builder.setField("foo", "baz"); Cursor root = createSlime(builder); // XXX: Not sure if this is the _right_ behavior....
@Override public ConsumerBuilder<T> loadConf(Map<String, Object> config) { this.conf = ConfigurationDataUtils.loadData(config, conf, ConsumerConfigurationData.class); return this; }
@Test public void testLoadConf() throws Exception { ConsumerBuilderImpl<byte[]> consumerBuilder = createConsumerBuilder(); String jsonConf = ("{\n" + " 'topicNames' : [ 'new-topic' ],\n" + " 'topicsPattern' : 'new-topics-pattern',\n" + " 'subscriptionNam...
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) { final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid); final HttpRequest request = HttpRequest.newBuilder() .uri(deleteUri) .DELETE() .header(HttpHeaders...
@Test void deleteStoredData() { final String username = RandomStringUtils.randomAlphabetic(16); final String password = RandomStringUtils.randomAlphanumeric(32); when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn( new ExternalServiceCredentials(username, password)); wireMock....
public static Date parse(String date, ParsePosition pos) throws ParseException { Exception fail = null; try { int offset = pos.getIndex(); // extract year int year = parseInt(date, offset, offset += 4); if (checkOffset(date, offset, '-')) { offset += 1; } // extract...
@Test @SuppressWarnings("UndefinedEquals") public void testDateParseWithTimezone() throws ParseException { String dateStr = "2018-06-25T00:00:00-03:00"; Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0)); GregorianCalendar calendar = createUtcCalendar(); calendar.set(2018, Calendar.JUNE, ...
@Override public List<Document> get() { try (var input = markdownResource.getInputStream()) { Node node = parser.parseReader(new InputStreamReader(input)); DocumentVisitor documentVisitor = new DocumentVisitor(config); node.accept(documentVisitor); return documentVisitor.getDocuments(); } catch (IO...
@Test void testWithFormatting() { MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/with-formatting.md"); List<Document> documents = reader.get(); assertThat(documents).hasSize(2) .extracting(Document::getMetadata, Document::getContent) .containsOnly(tuple(Map.of("category", "header_...
public static boolean needsQuotes(final String identifier) { return !(isValid(identifier) && upperCase(identifier)); }
@Test public void shouldNotNeedBackQuotes() { // Given: final String[] identifiers = new String[]{ "FOO", // nothing special "TABLES", // in vocabulary but non-reserved "`SELECT`" // already has back quotes }; // Then: for (final String identifier : identifiers) { ...
public QueryCacheConfig setBatchSize(int batchSize) { this.batchSize = checkPositive("batchSize", batchSize); return this; }
@Test(expected = IllegalArgumentException.class) public void testSetBatchSize_throwsException_whenNotPositive() { QueryCacheConfig config = new QueryCacheConfig(); config.setBatchSize(-1); }
@Override public void countDown() { get(countDownAsync()); }
@Test public void testCountDown() throws InterruptedException { RCountDownLatch latch = redisson.getCountDownLatch("latch"); latch.trySetCount(2); Assertions.assertEquals(2, latch.getCount()); latch.countDown(); Assertions.assertEquals(1, latch.getCount()); latch.coun...
public static String getRejectTips(PolarisRateLimitProperties polarisRateLimitProperties) { String tips = polarisRateLimitProperties.getRejectRequestTips(); if (StringUtils.hasText(tips)) { return tips; } String rejectFilePath = polarisRateLimitProperties.getRejectRequestTipsFilePath(); if (StringUtils.h...
@Test public void testGetRejectTips() { PolarisRateLimitProperties polarisRateLimitProperties = new PolarisRateLimitProperties(); // RejectRequestTips polarisRateLimitProperties.setRejectRequestTips("RejectRequestTips"); assertThat(RateLimitUtils.getRejectTips(polarisRateLimitProperties)).isEqualTo("RejectReq...
public void addChild(Entry entry) { childEntries.add(entry); entry.setParent(this); }
@Test public void equalEntriesWithChild() { Entry firstStructureWithEntry = new Entry(); final Entry firstEntry = new Entry(); firstStructureWithEntry.addChild(firstEntry); Entry otherStructureWithEntry = new Entry(); final Entry otherEntry = new Entry(); otherStructureWithEntry.addChild(otherEntry); ...
public void validate(String effectivePath, String artifactMD5, ChecksumValidationPublisher checksumValidationPublisher) { if (artifactMd5Checksums == null) { checksumValidationPublisher.md5ChecksumFileNotFound(); return; } String expectedMd5 = artifactMd5Checksums.md5For(...
@Test public void shouldCallbackWhenMd5Mismatch() throws IOException { when(checksums.md5For("path")).thenReturn(CachedDigestUtils.md5Hex("something")); final ByteArrayInputStream stream = new ByteArrayInputStream("foo".getBytes()); new ChecksumValidator(checksums).validate("path", CachedDi...
@Override protected URIRegisterDTO buildURIRegisterDTO(final ApplicationContext context, final Map<String, Object> beans) { try { return URIRegisterDTO.builder() .contextPath(getContextPath()) .appName(getAppName()) .protocol(protocol) ...
@Test public void testBuildURIRegisterDTO() { URIRegisterDTO uriRegisterDTO = eventListener.buildURIRegisterDTO(applicationContext, Collections.emptyMap()); assertNotNull(uriRegisterDTO); assertEquals("/contextPath", uriRegisterDTO.getContextPath()); assertEquals("appName", uriRegist...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { boolean satisfied = false; // No trading history or no position opened, no loss if (tradingRecord != null) { Position currentPosition = tradingRecord.getCurrentPosition(); if (currentPositi...
@Test public void isSatisfiedWorksForSell() { final TradingRecord tradingRecord = new BaseTradingRecord(Trade.TradeType.SELL); final Num tradedAmount = numOf(1); // 5% stop-loss StopLossRule rule = new StopLossRule(closePrice, numOf(5)); assertFalse(rule.isSatisfied(0, null...
public String generateJWE(String data, String jwksUri) { JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A256GCM); JWEObject jwsObject = new JWEObject(header, new Payload(data)); logger.debug("jwt data: {}", data); try { var publicEncryptionKey = get...
@Test void generateJWETest() { //given //when provider.generateJWE("data", "jwskUri"); //then }
public static <T> LengthPrefixCoder<T> of(Coder<T> valueCoder) { checkNotNull(valueCoder, "Coder not expected to be null"); return new LengthPrefixCoder<>(valueCoder); }
@Test public void testRegisterByteSizeObserver() throws Exception { CoderProperties.testByteCount( LengthPrefixCoder.of(VarIntCoder.of()), Coder.Context.NESTED, new Integer[] {0, 10, 1000}); }
protected List<ScenarioResult> getScenarioResultsFromGivenFacts(ScesimModelDescriptor scesimModelDescriptor, List<ScenarioExpect> scenarioOutputsPerFact, InstanceGiven input, ...
@Test public void getScenarioResultsTest() { List<InstanceGiven> scenario1Inputs = extractGivenValuesForScenario1(); List<ScenarioExpect> scenario1Outputs = runnerHelper.extractExpectedValues(scenario1.getUnmodifiableFactMappingValues()); assertThat(scenario1Inputs).isNotEmpty(); I...
public Promise<Void> gracefullyShutdownClientChannels() { return gracefullyShutdownClientChannels(ShutdownType.SHUTDOWN); }
@Test @SuppressWarnings("unchecked") void discoveryShutdown() { String configName = "server.outofservice.connections.shutdown"; AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); try { configuration.setProperty(configName, "true"); Eu...