3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.telemetry;
22 import com.tngtech.java.junit.dataprovider.DataProvider;
23 import com.tngtech.java.junit.dataprovider.DataProviderRunner;
24 import com.tngtech.java.junit.dataprovider.UseDataProvider;
25 import java.sql.DatabaseMetaData;
26 import java.sql.SQLException;
27 import java.time.LocalDateTime;
28 import java.time.ZoneId;
29 import java.time.ZonedDateTime;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Optional;
34 import java.util.function.Consumer;
35 import java.util.function.Function;
36 import java.util.stream.Collectors;
37 import java.util.stream.IntStream;
38 import org.junit.Before;
39 import org.junit.Rule;
40 import org.junit.Test;
41 import org.junit.runner.RunWith;
42 import org.sonar.api.config.Configuration;
43 import org.sonar.api.impl.utils.TestSystem2;
44 import org.sonar.core.platform.PlatformEditionProvider;
45 import org.sonar.core.platform.PluginInfo;
46 import org.sonar.core.platform.PluginRepository;
47 import org.sonar.db.DbSession;
48 import org.sonar.db.DbTester;
49 import org.sonar.db.alm.setting.AlmSettingDto;
50 import org.sonar.db.component.AnalysisPropertyDto;
51 import org.sonar.db.component.ComponentDto;
52 import org.sonar.db.component.SnapshotDto;
53 import org.sonar.db.metric.MetricDto;
54 import org.sonar.db.newcodeperiod.NewCodePeriodType;
55 import org.sonar.db.qualitygate.QualityGateDto;
56 import org.sonar.db.user.UserDbTester;
57 import org.sonar.db.user.UserDto;
58 import org.sonar.db.user.UserTelemetryDto;
59 import org.sonar.server.management.ManagedInstanceService;
60 import org.sonar.server.platform.DockerSupport;
61 import org.sonar.server.property.InternalProperties;
62 import org.sonar.server.property.MapInternalProperties;
63 import org.sonar.server.qualitygate.QualityGateCaycChecker;
64 import org.sonar.server.qualitygate.QualityGateFinder;
65 import org.sonar.server.telemetry.TelemetryData.Branch;
66 import org.sonar.server.telemetry.TelemetryData.NewCodeDefinition;
67 import org.sonar.server.telemetry.TelemetryData.ProjectStatistics;
68 import org.sonar.updatecenter.common.Version;
70 import static java.util.Arrays.asList;
71 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
72 import static org.assertj.core.api.Assertions.assertThat;
73 import static org.assertj.core.api.Assertions.entry;
74 import static org.assertj.core.groups.Tuple.tuple;
75 import static org.mockito.ArgumentMatchers.any;
76 import static org.mockito.Mockito.mock;
77 import static org.mockito.Mockito.spy;
78 import static org.mockito.Mockito.when;
79 import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
80 import static org.sonar.api.measures.CoreMetrics.BUGS_KEY;
81 import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
82 import static org.sonar.api.measures.CoreMetrics.DEVELOPMENT_COST_KEY;
83 import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
84 import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
85 import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY;
86 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
87 import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
88 import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY;
89 import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI;
90 import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDSCM;
91 import static org.sonar.core.platform.EditionProvider.Edition.COMMUNITY;
92 import static org.sonar.core.platform.EditionProvider.Edition.DEVELOPER;
93 import static org.sonar.core.platform.EditionProvider.Edition.ENTERPRISE;
94 import static org.sonar.db.component.BranchType.BRANCH;
95 import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_CPP_KEY;
96 import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_C_KEY;
97 import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT;
99 @RunWith(DataProviderRunner.class)
100 public class TelemetryDataLoaderImplTest {
101 private final static Long NOW = 100_000_000L;
102 private final TestSystem2 system2 = new TestSystem2().setNow(NOW);
105 public DbTester db = DbTester.create(system2);
107 private final FakeServer server = new FakeServer();
108 private final PluginRepository pluginRepository = mock(PluginRepository.class);
109 private final Configuration configuration = mock(Configuration.class);
110 private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
111 private final DockerSupport dockerSupport = mock(DockerSupport.class);
112 private final QualityGateCaycChecker qualityGateCaycChecker = mock(QualityGateCaycChecker.class);
113 private final QualityGateFinder qualityGateFinder = new QualityGateFinder(db.getDbClient());
114 private final InternalProperties internalProperties = spy(new MapInternalProperties());
115 private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
117 private final TelemetryDataLoader communityUnderTest = new TelemetryDataLoaderImpl(server, db.getDbClient(), pluginRepository, editionProvider,
118 internalProperties, configuration, dockerSupport, qualityGateCaycChecker, qualityGateFinder, managedInstanceService);
119 private final TelemetryDataLoader commercialUnderTest = new TelemetryDataLoaderImpl(server, db.getDbClient(), pluginRepository, editionProvider,
120 internalProperties, configuration, dockerSupport, qualityGateCaycChecker, qualityGateFinder, managedInstanceService);
122 private QualityGateDto builtInDefaultQualityGate;
123 private MetricDto bugsDto;
124 private MetricDto vulnerabilitiesDto;
125 private MetricDto securityHotspotsDto;
126 private MetricDto technicalDebtDto;
127 private MetricDto developmentCostDto;
130 public void setUpBuiltInQualityGate() {
131 String builtInQgName = "Sonar Way";
132 builtInDefaultQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName(builtInQgName).setBuiltIn(true));
133 when(qualityGateCaycChecker.checkCaycCompliant(any(), any())).thenReturn(NON_COMPLIANT);
134 db.qualityGates().setDefaultQualityGate(builtInDefaultQualityGate);
136 bugsDto = db.measures().insertMetric(m -> m.setKey(BUGS_KEY));
137 vulnerabilitiesDto = db.measures().insertMetric(m -> m.setKey(VULNERABILITIES_KEY));
138 securityHotspotsDto = db.measures().insertMetric(m -> m.setKey(SECURITY_HOTSPOTS_KEY));
139 technicalDebtDto = db.measures().insertMetric(m -> m.setKey(TECHNICAL_DEBT_KEY));
140 developmentCostDto = db.measures().insertMetric(m -> m.setKey(DEVELOPMENT_COST_KEY));
144 public void send_telemetry_data() {
145 String serverId = "AU-TpxcB-iU5OvuD2FL7";
146 String version = "7.5.4";
147 Long analysisDate = 1L;
148 Long lastConnectionDate = 5L;
150 server.setId(serverId);
151 server.setVersion(version);
152 List<PluginInfo> plugins = asList(newPlugin("java", "4.12.0.11033"), newPlugin("scmgit", "1.2"), new PluginInfo("other"));
153 when(pluginRepository.getPluginInfos()).thenReturn(plugins);
154 when(editionProvider.get()).thenReturn(Optional.of(DEVELOPER));
156 List<UserDto> activeUsers = composeActiveUsers(3);
158 // update last connection
159 activeUsers.forEach(u -> db.users().updateLastConnectionDate(u, 5L));
161 UserDto inactiveUser = db.users().insertUser(u -> u.setActive(false).setExternalIdentityProvider("provider0"));
163 MetricDto lines = db.measures().insertMetric(m -> m.setKey(LINES_KEY));
164 MetricDto ncloc = db.measures().insertMetric(m -> m.setKey(NCLOC_KEY));
165 MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
166 MetricDto nclocDistrib = db.measures().insertMetric(m -> m.setKey(NCLOC_LANGUAGE_DISTRIBUTION_KEY));
168 ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
169 db.measures().insertLiveMeasure(project1, lines, m -> m.setValue(110d));
170 db.measures().insertLiveMeasure(project1, ncloc, m -> m.setValue(110d));
171 db.measures().insertLiveMeasure(project1, coverage, m -> m.setValue(80d));
172 db.measures().insertLiveMeasure(project1, nclocDistrib, m -> m.setValue(null).setData("java=70;js=30;kotlin=10"));
173 db.measures().insertLiveMeasure(project1, bugsDto, m -> m.setValue(1d));
174 db.measures().insertLiveMeasure(project1, vulnerabilitiesDto, m -> m.setValue(1d).setData((String) null));
175 db.measures().insertLiveMeasure(project1, securityHotspotsDto, m -> m.setValue(1d).setData((String) null));
176 db.measures().insertLiveMeasure(project1, developmentCostDto, m -> m.setData("50").setValue(null));
177 db.measures().insertLiveMeasure(project1, technicalDebtDto, m -> m.setValue(5d).setData((String) null));
179 ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
180 db.measures().insertLiveMeasure(project2, lines, m -> m.setValue(200d));
181 db.measures().insertLiveMeasure(project2, ncloc, m -> m.setValue(200d));
182 db.measures().insertLiveMeasure(project2, coverage, m -> m.setValue(80d));
183 db.measures().insertLiveMeasure(project2, nclocDistrib, m -> m.setValue(null).setData("java=180;js=20"));
185 SnapshotDto project1Analysis = db.components().insertSnapshot(project1, t -> t.setLast(true).setBuildDate(analysisDate));
186 SnapshotDto project2Analysis = db.components().insertSnapshot(project2, t -> t.setLast(true).setBuildDate(analysisDate));
187 db.measures().insertMeasure(project1, project1Analysis, nclocDistrib, m -> m.setData("java=70;js=30;kotlin=10"));
188 db.measures().insertMeasure(project2, project2Analysis, nclocDistrib, m -> m.setData("java=180;js=20"));
190 insertAnalysisProperty(project1Analysis, "prop-uuid-1", SONAR_ANALYSIS_DETECTEDCI, "ci-1");
191 insertAnalysisProperty(project2Analysis, "prop-uuid-2", SONAR_ANALYSIS_DETECTEDCI, "ci-2");
192 insertAnalysisProperty(project1Analysis, "prop-uuid-3", SONAR_ANALYSIS_DETECTEDSCM, "scm-1");
193 insertAnalysisProperty(project2Analysis, "prop-uuid-4", SONAR_ANALYSIS_DETECTEDSCM, "scm-2");
196 db.almSettings().insertAzureAlmSetting();
197 db.almSettings().insertGitHubAlmSetting();
198 AlmSettingDto almSettingDto = db.almSettings().insertAzureAlmSetting(a -> a.setUrl("https://dev.azure.com"));
199 AlmSettingDto gitHubAlmSetting = db.almSettings().insertGitHubAlmSetting(a -> a.setUrl("https://api.github.com"));
200 db.almSettings().insertAzureProjectAlmSetting(almSettingDto, db.components().getProjectDtoByMainBranch(project1));
201 db.almSettings().insertGitlabProjectAlmSetting(gitHubAlmSetting, db.components().getProjectDtoByMainBranch(project2));
204 QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate(qg -> qg.setName("QG1").setBuiltIn(true));
205 QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(qg -> qg.setName("QG2"));
207 // link one project to a non-default QG
208 db.qualityGates().associateProjectToQualityGate(db.components().getProjectDtoByMainBranch(project1), qualityGate1);
210 var branch1 = db.components().insertProjectBranch(project1, branchDto -> branchDto.setKey("reference"));
211 var branch2 = db.components().insertProjectBranch(project1, branchDto -> branchDto.setKey("custom"));
213 var ncd1 = db.newCodePeriods().insert(project1.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, "30");
214 var ncd2 = db.newCodePeriods().insert(project1.uuid(), branch2.branchUuid(), NewCodePeriodType.REFERENCE_BRANCH, "reference");
216 var instanceNcdId = NewCodeDefinition.getInstanceDefault().hashCode();
217 var projectNcdId = new NewCodeDefinition(NewCodePeriodType.NUMBER_OF_DAYS.name(), "30", "project").hashCode();
218 var branchNcdId = new NewCodeDefinition(NewCodePeriodType.REFERENCE_BRANCH.name(), branch1.uuid(), "branch").hashCode();
220 TelemetryData data = communityUnderTest.load();
221 assertThat(data.getServerId()).isEqualTo(serverId);
222 assertThat(data.getVersion()).isEqualTo(version);
223 assertThat(data.getEdition()).contains(DEVELOPER);
224 assertThat(data.getDefaultQualityGate()).isEqualTo(builtInDefaultQualityGate.getUuid());
225 assertThat(data.getNcdId()).isEqualTo(NewCodeDefinition.getInstanceDefault().hashCode());
226 assertThat(data.getMessageSequenceNumber()).isOne();
227 assertDatabaseMetadata(data.getDatabase());
228 assertThat(data.getPlugins()).containsOnly(
229 entry("java", "4.12.0.11033"), entry("scmgit", "1.2"), entry("other", "undefined"));
230 assertThat(data.isInDocker()).isFalse();
232 assertThat(data.getUserTelemetries())
233 .extracting(UserTelemetryDto::getUuid, UserTelemetryDto::getLastConnectionDate, UserTelemetryDto::getLastSonarlintConnectionDate, UserTelemetryDto::isActive)
234 .containsExactlyInAnyOrder(
235 tuple(activeUsers.get(0).getUuid(), lastConnectionDate, activeUsers.get(0).getLastSonarlintConnectionDate(), true),
236 tuple(activeUsers.get(1).getUuid(), lastConnectionDate, activeUsers.get(1).getLastSonarlintConnectionDate(), true),
237 tuple(activeUsers.get(2).getUuid(), lastConnectionDate, activeUsers.get(2).getLastSonarlintConnectionDate(), true),
238 tuple(inactiveUser.getUuid(), null, inactiveUser.getLastSonarlintConnectionDate(), false));
239 assertThat(data.getProjects())
240 .extracting(TelemetryData.Project::projectUuid, TelemetryData.Project::language, TelemetryData.Project::loc, TelemetryData.Project::lastAnalysis)
241 .containsExactlyInAnyOrder(
242 tuple(project1.uuid(), "java", 70L, analysisDate),
243 tuple(project1.uuid(), "js", 30L, analysisDate),
244 tuple(project1.uuid(), "kotlin", 10L, analysisDate),
245 tuple(project2.uuid(), "java", 180L, analysisDate),
246 tuple(project2.uuid(), "js", 20L, analysisDate));
247 assertThat(data.getProjectStatistics())
248 .extracting(ProjectStatistics::getBranchCount, ProjectStatistics::getPullRequestCount, ProjectStatistics::getQualityGate,
249 ProjectStatistics::getScm, ProjectStatistics::getCi, ProjectStatistics::getDevopsPlatform,
250 ProjectStatistics::getBugs, ProjectStatistics::getVulnerabilities, ProjectStatistics::getSecurityHotspots,
251 ProjectStatistics::getDevelopmentCost, ProjectStatistics::getTechnicalDebt, ProjectStatistics::getNcdId)
252 .containsExactlyInAnyOrder(
253 tuple(3L, 0L, qualityGate1.getUuid(), "scm-1", "ci-1", "azure_devops_cloud", Optional.of(1L), Optional.of(1L), Optional.of(1L), Optional.of(50L), Optional.of(5L),
255 tuple(1L, 0L, builtInDefaultQualityGate.getUuid(), "scm-2", "ci-2", "github_cloud", Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(),
256 Optional.empty(), instanceNcdId));
258 assertThat(data.getBranches())
259 .extracting(Branch::branchUuid, Branch::ncdId)
260 .containsExactlyInAnyOrder(
261 tuple(branch1.uuid(), projectNcdId),
262 tuple(branch2.uuid(), branchNcdId),
263 tuple(project1.uuid(), projectNcdId),
264 tuple(project2.uuid(), instanceNcdId));
266 assertThat(data.getNewCodeDefinitions())
267 .extracting(NewCodeDefinition::scope, NewCodeDefinition::type, NewCodeDefinition::value)
268 .containsExactlyInAnyOrder(
269 tuple("instance", NewCodePeriodType.PREVIOUS_VERSION.name(), ""),
270 tuple("project", NewCodePeriodType.NUMBER_OF_DAYS.name(), "30"),
271 tuple("branch", NewCodePeriodType.REFERENCE_BRANCH.name(), branch1.uuid()));
273 assertThat(data.getQualityGates())
274 .extracting(TelemetryData.QualityGate::uuid, TelemetryData.QualityGate::caycStatus)
275 .containsExactlyInAnyOrder(
276 tuple(builtInDefaultQualityGate.getUuid(), "non-compliant"),
277 tuple(qualityGate1.getUuid(), "non-compliant"),
278 tuple(qualityGate2.getUuid(), "non-compliant")
283 public void send_branch_measures_data() {
284 Long analysisDate = ZonedDateTime.now(ZoneId.systemDefault()).toInstant().toEpochMilli();
286 MetricDto qg = db.measures().insertMetric(m -> m.setKey(ALERT_STATUS_KEY));
288 ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
290 ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
292 SnapshotDto project1Analysis1 = db.components().insertSnapshot(project1, t -> t.setLast(true).setBuildDate(analysisDate));
293 SnapshotDto project1Analysis2 = db.components().insertSnapshot(project1, t -> t.setLast(true).setBuildDate(analysisDate));
294 SnapshotDto project2Analysis = db.components().insertSnapshot(project2, t -> t.setLast(true).setBuildDate(analysisDate));
295 db.measures().insertMeasure(project1, project1Analysis1, qg, pm -> pm.setData("OK"));
296 db.measures().insertMeasure(project1, project1Analysis2, qg, pm -> pm.setData("ERROR"));
297 db.measures().insertMeasure(project2, project2Analysis, qg, pm -> pm.setData("ERROR"));
299 var branch1 = db.components().insertProjectBranch(project1, branchDto -> branchDto.setKey("reference"));
300 var branch2 = db.components().insertProjectBranch(project1, branchDto -> branchDto.setKey("custom"));
302 db.newCodePeriods().insert(project1.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, "30");
303 db.newCodePeriods().insert(project1.uuid(), branch2.branchUuid(), NewCodePeriodType.REFERENCE_BRANCH, "reference");
305 var instanceNcdId = NewCodeDefinition.getInstanceDefault().hashCode();
306 var projectNcdId = new NewCodeDefinition(NewCodePeriodType.NUMBER_OF_DAYS.name(), "30", "project").hashCode();
307 var branchNcdId = new NewCodeDefinition(NewCodePeriodType.REFERENCE_BRANCH.name(), branch1.uuid(), "branch").hashCode();
309 TelemetryData data = communityUnderTest.load();
311 assertThat(data.getBranches())
312 .extracting(Branch::branchUuid, Branch::ncdId, Branch::greenQualityGateCount, Branch::analysisCount)
313 .containsExactlyInAnyOrder(
314 tuple(branch1.uuid(), projectNcdId, 0, 0),
315 tuple(branch2.uuid(), branchNcdId, 0, 0),
316 tuple(project1.uuid(), projectNcdId, 1, 2),
317 tuple(project2.uuid(), instanceNcdId, 0, 1));
321 private List<UserDto> composeActiveUsers(int count) {
322 UserDbTester userDbTester = db.users();
323 Function<Integer, Consumer<UserDto>> userConfigurator = index -> user -> user.setExternalIdentityProvider("provider" + index).setLastSonarlintConnectionDate(index * 2L);
326 .rangeClosed(1, count)
327 .mapToObj(userConfigurator::apply)
328 .map(userDbTester::insertUser)
329 .collect(Collectors.toList());
332 private void assertDatabaseMetadata(TelemetryData.Database database) {
333 try (DbSession dbSession = db.getDbClient().openSession(false)) {
334 DatabaseMetaData metadata = dbSession.getConnection().getMetaData();
335 assertThat(database.name()).isEqualTo("H2");
336 assertThat(database.version()).isEqualTo(metadata.getDatabaseProductVersion());
337 } catch (SQLException e) {
338 throw new RuntimeException(e);
343 public void take_largest_branch_snapshot_project_data() {
344 server.setId("AU-TpxcB-iU5OvuD2FL7").setVersion("7.5.4");
346 MetricDto lines = db.measures().insertMetric(m -> m.setKey(LINES_KEY));
347 MetricDto ncloc = db.measures().insertMetric(m -> m.setKey(NCLOC_KEY));
348 MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
349 MetricDto nclocDistrib = db.measures().insertMetric(m -> m.setKey(NCLOC_LANGUAGE_DISTRIBUTION_KEY));
351 ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
352 db.measures().insertLiveMeasure(project, lines, m -> m.setValue(110d));
353 db.measures().insertLiveMeasure(project, ncloc, m -> m.setValue(110d));
354 db.measures().insertLiveMeasure(project, coverage, m -> m.setValue(80d));
355 db.measures().insertLiveMeasure(project, nclocDistrib, m -> m.setValue(null).setData("java=70;js=30;kotlin=10"));
357 ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH));
358 db.measures().insertLiveMeasure(branch, lines, m -> m.setValue(180d));
359 db.measures().insertLiveMeasure(branch, ncloc, m -> m.setValue(180d));
360 db.measures().insertLiveMeasure(branch, coverage, m -> m.setValue(80d));
361 db.measures().insertLiveMeasure(branch, nclocDistrib, m -> m.setValue(null).setData("java=100;js=50;kotlin=30"));
363 SnapshotDto project1Analysis = db.components().insertSnapshot(project, t -> t.setLast(true));
364 SnapshotDto project2Analysis = db.components().insertSnapshot(branch, t -> t.setLast(true));
365 db.measures().insertMeasure(project, project1Analysis, nclocDistrib, m -> m.setData("java=70;js=30;kotlin=10"));
366 db.measures().insertMeasure(branch, project2Analysis, nclocDistrib, m -> m.setData("java=100;js=50;kotlin=30"));
368 TelemetryData data = communityUnderTest.load();
370 assertThat(data.getProjects()).extracting(TelemetryData.Project::projectUuid, TelemetryData.Project::language, TelemetryData.Project::loc)
371 .containsExactlyInAnyOrder(
372 tuple(project.uuid(), "java", 100L),
373 tuple(project.uuid(), "js", 50L),
374 tuple(project.uuid(), "kotlin", 30L));
375 assertThat(data.getProjectStatistics())
376 .extracting(ProjectStatistics::getBranchCount, ProjectStatistics::getPullRequestCount,
377 ProjectStatistics::getScm, ProjectStatistics::getCi)
378 .containsExactlyInAnyOrder(
379 tuple(2L, 0L, "undetected", "undetected"));
383 public void test_ncd_on_community_edition() {
384 server.setId("AU-TpxcB-iU5OvuD2FL7").setVersion("7.5.4");
385 when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
387 ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
389 ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH));
391 db.newCodePeriods().insert(project.uuid(), branch.branchUuid(), NewCodePeriodType.NUMBER_OF_DAYS, "30");
393 var projectNcdId = new NewCodeDefinition(NewCodePeriodType.NUMBER_OF_DAYS.name(), "30", "project").hashCode();
395 TelemetryData data = communityUnderTest.load();
397 assertThat(data.getProjectStatistics())
398 .extracting(ProjectStatistics::getBranchCount, ProjectStatistics::getNcdId)
399 .containsExactlyInAnyOrder(tuple(2L, projectNcdId));
401 assertThat(data.getBranches())
402 .extracting(Branch::branchUuid, Branch::ncdId)
403 .contains(tuple(branch.uuid(), projectNcdId));
407 public void data_contains_weekly_count_sonarlint_users() {
408 db.users().insertUser(c -> c.setLastSonarlintConnectionDate(NOW - 100_000L));
409 db.users().insertUser(c -> c.setLastSonarlintConnectionDate(NOW));
411 db.users().insertUser(c -> c.setLastSonarlintConnectionDate(NOW - 1_000_000_000L));
412 db.users().insertUser();
414 TelemetryData data = communityUnderTest.load();
415 assertThat(data.getUserTelemetries())
420 public void send_server_id_and_version() {
421 String id = randomAlphanumeric(40);
422 String version = randomAlphanumeric(10);
424 server.setVersion(version);
426 TelemetryData data = communityUnderTest.load();
427 assertThat(data.getServerId()).isEqualTo(id);
428 assertThat(data.getVersion()).isEqualTo(version);
430 data = commercialUnderTest.load();
431 assertThat(data.getServerId()).isEqualTo(id);
432 assertThat(data.getVersion()).isEqualTo(version);
436 public void send_server_installation_date_and_installation_version() {
437 String installationVersion = "7.9.BEST.LTS.EVER";
438 Long installationDate = 1546300800000L; // 2019/01/01
439 internalProperties.write(InternalProperties.INSTALLATION_DATE, String.valueOf(installationDate));
440 internalProperties.write(InternalProperties.INSTALLATION_VERSION, installationVersion);
442 TelemetryData data = communityUnderTest.load();
444 assertThat(data.getInstallationDate()).isEqualTo(installationDate);
445 assertThat(data.getInstallationVersion()).isEqualTo(installationVersion);
449 public void send_correct_sequence_number() {
450 internalProperties.write(TelemetryDaemon.I_PROP_MESSAGE_SEQUENCE, "10");
451 TelemetryData data = communityUnderTest.load();
452 assertThat(data.getMessageSequenceNumber()).isEqualTo(11L);
456 public void do_not_send_server_installation_details_if_missing_property() {
457 TelemetryData data = communityUnderTest.load();
458 assertThat(data.getInstallationDate()).isNull();
459 assertThat(data.getInstallationVersion()).isNull();
461 data = commercialUnderTest.load();
462 assertThat(data.getInstallationDate()).isNull();
463 assertThat(data.getInstallationVersion()).isNull();
467 public void send_unanalyzed_languages_flags_when_edition_is_community() {
468 when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
469 MetricDto unanalyzedC = db.measures().insertMetric(m -> m.setKey(UNANALYZED_C_KEY));
470 MetricDto unanalyzedCpp = db.measures().insertMetric(m -> m.setKey(UNANALYZED_CPP_KEY));
471 ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
472 ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent();
473 db.measures().insertLiveMeasure(project1, unanalyzedC);
474 db.measures().insertLiveMeasure(project2, unanalyzedC);
475 db.measures().insertLiveMeasure(project2, unanalyzedCpp);
477 TelemetryData data = communityUnderTest.load();
479 assertThat(data.hasUnanalyzedC().get()).isTrue();
480 assertThat(data.hasUnanalyzedCpp().get()).isTrue();
484 public void do_not_send_unanalyzed_languages_flags_when_edition_is_not_community() {
485 when(editionProvider.get()).thenReturn(Optional.of(DEVELOPER));
486 MetricDto unanalyzedC = db.measures().insertMetric(m -> m.setKey(UNANALYZED_C_KEY));
487 MetricDto unanalyzedCpp = db.measures().insertMetric(m -> m.setKey(UNANALYZED_CPP_KEY));
488 ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
489 ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent();
490 db.measures().insertLiveMeasure(project1, unanalyzedC);
491 db.measures().insertLiveMeasure(project2, unanalyzedCpp);
493 TelemetryData data = communityUnderTest.load();
495 assertThat(data.hasUnanalyzedC()).isEmpty();
496 assertThat(data.hasUnanalyzedCpp()).isEmpty();
500 public void unanalyzed_languages_flags_are_set_to_false_when_no_unanalyzed_languages_and_edition_is_community() {
501 when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
503 TelemetryData data = communityUnderTest.load();
505 assertThat(data.hasUnanalyzedC().get()).isFalse();
506 assertThat(data.hasUnanalyzedCpp().get()).isFalse();
510 public void populate_security_custom_config_for_languages_on_enterprise() {
511 when(editionProvider.get()).thenReturn(Optional.of(ENTERPRISE));
513 when(configuration.get("sonar.security.config.javasecurity")).thenReturn(Optional.of("{}"));
514 when(configuration.get("sonar.security.config.phpsecurity")).thenReturn(Optional.of("{}"));
515 when(configuration.get("sonar.security.config.pythonsecurity")).thenReturn(Optional.of("{}"));
516 when(configuration.get("sonar.security.config.roslyn.sonaranalyzer.security.cs")).thenReturn(Optional.of("{}"));
518 TelemetryData data = commercialUnderTest.load();
520 assertThat(data.getCustomSecurityConfigs())
521 .containsExactlyInAnyOrder("java", "php", "python", "csharp");
525 public void skip_security_custom_config_on_community() {
526 when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
528 TelemetryData data = communityUnderTest.load();
530 assertThat(data.getCustomSecurityConfigs()).isEmpty();
534 public void undetected_alm_ci_slm_data() {
535 server.setId("AU-TpxcB-iU5OvuD2FL7").setVersion("7.5.4");
536 db.components().insertPublicProject().getMainBranchComponent();
537 TelemetryData data = communityUnderTest.load();
538 assertThat(data.getProjectStatistics())
539 .extracting(ProjectStatistics::getDevopsPlatform, ProjectStatistics::getScm, ProjectStatistics::getCi)
540 .containsExactlyInAnyOrder(tuple("undetected", "undetected", "undetected"));
544 @UseDataProvider("getManagedInstanceData")
545 public void managedInstanceData_containsCorrectInformation(boolean isManaged, String provider) {
546 when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(isManaged);
547 when(managedInstanceService.getProviderName()).thenReturn(provider);
549 TelemetryData data = commercialUnderTest.load();
551 TelemetryData.ManagedInstanceInformation managedInstance = data.getManagedInstanceInformation();
552 assertThat(managedInstance.isManaged()).isEqualTo(isManaged);
553 assertThat(managedInstance.provider()).isEqualTo(provider);
557 public void default_quality_gate_sent_with_project() {
558 db.components().insertPublicProject().getMainBranchComponent();
559 QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("anything").setBuiltIn(true));
560 db.qualityGates().setDefaultQualityGate(qualityGate);
561 TelemetryData data = communityUnderTest.load();
562 assertThat(data.getProjectStatistics())
563 .extracting(ProjectStatistics::getQualityGate)
564 .containsOnly(qualityGate.getUuid());
567 private PluginInfo newPlugin(String key, String version) {
568 return new PluginInfo(key)
569 .setVersion(Version.create(version));
572 private void insertAnalysisProperty(SnapshotDto snapshotDto, String uuid, String key, String value) {
573 db.getDbClient().analysisPropertiesDao().insert(db.getSession(), new AnalysisPropertyDto()
575 .setAnalysisUuid(snapshotDto.getUuid())
582 public static Set<String> getScimFeatureStatues() {
583 HashSet<String> result = new HashSet<>();
591 public static Object[][] getManagedInstanceData() {
592 return new Object[][] {