focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean isUpgrade() { return oldVersion.isLessThan(newVersion); }
@Test public void testIsUpgrade() { assertTrue(CHANGE_3_0_IV1_TO_3_3_IV0.isUpgrade()); assertFalse(CHANGE_3_3_IV0_TO_3_0_IV1.isUpgrade()); }
@Override // Camel calls this method if the endpoint isSynchronous(), as the // KafkaEndpoint creates a SynchronousDelegateProducer for it public void process(Exchange exchange) throws Exception { // is the message body a list or something that contains multiple values Message message = exch...
@Test public void processRequiresTopicInEndpointOrInHeader() throws Exception { endpoint.getConfiguration().setTopic(null); Mockito.when(exchange.getIn()).thenReturn(in); Mockito.when(exchange.getMessage()).thenReturn(in); in.setHeader(KafkaConstants.PARTITION_KEY, 4); in.set...
@Override public long getMax() { if (values.length == 0) { return 0; } return values[values.length - 1]; }
@Test public void calculatesTheMaximumValue() throws Exception { assertThat(snapshot.getMax()) .isEqualTo(5); }
@Override public void run() { final Instant now = time.get(); try { final Collection<PersistentQueryMetadata> queries = engine.getPersistentQueries(); final Optional<Double> saturation = queries.stream() .collect(Collectors.groupingBy(PersistentQueryMetadata::getQueryApplicationId)) ...
@Test public void shouldAddPointsForQueriesSharingRuntimes() { // Given: final Instant start = Instant.now(); when(clock.get()).thenReturn(start); givenMetrics(kafkaStreams1) .withThreadStartTime("t1", start.minus(WINDOW.multipliedBy(2))) .withBlockedTime("t1", Duration.ofMinutes(2)); ...
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException("The level of the root logger cannot be set to null"); } leve...
@Test public void testEnabled_Info() throws Exception { root.setLevel(Level.INFO); checkLevelThreshold(loggerTest, Level.INFO); }
public static String encode(final String input) { try { final StringBuilder b = new StringBuilder(); final StringTokenizer t = new StringTokenizer(input, "/"); if(!t.hasMoreTokens()) { return input; } if(StringUtils.startsWith(input, St...
@Test public void testEncodeTrailingDelimiter() { assertEquals("/a/p/", URIEncoder.encode("/a/p/")); assertEquals("/p%20d/", URIEncoder.encode("/p d/")); }
public static Action resolve(Schema writer, Schema reader, GenericData data) { return resolve(Schema.applyAliases(writer, reader), reader, data, new HashMap<>()); }
@Test void resolveTime() { final Schema writeSchema = Schema.create(Schema.Type.INT); final Schema readSchema = new TimeConversions.TimeMicrosConversion().getRecommendedSchema(); // LONG Resolver.Action action = Resolver.resolve(writeSchema, readSchema); Assertions.assertNotNull(action); MatcherA...
@Override public void validate(final SingleRule rule, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database) { DropSchemaStatement dropSchemaStatement = (DropSchemaStatement) sqlStatementContext.getSqlStatement(); boolean containsCascade = dropSchemaStatement.isContain...
@Test void assertValidateWithNotExistedSchema() { ShardingSphereDatabase database = mockDatabase(); when(database.getSchema("not_existed_schema")).thenReturn(null); assertThrows(SchemaNotFoundException.class, () -> new SingleDropSchemaMetaDataValidator().validate(mock(SingleR...
@Override @SuppressWarnings("unchecked") public int run() throws IOException { RewriteOptions options = buildOptionsOrFail(); ParquetRewriter rewriter = new ParquetRewriter(options); rewriter.processBlocks(); rewriter.close(); return 0; }
@Test(expected = FileAlreadyExistsException.class) public void testRewriteCommandWithoutOverwrite() throws IOException { File file = parquetFile(); RewriteCommand command = new RewriteCommand(createLogger()); command.inputs = Arrays.asList(file.getAbsolutePath()); File output = new File(getTempFolder(...
@Override public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) { if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) { return resolveRequestConfig(propertyName); } else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX) && !propertyName.starts...
@Test public void shouldNotFindUnknownProducerPropertyIfStrict() { // Given: final String configName = StreamsConfig.PRODUCER_PREFIX + "custom.interceptor.config"; // Then: assertThat(resolver.resolve(configName, true), is(Optional.empty())); }
public String ldapLogin(String userId, String userPwd) { Properties searchEnv = getManagerLdapEnv(); LdapContext ctx = null; try { // Connect to the LDAP server and Authenticate with a service user of whom we know the DN and credentials ctx = new InitialLdapContext(search...
@Test public void ldapLoginError() throws NoSuchFieldException, IllegalAccessException { changeSslEnable(false); String email2 = ldapService.ldapLogin(username, "error password"); Assertions.assertNull(email2); }
@Override public KsMaterializedQueryResult<Row> get( final GenericKey key, final int partition, final Optional<Position> position ) { try { final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key); StateQueryRequest<ValueAndTimestamp<GenericRow>> ...
@Test public void shouldThrowIfRangeQueryResultIsError() { // Given: when(kafkaStreams.query(any())).thenReturn(getErrorResult()); // When: final Exception e = assertThrows( MaterializationException.class, () -> table.get(PARTITION, A_KEY, A_KEY2) ); // Then: assertThat(e...
public Future<Collection<Integer>> resizeAndReconcilePvcs(KafkaStatus kafkaStatus, List<PersistentVolumeClaim> pvcs) { Set<Integer> podIdsToRestart = new HashSet<>(); List<Future<Void>> futures = new ArrayList<>(pvcs.size()); for (PersistentVolumeClaim desiredPvc : pvcs) { Future<V...
@Test public void testVolumesBoundExpandableStorageClass(VertxTestContext context) { List<PersistentVolumeClaim> pvcs = List.of( createPvc("data-pod-0"), createPvc("data-pod-1"), createPvc("data-pod-2") ); ResourceOperatorSupplier supplier = ...
public static DockerContainerStatus getContainerStatus(String containerId, PrivilegedOperationExecutor privilegedOperationExecutor, Context nmContext) { try { String currentContainerStatus = executeStatusCommand(containerId, privilegedOperationExecutor, nmContext); Docker...
@Test public void testGetContainerStatus() throws Exception { for (DockerContainerStatus status : DockerContainerStatus.values()) { when(mockExecutor.executePrivilegedOperation(eq(null), any(PrivilegedOperation.class), eq(null), any(), eq(true), eq(false))) .thenReturn(status.getName());...
public static Context context(int ioThreads) { return new Context(ioThreads); }
@Test(expected = ZMQException.class) public void testBindInprocSameAddress() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket socket1 = context.socket(SocketType.REQ); ZMQ.Socket socket2 = context.socket(SocketType.REQ); socket1.bind("inproc://address.already.in.use"); ...
@SuppressWarnings("checkstyle:HiddenField") public AwsCredentialsProvider credentialsProvider( String accessKeyId, String secretAccessKey, String sessionToken) { if (!Strings.isNullOrEmpty(accessKeyId) && !Strings.isNullOrEmpty(secretAccessKey)) { if (Strings.isNullOrEmpty(sessionToken)) { ret...
@Test public void testCreatesNewInstanceOfDefaultCredentialsConfiguration() { AwsClientProperties awsClientProperties = new AwsClientProperties(); AwsCredentialsProvider credentialsProvider = awsClientProperties.credentialsProvider(null, null, null); AwsCredentialsProvider credentialsProvider2 = ...
@Udf(description = "Adds a duration to a timestamp") public Timestamp timestampAdd( @UdfParameter(description = "A unit of time, for example DAY or HOUR") final TimeUnit unit, @UdfParameter(description = "An integer number of intervals to add") final Integer interval, @UdfParameter(description = "A ...
@Test public void handleNullTimestamp() { // When: final Timestamp result = udf.timestampAdd(TimeUnit.MILLISECONDS, -300, null); // Then: assertNull(result); }
public static void tripSuggestions( List<CharSequence> suggestions, final int maxSuggestions, List<CharSequence> stringsPool) { while (suggestions.size() > maxSuggestions) { removeSuggestion(suggestions, maxSuggestions, stringsPool); } }
@Test public void testTrimSuggestionsWithRecycleBackToPool() { ArrayList<CharSequence> list = new ArrayList<>( Arrays.<CharSequence>asList( "typed", "something", "duped", new StringBuilder("duped"), "something")); Assert.assertEquals(0, mStringPool.size()); IMEUtil.tri...
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type =...
@Test public void applyGeneratesIntegerUsingJavaTypeLongPrimitiveWhenMinimumLessThanIntegerMin() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "integer"); obj...
public void writeTo(OutputStream out) throws IOException { if (image.getImageFormat() == OciManifestTemplate.class) { ociWriteTo(out); } else { dockerWriteTo(out); } }
@Test public void testWriteTo_oci() throws InvalidImageReferenceException, IOException, LayerPropertyNotFoundException { Image testImage = Image.builder(OciManifestTemplate.class).addLayer(mockLayer1).addLayer(mockLayer2).build(); ImageTarball imageTarball = new ImageTarball( ...
@Override public void configure(Map<String, ?> configs) { final SimpleConfig simpleConfig = new SimpleConfig(CONFIG_DEF, configs); final String field = simpleConfig.getString(FIELD_CONFIG); final String type = simpleConfig.getString(TARGET_TYPE_CONFIG); String formatPattern = simpleC...
@Test public void testConfigInvalidTargetType() { assertThrows(ConfigException.class, () -> xformValue.configure(Collections.singletonMap(TimestampConverter.TARGET_TYPE_CONFIG, "invalid"))); }
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { scheduledRepetitively.mark(); return delegate.scheduleAtFixedRate(new InstrumentedPeriodicRunnable(command, period, unit), initialDelay, period, unit); }
@Test public void testScheduleFixedRateCallable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); assertThat(completed.getCount()).isZero(); assertThat(duration.getCount()).isZero(); assertThat(scheduledOnce.getCount())...
@Override public boolean isPluginDisabled(String pluginId) { if (disabledPlugins.contains(pluginId)) { return true; } return !enabledPlugins.isEmpty() && !enabledPlugins.contains(pluginId); }
@Test public void testIsPluginDisabled() throws IOException { createEnabledFile(); createDisabledFile(); PluginStatusProvider statusProvider = new DefaultPluginStatusProvider(pluginsPath); assertFalse(statusProvider.isPluginDisabled("plugin-1")); assertTrue(statusProvider.i...
public static String md5Hex(String string) { return compute(string, DigestObjectPools.MD5); }
@Test public void shouldComputeForAnEmptyStringUsingMD5() { String fingerprint = ""; String digest = md5Hex(fingerprint); assertEquals(DigestUtils.md5Hex(fingerprint), digest); }
@VisibleForTesting public int getContainerReportFailedRetrieved() { return numGetContainerReportFailedRetrieved.value(); }
@Test public void testGetContainerReportFailed() { long totalBadBefore = metrics.getContainerReportFailedRetrieved(); badSubCluster.getContainerReport(); Assert.assertEquals(totalBadBefore + 1, metrics.getContainerReportFailedRetrieved()); }
public void perform(List<Exception> list, T obj) { do { try { op.operation(list); return; } catch (Exception e) { this.errors.add(e); if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) { this.handleError.handleIssue(obj, e); ...
@Test void performTest() { Retry.Operation op = (l) -> { if (!l.isEmpty()) { throw l.remove(0); } }; Retry.HandleErrorIssue<Order> handleError = (o, e) -> { }; var r1 = new Retry<>(op, handleError, 3, 30000, e -> DatabaseUnavailableException.class.isAssignableFrom(e.get...
@SuppressWarnings("unchecked") @Override public void execute(String mapName, Predicate predicate, Collection<Integer> partitions, Result result) { runUsingPartitionScanWithoutPaging(mapName, predicate, partitions, result); if (predicate instanceof PagingPredicateImpl pagingPredicate) { ...
@Test public void execute_fail_retryable() { PartitionScanRunner runner = mock(PartitionScanRunner.class); ParallelPartitionScanExecutor executor = executor(runner); Predicate<Object, Object> predicate = Predicates.equal("attribute", 1); QueryResult queryResult = new QueryResult(Iter...
@Override public boolean put(final V value, final T t) { addToCounter(); final boolean put = map.put(value, t); addToChangeSet(value, t); fire(); return put; }
@Test void testPut() throws Exception { map.put(new Value("hello"), "test"); assertThat(changeSet.getAdded().get(new Value("hello"))).contains("test"); assertThat(timesCalled).isEqualTo(1); }
@Override public void build(final DefaultGoPublisher publisher, final EnvironmentVariableContext environmentVariableContext, TaskExtension taskExtension, ArtifactExtension artifactExtension, PluginRequestProcessorRegistry pluginRequestProcessorRegistry, Charset consoleLogCharset) { Exe...
@Test public void shouldPublishErrorMessageIfPluginThrowsAnException() { PluggableTaskBuilder taskBuilder = new PluggableTaskBuilder(runIfConfigs, cancelBuilder, pluggableTask, TEST_PLUGIN_ID, "test-directory") { @Override protected ExecutionResult executeTask(Task task, DefaultGoPub...
static Logger configureHttpLogging(Level level) { // To instantiate the static HttpTransport logger field. // Fixes https://github.com/GoogleContainerTools/jib/issues/3156. new ApacheHttpTransport(); ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(level); Logger lo...
@Test public void testConfigureHttpLogging() { Logger logger = JibCli.configureHttpLogging(Level.ALL); assertThat(logger.getName()).isEqualTo("com.google.api.client.http.HttpTransport"); assertThat(logger.getLevel()).isEqualTo(Level.ALL); assertThat(logger.getHandlers()).hasLength(1); Handler han...
@VisibleForTesting Set<? extends Watcher> getEntries() { return Sets.newHashSet(entries); }
@Test public void testResetFromWatcher() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final WatcherRemovalFacade removerClient = (Wa...
public static <K,V> List<Pair<K,V>> mapToPair(Map<K,V> map) { List<Pair<K,V>> ret = new ArrayList<>(map.size()); for(Map.Entry<K,V> entry : map.entrySet()) { ret.add(Pair.of(entry.getKey(),entry.getValue())); } return ret; }
@Test public void testMapToPair() { Map<String,String> map = new HashMap<>(); for(int i = 0; i < 5; i++) { map.put(String.valueOf(i),String.valueOf(i)); } List<Pair<String, String>> pairs = FunctionalUtils.mapToPair(map); assertEquals(map.size(),pairs.size()); ...
MemberMap toMemberMap() { MemberImpl[] m = new MemberImpl[size()]; int ix = 0; for (MemberInfo memberInfo : members) { m[ix++] = memberInfo.toMember(); } return MemberMap.createNew(version, m); }
@Test public void toMemberMap() { int version = 5; MemberImpl[] members = MemberMapTest.newMembers(3); MembersView view = MembersView.createNew(version, Arrays.asList(members)); MemberMap memberMap = view.toMemberMap(); assertEquals(version, memberMap.getVersion()); ...
@Override public PageResult<ArticleCategoryDO> getArticleCategoryPage(ArticleCategoryPageReqVO pageReqVO) { return articleCategoryMapper.selectPage(pageReqVO); }
@Test @Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解 public void testGetArticleCategoryPage() { // mock 数据 ArticleCategoryDO dbArticleCategory = randomPojo(ArticleCategoryDO.class, o -> { // 等会查询到 o.setName(null); o.setPicUrl(null); o.setStatus(null); ...
static Properties readProps(List<String> producerProps, String producerConfig) throws IOException { Properties props = new Properties(); if (producerConfig != null) { props.putAll(Utils.loadProps(producerConfig)); } if (producerProps != null) for (String prop : pr...
@Test public void testReadProps() throws Exception { List<String> producerProps = Collections.singletonList("bootstrap.servers=localhost:9000"); File producerConfig = createTempFile("acks=1"); Properties prop = ProducerPerformance.readProps(producerProps, producerConfig.getAbsolutePath()); ...
public TreeCache start() throws Exception { Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started"); if (createParentNodes) { client.createContainers(root.path); } client.getConnectionStateListenable().addListener(connectionSt...
@Test public void testSyncInitialPopulation() throws Exception { cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); ...
public Span nextSpan(TraceContextOrSamplingFlags extracted) { if (extracted == null) throw new NullPointerException("extracted == null"); TraceContext context = extracted.context(); if (context != null) return newChild(context); TraceIdContext traceIdContext = extracted.traceIdContext(); if (traceI...
@Test void nextSpan_fromFlags_resultantSpanIsLocalRoot() { Span span = tracer.nextSpan(TraceContextOrSamplingFlags.create(SamplingFlags.SAMPLED)); assertThat(span.context().spanId()).isEqualTo(span.context().localRootId()); // Sanity check assertThat(span.context().isLocalRoot()).isTrue(); }
@Nonnull public static List<String> fastSplit(@Nonnull String input, boolean includeEmpty, char split) { StringBuilder sb = new StringBuilder(); ArrayList<String> words = new ArrayList<>(); words.ensureCapacity(input.length() / 5); char[] strArray = input.toCharArray(); for (char c : strArray) { if (c == ...
@Test void testFastSplit() { // Empty discarded assertEquals(List.of("a", "b", "c", "d"), StringUtil.fastSplit("a/b/c/d", false, '/')); assertEquals(List.of("a", "b", "c"), StringUtil.fastSplit("a/b/c/", false, '/')); assertEquals(List.of("b", "c", "d"), StringUtil.fastSplit("/b/c/d", false, '/')); assertEqu...
public void validate(String clientId, String clientSecret, String workspace) { Token token = validateAccessToken(clientId, clientSecret); if (token.getScopes() == null || !token.getScopes().contains("pullrequest")) { LOG.info(MISSING_PULL_REQUEST_READ_PERMISSION + String.format(SCOPE, token.getScopes()))...
@Test public void validate_fails_with_IAE_if_timeout() { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); assertThatIllegalArgumentException() .isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace")); }
private ServiceConfig() { this(CONFIG_NAME); }
@Test public void testServiceConfig() { ServiceConfig serviceConfig = (ServiceConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ServiceConfig.class); List<Map<String, Object>> singletons = serviceConfig.getSingletons(); Assert.assertTrue(singletons.size() > 0); }
Object getCellValue(Cell cell, Schema.FieldType type) { ByteString cellValue = cell.getValue(); int valueSize = cellValue.size(); switch (type.getTypeName()) { case BOOLEAN: checkArgument(valueSize == 1, message("Boolean", 1)); return cellValue.toByteArray()[0] != 0; case BYTE: ...
@Test public void shouldParseStringType() { byte[] value = "stringValue".getBytes(UTF_8); assertEquals("stringValue", PARSER.getCellValue(cell(value), STRING)); }
public long getNumBlocksFailedToUncache() { return numBlocksFailedToUncache.longValue(); }
@Test(timeout=60000) public void testUncacheUnknownBlock() throws Exception { // Create a file Path fileName = new Path("/testUncacheUnknownBlock"); int fileLen = 4096; DFSTestUtil.createFile(fs, fileName, fileLen, (short)1, 0xFDFD); HdfsBlockLocation[] locs = (HdfsBlockLocation[])fs.getFileBlockL...
public static boolean isRetryOrDlqTopic(String topic) { if (StringUtils.isBlank(topic)) { return false; } return topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX) || topic.startsWith(MixAll.DLQ_GROUP_TOPIC_PREFIX); }
@Test public void testIsRetryOrDlqTopicWithEmptyTopic() { String topic = ""; boolean result = BrokerMetricsManager.isRetryOrDlqTopic(topic); assertThat(result).isFalse(); }
@Override public <T> List<T> toList(DataTable dataTable, Type itemType) { requireNonNull(dataTable, "dataTable may not be null"); requireNonNull(itemType, "itemType may not be null"); if (dataTable.isEmpty()) { return emptyList(); } ListOrProblems<T> result = to...
@Test void convert_to_optional_list() { DataTable table = parse("", "| 11.22 |", "| 255.999 |", "| |"); List<Optional<BigDecimal>> expected = asList( Optional.of(new BigDecimal("11.22")), Optional.of(new BigDecimal("255.999")), ...
public long get(final long key) { final long[] entries = this.entries; int index = evenLongHash(key, mask); long candidateKey; while ((candidateKey = entries[index]) != missingValue) { if (candidateKey == key) { return entries[index + 1]; } ...
@Test public void getShouldReturnMissingValueWhenEmpty() { assertEquals(MISSING_VALUE, map.get(1L)); }
@Override public List<byte[]> clusterGetKeysInSlot(int slot, Integer count) { RFuture<List<byte[]>> f = executorService.readAsync((String)null, ByteArrayCodec.INSTANCE, CLUSTER_GETKEYSINSLOT, slot, count); return syncFuture(f); }
@Test public void testClusterGetKeysInSlot() { testInCluster(connection -> { connection.flushAll(); List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10); assertThat(keys).isEmpty(); }); }
@Override public final List<? extends FileBasedSource<T>> split( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { // This implementation of method split is provided to simplify subclasses. Here we // split a FileBasedSource based on a file pattern to FileBasedSources based on ful...
@Test public void testReadAllSplitsOfFilePattern() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); List<String> data1 = createStringDataset(3, 50); File file1 = createFileWithData("file1", data1); List<String> data2 = createStringDataset(3, 50); createFileWithData("f...
@Override public void checkTopicAccess( final KsqlSecurityContext securityContext, final String topicName, final AclOperation operation ) { checkAccess(new CacheKey(securityContext, AuthObjectType.TOPIC, topicName, operation)); }
@Test public void shouldThrowAuthorizationExceptionWhenBackendTopicValidatorIsDenied() { // Given doThrow(KsqlTopicAuthorizationException.class).when(backendValidator) .checkTopicAccess(securityContext, TOPIC_1, AclOperation.READ); // When: assertThrows( KsqlTopicAuthorizationExceptio...
public TopicStatsImpl add(TopicStats ts) { TopicStatsImpl stats = (TopicStatsImpl) ts; this.count++; this.msgRateIn += stats.msgRateIn; this.msgThroughputIn += stats.msgThroughputIn; this.msgRateOut += stats.msgRateOut; this.msgThroughputOut += stats.msgThroughputOut; ...
@Test public void testAdd_EarliestMsgPublishTimeInBacklogs_Earliest() { TopicStatsImpl stats1 = new TopicStatsImpl(); stats1.earliestMsgPublishTimeInBacklogs = 10L; TopicStatsImpl stats2 = new TopicStatsImpl(); stats2.earliestMsgPublishTimeInBacklogs = 20L; TopicStatsImpl a...
public CompiledPipeline.CompiledExecution buildExecution() { return buildExecution(false); }
@SuppressWarnings({"unchecked"}) @Test public void moreThan255Parents() throws Exception { final ConfigVariableExpander cve = ConfigVariableExpander.withoutSecret(EnvironmentVariableProvider.defaultProvider()); final PipelineIR pipelineIR = ConfigCompiler.configToPipelineIR( IRHe...
public void generateAcknowledgementPayload( MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode) throws MllpAcknowledgementGenerationException { generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null); }
@Test public void testGenerateAcknowledgementPayloadFromNullMessage() { MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub()); assertThrows(MllpAcknowledgementGenerationException.class, () -> hl7util.generateAcknowledgementPayload(mllpSocketBuffer, null, "A...
public static String generateNewId(String id, int targetLength) { if (id.length() <= targetLength) { return id; } if (targetLength <= 8) { throw new IllegalArgumentException("targetLength must be greater than 8"); } HashFunction hashFunction = goodFastHash(32); String hash = hashFu...
@Test public void testGenerateNewIdShouldThrowExceptionWhenTargetLengthIsNotGreaterThanEight() { String id = "long-test-id"; assertThrows(IllegalArgumentException.class, () -> generateNewId(id, 8)); }
@Override public void run() { if (!ignoreListenShutdownHook && destroyed.compareAndSet(false, true)) { if (logger.isInfoEnabled()) { logger.info("Run shutdown hook now."); } doDestroy(); } }
@Test public void testDestoryWithModuleManagedExternally() throws InterruptedException { applicationModel.getModuleModels().get(0).setLifeCycleManagedExternally(true); new Thread(() -> { applicationModel.getModuleModels().get(0).destroy(); }) .star...
public static Map<String, String> toStringMap(String... pairs) { Map<String, String> parameters = new HashMap<>(); if (ArrayUtils.isEmpty(pairs)) { return parameters; } if (pairs.length > 0) { if (pairs.length % 2 != 0) { throw new IllegalArgument...
@Test void testStringMap1() { assertThat(toStringMap("key", "value"), equalTo(Collections.singletonMap("key", "value"))); }
@Override public HttpRestResult<String> httpPost(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception { final long endTime = System.currentTimeMillis() + readTimeoutMs; String currentServerAddr = serverListMgr.getC...
@Test void testHttpPostFailed() throws Exception { assertThrows(ConnectException.class, () -> { when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); ...
public static void generate(String cluster, OutputStream out, List<PrometheusRawMetricsProvider> metricsProviders) throws IOException { ByteBuf buf = PulsarByteBufAllocator.DEFAULT.heapBuffer(); try { SimpleTextOutputStream stream = new SimpleTextO...
@Test public void testGenerateSystemMetricsWithSpecifyCluster() throws Exception { String defaultClusterValue = "cluster_test"; String specifyClusterValue = "lb_x"; String metricsName = "label_contains_cluster" + randomString(); Counter counter = new Counter.Builder() ...
@Override public Mono<ConfirmUsernameHashResponse> confirmUsernameHash(final ConfirmUsernameHashRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); if (request.getUsernameHash().isEmpty()) { throw Status.INVALID_ARGUMENT .withDes...
@Test void confirmUsernameHashInvalidProof() throws BaseUsernameException { final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH); final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32); final byte[] zkProof = TestRandomUtil.nextBytes(32); final Accoun...
@Override public final InputStream getInputStream(final int columnIndex, final String type) throws SQLException { InputStream result = getCurrentQueryResult().getInputStream(columnIndex, type); wasNull = getCurrentQueryResult().wasNull(); return result; }
@Test void assertGetInputStream() throws SQLException { QueryResult queryResult = mock(QueryResult.class); InputStream value = mock(InputStream.class); when(queryResult.getInputStream(1, "Ascii")).thenReturn(value); streamMergedResult.setCurrentQueryResult(queryResult); asser...
public static List<String> parseAddressList(String addressInfo) { if (StringUtils.isBlank(addressInfo)) { return Collections.emptyList(); } List<String> addressList = new ArrayList<>(); String[] addresses = addressInfo.split(ADDRESS_SEPARATOR); for (String address : addresses) { URI uri = URI.create(add...
@Test public void testNullStr() { List<String> result = AddressUtils.parseAddressList(null); assertThat(result).isNotNull(); assertThat(result).isEmpty(); }
public EmailVerifyResult verifyEmail(long accountId, EmailVerifyRequest request) { Map<String, Object> resultMap = accountClient.verifyEmail(accountId, request.getVerificationCode()); return objectMapper.convertValue(resultMap, EmailVerifyResult.class); }
@Test public void testVerifyEmail() { EmailVerifyRequest request = new EmailVerifyRequest(); request.setVerificationCode("code"); Map<String, Object> result = Map.of( "status", "OK", "error", "custom error", "remaining_attempts", "5"); ...
public Optional<Integer> loadInstanceWorkerId(final String instanceId) { try { String workerId = repository.query(ComputeNode.getInstanceWorkerIdNodePath(instanceId)); return Strings.isNullOrEmpty(workerId) ? Optional.empty() : Optional.of(Integer.valueOf(workerId)); } catch (fin...
@Test void assertLoadInstanceWorkerId() { InstanceMetaData instanceMetaData = new ProxyInstanceMetaData("foo_instance_id", 3307); final String instanceId = instanceMetaData.getId(); new ComputeNodePersistService(repository).loadInstanceWorkerId(instanceId); verify(repository).query(C...
@Override public void updateJobResourceRequirements(JobResourceRequirements jobResourceRequirements) { if (settings.getExecutionMode() == SchedulerExecutionMode.REACTIVE) { throw new UnsupportedOperationException( "Cannot change the parallelism of a job running in reactive mo...
@Test void testRequirementLowerBoundDecreaseAfterResourceScarcityBelowAvailableSlots() throws Exception { final JobGraph jobGraph = createJobGraph(); final DefaultDeclarativeSlotPool declarativeSlotPool = createDeclarativeSlotPool(jobGraph.getJobID()); final int...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatCreateTableStatementWithImplicitKey() { // Given: final CreateTable createTable = new CreateTable( TEST, ELEMENTS_WITHOUT_KEY, false, false, SOME_WITH_PROPS, false); // When: final String sql = SqlFormatter.formatSql(create...
@NotNull public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) { // 优先从 DB 中获取,因为 code 有且可以使用一次。 // 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次 SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state); i...
@Test public void testAuthSocialUser_update() { // 准备参数 Integer socialType = SocialTypeEnum.GITEE.getType(); Integer userType = randomEle(SocialTypeEnum.values()).getType(); String code = "tudou"; String state = "yuanma"; // mock 数据 socialUserMapper.insert(ran...
@Override public synchronized ScheduleResult schedule() { dropListenersFromWhenFinishedOrNewLifespansAdded(); int overallSplitAssignmentCount = 0; ImmutableSet.Builder<RemoteTask> overallNewTasks = ImmutableSet.builder(); List<ListenableFuture<?>> overallBlockedFutures = new Arr...
@Test public void testBalancedSplitAssignment() { // use private node manager so we can add a node later InMemoryNodeManager nodeManager = new InMemoryNodeManager(); nodeManager.addNode(CONNECTOR_ID, new InternalNode("other1", URI.create("http://127.0.0.1:11"), NodeVersio...
@Override public void unregister(String pluginId) { mainLock.runWithWriteLock( () -> Optional.ofNullable(pluginId) .map(registeredPlugins::remove) .ifPresent(plugin -> { disabledPlugins.remove(pluginId); ...
@Test public void testUnregister() { manager.register(new TestTaskAwarePlugin()); manager.unregister(TestTaskAwarePlugin.class.getSimpleName()); Assert.assertFalse(manager.isRegistered(TestTaskAwarePlugin.class.getSimpleName())); manager.register(new TestRejectedAwarePlugin()); ...
@Override public void checkAuthorization( final KsqlSecurityContext securityContext, final MetaStore metaStore, final Statement statement ) { if (statement instanceof Query) { validateQuery(securityContext, metaStore, (Query)statement); } else if (statement instanceof InsertInto) { ...
@Test public void shouldThrowWhenCreateAsSelectOnNewTopicWithoutKeySchemaWritePermissions() { // Given: givenSubjectAccessDenied("topic-key", AclOperation.WRITE); final Statement statement = givenStatement(String.format( "CREATE STREAM newStream WITH (kafka_topic='topic', key_format='AVRO') " ...
@Override public int get(int key) { if (key == NO_KEY) { return val0; } final int V = ihc.get(key); assert !isPrime(V); // Never return a Prime return V; }
@Test public void testSingleThread() { final IntHashCounter intMap = new AtomicIntHashCounter(128 * 1024); final AtomicIntegerArray intArray = new AtomicIntegerArray(128 * 1024); final ConcurrentMap<Integer, AtomicInteger> integerMap = new ConcurrentHashMap<>(128 * 1024); mode1(intMa...
public static String extractPartsFromURIs(List<String> uris) { // 1st pass on collection: find a common prefix. String commonURIPath = extractCommonPrefix(uris); // 2nd pass on collection: find a common suffix. String commonURIEnd = extractCommonSuffix(uris); // 3rd pass on collection: g...
@Test void testExtractPartsFromURIs() { // Prepare a bunch of uri paths. List<String> resourcePaths = new ArrayList<>(); resourcePaths.add("/v2/pet/findByDate/2017"); resourcePaths.add("/v2/pet/findByDate/2016/12"); resourcePaths.add("/v2/pet/findByDate/2016/12/20"); // Dispatch ...
public static void hasText(String text, String message) { if (!StringUtil.hasText(text)) { throw new IllegalArgumentException(message); } }
@Test(expected = IllegalArgumentException.class) public void assertHasTextAndMessageIsNull() { Assert.hasText(" "); }
@Override public PostgresConnectorEmbeddedDebeziumConfiguration getConfiguration() { return configuration; }
@Test void testIfConnectorEndpointCreatedWithConfig() throws Exception { final Map<String, Object> params = new HashMap<>(); params.put("offsetStorageFileName", "/offset_test_file"); params.put("databaseHostname", "localhost"); params.put("databaseUser", "dbz"); params.put("d...
public Translation get(String locale) { locale = locale.replace("-", "_"); Translation tr = translations.get(locale); if (locale.contains("_") && tr == null) tr = translations.get(locale.substring(0, 2)); return tr; }
@Test public void testToRoundaboutString() { Translation ptMap = SINGLETON.get("pt"); assertTrue(ptMap.tr("roundabout_exit_onto", "1", "somestreet").contains("somestreet")); }
public static boolean isBlankChar(char c) { return isBlankChar((int) c); }
@Test public void isBlankCharTest(){ final char a = '\u00A0'; assertTrue(CharUtil.isBlankChar(a)); final char a2 = '\u0020'; assertTrue(CharUtil.isBlankChar(a2)); final char a3 = '\u3000'; assertTrue(CharUtil.isBlankChar(a3)); final char a4 = '\u0000'; assertTrue(CharUtil.isBlankChar(a4)); final ...
@Override public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); }
@Test public void validateSmsCode_success() { // 准备参数 SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { o.setMobile("15601691300"); o.setScene(randomEle(SmsSceneEnum.values()).getScene()); }); // mock 数据 SqlConstants.init(Db...
@NonNull @Override public String getId() { return ID; }
@Test public void getOrganizationsWithInvalidCredentialId() throws IOException, UnirestException { Map r = new RequestBuilder(baseUrl) .crumb(crumb) .status(400) .jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), authenticatedUser.getId())) .post("/or...
@Override public Num calculate(BarSeries series, Position position) { return criterion.calculate(series, position).dividedBy(enterAndHoldCriterion.calculate(series, position)); }
@Test public void calculateOnlyWithLossPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series), Trade.buyAt(2, series), Trade.sellAt(5, series));...
public static int[] sort(int[] array) { int[] order = new int[array.length]; for (int i = 0; i < order.length; i++) { order[i] = i; } sort(array, order); return order; }
@Test public void testSortInt() { System.out.println("sort int"); int[] data1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] order1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; assertArrayEquals(order1, QuickSort.sort(data1)); int[] data2 = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; int[] order2 ...
public Object evaluate( final GenericRow row, final Object defaultValue, final ProcessingLogger logger, final Supplier<String> errorMsg ) { try { return expressionEvaluator.evaluate(new Object[]{ spec.resolveArguments(row), defaultValue, logger, ...
@Test public void shouldLogIfEvalThrows() throws Exception { // Given: spec.addParameter( ColumnName.of("foo1"), Integer.class, 0 ); compiledExpression = new CompiledExpression( expressionEvaluator, spec.build(), EXPRESSION_TYPE, expression ...
static void unTarUsingJava(File inFile, File untarDir, boolean gzipped) throws IOException { InputStream inputStream = null; TarArchiveInputStream tis = null; try { if (gzipped) { inputStream = new GZIPInputStream(Files.newInputStream(inFile.toPath())); } else { ...
@Test(timeout = 8000) public void testCreateSymbolicLinkUsingJava() throws IOException { final File simpleTar = new File(del, FILE); OutputStream os = new FileOutputStream(simpleTar); try (TarArchiveOutputStream tos = new TarArchiveOutputStream(os)) { // Files to tar final String tmpDir = "tmp...
public List<Set<String>> getActualTableNameGroups(final String actualDataSourceName, final Set<String> logicTableNames) { return logicTableNames.stream().map(each -> getActualTableNames(actualDataSourceName, each)).filter(each -> !each.isEmpty()).collect(Collectors.toList()); }
@Test void assertGetActualTableNameGroups() { List<Set<String>> actual = multiRouteContext.getActualTableNameGroups(DATASOURCE_NAME_1, new HashSet<>(Collections.singleton(LOGIC_TABLE))); assertThat(actual.size(), is(1)); assertTrue(actual.get(0).contains(ACTUAL_TABLE)); }
@UdafFactory(description = "Compute sample standard deviation of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint, M2 double>") public static TableUdaf<Integer, Struct, Double> stdDevInt() { return getStdDevImplementation( 0, STRUCT_INT, (agg, newValue)...
@Test public void shouldAverageZeroes() { final TableUdaf<Integer, Struct, Double> udaf = stdDevInt(); Struct agg = udaf.initialize(); final int[] values = new int[] {0, 0, 0}; for (final int thisValue : values) { agg = udaf.aggregate(thisValue, agg); } final double standardDev = udaf.ma...
@Override public void exists(final String path, final boolean watch, final AsyncCallback.StatCallback cb, final Object ctx) { if (!SymlinkUtil.containsSymlink(path)) { _zk.exists(path, watch, cb, ctx); } else { SymlinkStatCallback compositeCallback = new SymlinkStatCallback(path, _de...
@Test public void testInvalidSymlinkWithExists() throws ExecutionException, InterruptedException { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.StatCallback callback = new AsyncCallback.StatCallback() { @Override ...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertDatetime() { Column column = PhysicalColumn.builder() .name("test") .dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE) .build(); BasicTypeDefine typeDefine = SqlServerTypeConverter.INST...
@Override public AwsProxyResponse handle(Throwable ex) { log.error("Called exception handler for:", ex); // adding a print stack trace in case we have no appender or we are running inside SAM local, where need the // output to go to the stderr. ex.printStackTrace(); if (ex i...
@Test void streamHandle_InvalidRequestEventException_500State() throws IOException { ByteArrayOutputStream respStream = new ByteArrayOutputStream(); exceptionHandler.handle(new InvalidRequestEventException(INVALID_REQUEST_MESSAGE, null), respStream); assertNotNull(respStream); ...
public Optional<MaskTable> findMaskTable(final String tableName) { return Optional.ofNullable(tables.get(tableName)); }
@Test void assertFindMaskTableWhenTableNameDoesNotExist() { assertFalse(maskRule.findMaskTable("non_existent_table").isPresent()); }
@Override public Collection<String> getXADriverClassNames() { return Arrays.asList("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "com.mysql.cj.jdbc.MysqlXADataSource"); }
@Test void assertGetXADriverClassName() { assertThat(new MySQLXADataSourceDefinition().getXADriverClassNames(), is(Arrays.asList("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "com.mysql.cj.jdbc.MysqlXADataSource"))); }
@Override public String toString() { if (mUriString != null) { return mUriString; } StringBuilder sb = new StringBuilder(); if (mUri.getScheme() != null) { sb.append(mUri.getScheme()); sb.append("://"); } if (hasAuthority()) { if (mUri.getScheme() == null) { sb....
@Test public void normalizeTests() { assertEquals("/", new AlluxioURI("//").toString()); assertEquals("/foo", new AlluxioURI("/foo/").toString()); assertEquals("/foo", new AlluxioURI("/foo/").toString()); assertEquals("foo", new AlluxioURI("foo/").toString()); assertEquals("foo", new AlluxioURI("f...
@Override public long getMin() { if (values.length == 0) { return 0; } return values[0]; }
@Test public void calculatesTheMinimumValue() { assertThat(snapshot.getMin()) .isEqualTo(1); }
public List<PrometheusQueryResult> queryMetric(String queryString, long startTimeMs, long endTimeMs) throws IOException { URI queryUri = URI.create(_prometheusEndpoint.toURI() + QUERY_RANGE_API_PATH); H...
@Test(expected = IOException.class) public void testEmptyStatus() throws Exception { this.serverBootstrap.registerHandler("/api/v1/query_range", new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) { ...
public Duration elapsed() { return Duration.between(startTime, isRunning() ? Instant.now() : stopTime); }
@Test public void compareTo() { Duration hour = Duration.ofHours(1); assertTrue(stopwatch.elapsed().compareTo(hour) < 0); assertTrue(hour.compareTo(stopwatch.elapsed()) > 0); }
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariableStatement sqlStatement, final ContextManager contextManager) { ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData(); String variableName = sqlStatement.getName(); if (isConfigur...
@Test void assertShowPropsVariable() { when(contextManager.getMetaDataContexts().getMetaData().getProps()).thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property("sql-show", Boolean.TRUE.toString())))); ShowDistVariableExecutor executor = new ShowDistVariableExecutor(); ...
@Override public void write(String propertyKey, @Nullable String value) { checkPropertyKey(propertyKey); try (DbSession dbSession = dbClient.openSession(false)) { if (value == null || value.isEmpty()) { dbClient.internalPropertiesDao().saveAsEmpty(dbSession, propertyKey); } else { ...
@Test public void write_calls_dao_saveAsEmpty_when_value_is_empty() { underTest.write(SOME_KEY, EMPTY_STRING); verify(internalPropertiesDao).saveAsEmpty(dbSession, SOME_KEY); verify(dbSession).commit(); }
@Override public ObjectNode encode(TrafficTreatment treatment, CodecContext context) { checkNotNull(treatment, "Traffic treatment cannot be null"); final ObjectNode result = context.mapper().createObjectNode(); final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS); final...
@Test public void testTrafficTreatmentEncode() { Instruction output = Instructions.createOutput(PortNumber.portNumber(0)); Instruction modL2Src = Instructions.modL2Src(MacAddress.valueOf("11:22:33:44:55:66")); Instruction modL2Dst = Instructions.modL2Dst(MacAddress.valueOf("44:55:66:77:88:9...
@Override public void onError(QueryException error) { assert error != null; done.compareAndSet(null, error); }
@Test public void when_doneWithErrorWhileWaiting_then_throw_sync() throws Exception { initProducer(false); Future<?> future = spawn(() -> { assertThatThrownBy(() -> iterator.hasNext(1, DAYS)) .hasMessageContaining("mock error"); }); sleepMillis(50); //...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void pathExpression() { String inputExpression = "[ 10, 15 ].size"; BaseNode pathBase = parse( inputExpression ); assertThat( pathBase).isInstanceOf(PathExpressionNode.class); assertThat( pathBase.getText()).isEqualTo(inputExpression); PathExpressionNode pathExpr = (P...
@Override public Map<String, String> parameters() { return parameters == null ? null : Collections.unmodifiableMap(parameters); }
@Test public void testParameters() { Map<String, String> expectedParameters = new HashMap<>(); expectedParameters.put("foo", "val"); expectedParameters.put("bar", "baz"); Schema schema = SchemaBuilder.string().parameter("foo", "val").parameter("bar", "baz").build(); assertTy...
@Override public void refreshLogRetentionSettings() throws IOException { UserGroupInformation user = checkAcls("refreshLogRetentionSettings"); try { loginUGI.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws IOException { aggLogDelService.refreshL...
@Test public void testRefreshLogRetentionSettings() throws Exception { String[] args = new String[1]; args[0] = "-refreshLogRetentionSettings"; hsAdminClient.run(args); verify(alds).refreshLogRetentionSettings(); }
public void ignoreSynchronous() { pending.get().clear(); }
@Test public void ignoreSynchronous() { var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run); dispatcher.pending.get().add(CompletableFuture.completedFuture(null)); dispatcher.ignoreSynchronous(); assertThat(dispatcher.pending.get()).isEmpty(); }
public CompletionService<MultiHttpRequestResponse> executeGet(List<String> urls, @Nullable Map<String, String> requestHeaders, int timeoutMs) { List<Pair<String, String>> urlsAndRequestBodies = new ArrayList<>(); urls.forEach(url -> urlsAndRequestBodies.add(Pair.of(url, ""))); return execute(urlsAndRe...
@Test public void testMultiGet() { List<String> urls = Arrays.asList("http://localhost:" + String.valueOf(_portStart) + URI_PATH, "http://localhost:" + String.valueOf(_portStart + 1) + URI_PATH, "http://localhost:" + String.valueOf(_portStart + 2) + URI_PATH, // 2nd request to the same ser...
@Override public void onIssue(Component component, DefaultIssue issue) { if (issue.authorLogin() != null) { return; } loadScmChangesets(component); Optional<String> scmAuthor = guessScmAuthor(issue, component); if (scmAuthor.isPresent()) { if (scmAuthor.get().length() <= IssueDto.AUTH...
@Test void assign_to_default_assignee_if_no_scm_on_issue_locations() { addScmUser("john", buildUserId("u123", "John C")); Changeset changeset = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build(); scmInfoRepository.setScmInfo(FILE_...