private static Set<String> shuffleWithNonExistentUuids(String... uuids) { return Stream.concat( IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> randomAlphabetic(9)), Arrays.stream(uuids)) .collect(toSet()); }
@Test public void add_counts_issue_per_component_on_leak_globally_and_per_assignee() { List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).collect(Collectors.toList()); String assignee = randomAlphanumeric(10); componentUuids.stream() .map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(true)) .forEach(underTest::add); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT); DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.COMPONENT); Stream.of(globalDistribution, assigneeDistribution) .forEach(distribution -> componentUuids.forEach(componentUuid -> assertStats(distribution, componentUuid, 1, 0, 1))); }
@Test public void checkCluster_returns_causes_of_all_ClusterHealthChecks_whichever_their_status() { when(webServer.isStandalone()).thenReturn(false); List<String[]> causesGroups = IntStream.range(0, 1 + random.nextInt(20)) .mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new)) .collect(Collectors.toList()); ClusterHealthCheck[] clusterHealthChecks = causesGroups.stream() .map(HardcodedHealthClusterCheck::new) .map(ClusterHealthCheck.class::cast) .toArray(ClusterHealthCheck[]::new); String[] expectedCauses = causesGroups.stream().flatMap(Arrays::stream).collect(Collectors.toSet()).stream().toArray(String[]::new); HealthCheckerImpl underTest = new HealthCheckerImpl(webServer, new NodeHealthCheck[0], clusterHealthChecks, sharedHealthState); assertThat(underTest.checkCluster().getHealth().getCauses()).containsOnly(expectedCauses); }
@Test public void keys_whose_length_is_lower_than_40_should_not_be_updated() throws SQLException { // Create 10 permission templates with keys' length lower or equals than 40 List<String> correctKeys = IntStream.range(0, 10) .mapToObj(i -> insertTemplate(randomAlphanumeric(RANDOM.nextInt(41)))) .collect(toList()); underTest.execute(); assertThat(UUID_FACTORY.getRecordedUuids()).hasSize(0); List<String> kees = dbTester.select("select kee from permission_templates").stream() .map(r -> (String) r.get("KEE")).collect(toList()); assertThat(kees).containsExactlyInAnyOrder(correctKeys.toArray(new String[] {})); }
@Test public void execute_populates_line_count_of_any_type() throws SQLException { String projectUuid = randomAlphanumeric(4); String fileUuid = randomAlphanumeric(5); when(ceTask.getComponent()).thenReturn(newComponent(projectUuid)); int lineCount = 1 + random.nextInt(15); insertUnpopulatedFileSource(projectUuid, fileUuid, lineCount); assertThat(getLineCountByFileUuid(fileUuid)).isEqualTo(LINE_COUNT_NOT_POPULATED); underTest.execute(); assertThat(getLineCountByFileUuid(fileUuid)).isEqualTo(lineCount); }
@Test public void add_does_not_count_tags_if_empty_neither_globally_nor_per_assignee() { String assignee = randomAlphanumeric(10); underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(Collections.emptyList()).setAssigneeUuid(assignee).setNew(new Random().nextBoolean())); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG); DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.TAG); Stream.of(globalDistribution, assigneeDistribution) .forEach(distribution -> { assertThat(distribution.getTotal()).isEqualTo(0); assertThat(distribution.getForLabel(null).isPresent()).isFalse(); }); }
@Test public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_many_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) .map(CeQueueDto::getUuid) .toArray(String[]::new); Optional<CeTask> task = underTest.submit(taskSubmit, UNIQUE_QUEUE_PER_MAIN_COMPONENT); assertThat(task).isEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(uuids); }
@Test public void checkNode_returns_causes_of_all_NodeHealthCheck_whichever_their_status() { NodeHealthCheck[] nodeHealthChecks = IntStream.range(0, 1 + random.nextInt(20)) .mapToObj(s -> new HardcodedHealthNodeCheck(IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new))) .map(NodeHealthCheck.class::cast) .toArray(NodeHealthCheck[]::new); String[] expected = Arrays.stream(nodeHealthChecks).map(NodeHealthCheck::check).flatMap(s -> s.getCauses().stream()).toArray(String[]::new); HealthCheckerImpl underTest = new HealthCheckerImpl(webServer, nodeHealthChecks); assertThat(underTest.checkNode().getCauses()).containsOnly(expected); }
@Test public void request_returns_status_and_causes_from_HealthChecker_checkNode_method() { authenticateWithPasscode(); Health.Status randomStatus = Health.Status.values()[new Random().nextInt(Health.Status.values().length)]; Health.Builder builder = newHealthCheckBuilder() .setStatus(randomStatus); IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.randomAlphanumeric(3)).forEach(builder::addCause); Health health = builder.build(); when(healthChecker.checkNode()).thenReturn(health); TestRequest request = underTest.newRequest(); System.HealthResponse healthResponse = request.executeProtobuf(System.HealthResponse.class); assertThat(healthResponse.getHealth().name()).isEqualTo(randomStatus.name()); assertThat(health.getCauses()).isEqualTo(health.getCauses()); }
@Test public void setErrorMessage_truncates_to_1000_after_removing_char_zero() { String before = randomAlphanumeric(50); String after = randomAlphanumeric(950); String truncated = randomAlphanumeric(1 + new Random().nextInt(50)); underTest.setErrorMessage(before + "\u0000" + after + truncated); assertThat(underTest.getErrorMessage()).isEqualTo(before + after); }
private void insertMeasureFor(ComponentDto... components) { Arrays.stream(components).forEach(componentDto -> db.getDbClient().measureDao().insert(dbSession, new MeasureDto() .setMetricId(new Random().nextInt()) .setComponentUuid(componentDto.uuid()) .setAnalysisUuid(randomAlphabetic(3)))); dbSession.commit(); }
private <T> void verifySupportHeadAndOrTrailingWhitespaces(T value, BiFunction<Configuration, String, Optional<T>> t) { String randomKey = RandomStringUtils.randomAlphabetic(3); String randomNumberOfWhitespaces = StringUtils.repeat(" ", 1 + new Random().nextInt(10)); assertThat(t.apply(underTest.put(randomKey, randomNumberOfWhitespaces + String.valueOf(value)), randomKey)).isEqualTo(Optional.of(value)); assertThat(t.apply(underTest.put(randomKey, String.valueOf(value) + randomNumberOfWhitespaces), randomKey)).isEqualTo(Optional.of(value)); assertThat(t.apply(underTest.put(randomKey, randomNumberOfWhitespaces + String.valueOf(value) + randomNumberOfWhitespaces), randomKey)).isEqualTo(Optional.of(value)); }
private Health randomHealth() { Health.Builder healthBuilder = newHealthCheckBuilder(); healthBuilder.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]); IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).forEach(healthBuilder::addCause); return healthBuilder.build(); }
@Test public void clearMine_clears_entry_into_map_sq_health_state_under_current_client_uuid() { Map<String, TimestampedNodeHealth> map = mock(Map.class); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); String uuid = randomAlphanumeric(5); when(hazelcastMember.getUuid()).thenReturn(uuid); underTest.clearMine(); verify(map).remove(uuid); verifyNoMoreInteractions(map); assertThat(logging.getLogs()).isEmpty(); }
@Test public void findProjectKey_returns_projectKey_when_entry_exists() { String projectKey = randomAlphabetic(10); ComponentDto project = createProject(projectKey); when(uuidFactory.create()).thenReturn("uuid1"); underTest.insertOrUpdate(dbSession, GITHUB, A_REPO, project.projectUuid(), A_GITHUB_SLUG, A_URL); assertThat(underTest.findProjectKey(dbSession, GITHUB, A_REPO)).contains(projectKey); }
@Test public void set_accepts_empty_value_and_trims_it() { MapSettings underTest = new MapSettings(); Random random = new Random(); String key = randomAlphanumeric(3); underTest.set(key, blank(random)); assertThat(underTest.getString(key)).isEmpty(); }
private void testStringDictionary(ImmutableDictionaryReader stringDictionary) { for (int i = 0; i < NUM_VALUES; i++) { assertEquals(stringDictionary.get(i), _stringValues[i]); assertEquals(stringDictionary.getStringValue(i), _stringValues[i]); assertEquals(stringDictionary.indexOf(_stringValues[i]), i); // Test String longer than MAX_STRING_LENGTH String randomString = RandomStringUtils.random(RANDOM.nextInt(2 * MAX_STRING_LENGTH)).replace('\0', ' '); assertEquals(stringDictionary.insertionIndexOf(randomString), Arrays.binarySearch(_stringValues, randomString)); } }
@Test public void call_sets_and_restores_thread_name_with_information_of_worker_when_there_is_no_task_to_process() throws Exception { String threadName = randomAlphabetic(3); when(queue.peek(anyString())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) .isEqualTo("Worker " + randomOrdinal + " (UUID=" + workerUuid + ") on " + threadName); return Optional.empty(); }); Thread newThread = createThreadNameVerifyingThread(threadName); newThread.start(); newThread.join(); }
@SafeVarargs public final QualityGateConditionDto addCondition(QualityGateDto qualityGate, MetricDto metric, Consumer<QualityGateConditionDto>... dtoPopulators) { QualityGateConditionDto condition = new QualityGateConditionDto().setQualityGateId(qualityGate.getId()) .setMetricId(metric.getId()) .setOperator("GT") .setErrorThreshold(randomNumeric(10)); Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(condition)); dbClient.gateConditionDao().insert(condition, dbSession); db.commit(); return condition; } }