-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
PurgeTest.java
363 lines (300 loc) · 15.6 KB
/
PurgeTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package it.dbCleaner;
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.build.BuildResult;
import com.sonar.orchestrator.build.SonarScanner;
import com.sonar.orchestrator.locator.FileLocation;
import it.Category4Suite;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.WsResponse;
import util.ItUtils;
import static org.apache.commons.lang.time.DateUtils.addDays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static util.ItUtils.formatDate;
import static util.ItUtils.newAdminWsClient;
import static util.ItUtils.runProjectAnalysis;
import static util.ItUtils.setServerProperty;
public class PurgeTest {
private static final String COUNT_FILE_SNAPSHOTS = "snapshots where scope='FIL'";
private static final String COUNT_FILE_MEASURES = "project_measures pm, snapshots s where pm.snapshot_id = s.id and s.scope='FIL'";
private static final String COUNT_DIR_SNAPSHOTS = "snapshots where scope='DIR'";
private static final String COUNT_DIR_MEASURES = "project_measures pm, snapshots s where pm.snapshot_id = s.id and s.scope='DIR'";
private static final String PROJECT_KEY = "com.sonarsource.it.samples:multi-modules-sample";
private static final String PROJECT_SAMPLE_PATH = "dbCleaner/xoo-multi-modules-sample";
@ClassRule
public static final Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
@Rule
public ErrorCollector collector = new ErrorCollector();
@Before
public void deleteProjectData() {
orchestrator.resetData();
orchestrator.getServer().provisionProject(PROJECT_KEY, PROJECT_KEY);
orchestrator.getServer().restoreProfile(FileLocation.ofClasspath("/dbCleaner/one-issue-per-line-profile.xml"));
setServerProperty(orchestrator, "sonar.dbcleaner.cleanDirectory", null);
setServerProperty(orchestrator, "sonar.dbcleaner.hoursBeforeKeepingOnlyOneSnapshotByDay", null);
setServerProperty(orchestrator, "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByWeek", null);
}
@Test
public void test_evolution_of_number_of_rows_when_scanning_two_times_the_same_project() {
Date today = new Date();
Date yesterday = DateUtils.addDays(today, -1);
scan(PROJECT_SAMPLE_PATH, DateFormatUtils.ISO_DATE_FORMAT.format(yesterday));
// count components
collector.checkThat("Wrong number of projects", count("projects where qualifier in ('TRK','BRC')"), equalTo(7));
collector.checkThat("Wrong number of directories", count("projects where qualifier in ('DIR')"), equalTo(4));
collector.checkThat("Wrong number of files", count("projects where qualifier in ('FIL')"), equalTo(4));
collector.checkThat("Wrong number of unit test files", count("projects where qualifier in ('UTS')"), equalTo(0));
int measuresOnTrk = 45;
int measuresOnBrc = 222;
int measuresOnDir = 141;
int measuresOnFil = 69;
// count measures
assertMeasuresCountForQualifier("TRK", measuresOnTrk);
assertMeasuresCountForQualifier("BRC", measuresOnBrc);
assertMeasuresCountForQualifier("DIR", measuresOnDir);
assertMeasuresCountForQualifier("FIL", measuresOnFil);
// No new_* metrics measure should be recorded the first time
collector.checkThat(
"Wrong number of measure of new_ metrics",
count("project_measures, metrics where metrics.id = project_measures.metric_id and metrics.name like 'new_%'"),
equalTo(0));
int expectedMeasures = measuresOnTrk + measuresOnBrc + measuresOnDir + measuresOnFil;
collector.checkThat("Wrong number of measures", count("project_measures"), equalTo(expectedMeasures));
collector.checkThat("Wrong number of measure data", count("project_measures where measure_data is not null"), equalTo(0));
// count other tables that are constant between 2 scans
int expectedIssues = 52;
collector.checkThat("Wrong number of issues", count("issues"), equalTo(expectedIssues));
// must be a different date, else a single snapshot is kept per day
scan(PROJECT_SAMPLE_PATH, DateFormatUtils.ISO_DATE_FORMAT.format(today));
int newMeasuresOnTrk = 55;
int newMeasuresOnBrc = 286;
int newMeasuresOnDir = 44;
int newMeasuresOnFil = 0;
assertMeasuresCountForQualifier("TRK", measuresOnTrk + newMeasuresOnTrk);
assertMeasuresCountForQualifier("BRC", measuresOnBrc + newMeasuresOnBrc);
assertMeasuresCountForQualifier("DIR", measuresOnDir + newMeasuresOnDir);
assertMeasuresCountForQualifier("FIL", measuresOnFil + newMeasuresOnFil);
// Measures on new_* metrics should be recorded
collector.checkThat(
"Wrong number of measure of new_ metrics",
count("project_measures, metrics where metrics.id = project_measures.metric_id and metrics.name like 'new_%'"),
equalTo(121));
// added measures relate to project and new_* metrics
expectedMeasures += newMeasuresOnTrk + newMeasuresOnBrc + newMeasuresOnDir + newMeasuresOnFil;
collector.checkThat("Wrong number of measures after second analysis", count("project_measures"), equalTo(expectedMeasures));
collector.checkThat("Wrong number of measure data", count("project_measures where measure_data is not null"), equalTo(0));
collector.checkThat("Wrong number of issues", count("issues"), equalTo(expectedIssues));
}
/**
* SONAR-3378
*/
@Test
public void should_keep_all_snapshots_the_first_day() {
// analyse once
scan(PROJECT_SAMPLE_PATH);
// analyse twice
scan(PROJECT_SAMPLE_PATH);
// and check we have 2 snapshots
assertThat(count("snapshots s where s.component_uuid=(select p.uuid from projects p where p.kee='com.sonarsource.it.samples:multi-modules-sample')")).isEqualTo(2);
}
/**
* SONAR-2807 & SONAR-3378 & SONAR-4710
*/
@Test
public void should_keep_only_one_snapshot_per_day() {
scan(PROJECT_SAMPLE_PATH);
int snapshotsCount = count("snapshots where qualifier<>'LIB'");
int measuresCount = count("project_measures");
// Using the "sonar.dbcleaner.hoursBeforeKeepingOnlyOneSnapshotByDay" property set to '0' is the way
// to keep only 1 snapshot per day
setServerProperty(orchestrator, "sonar.dbcleaner.hoursBeforeKeepingOnlyOneSnapshotByDay", "0");
scan(PROJECT_SAMPLE_PATH);
assertThat(count("snapshots where qualifier<>'LIB'")).as("Different number of snapshots").isEqualTo(snapshotsCount);
int measureOnNewMetrics = count("project_measures, metrics where metrics.id = project_measures.metric_id and metrics.name like 'new_%'");
// Number of measures should be the same as previous, with the measures on new metrics
assertThat(count("project_measures")).as("Different number of measures").isEqualTo(measuresCount + measureOnNewMetrics);
}
/**
* SONAR-7175
*/
@Test
public void keep_latest_snapshot() {
// Keep all snapshots from last 4 weeks
setServerProperty(orchestrator, "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByWeek", "4");
Date oneWeekAgo = addDays(new Date(), -7);
// Execute an analysis wednesday last week
Calendar lastWednesday = Calendar.getInstance();
lastWednesday.setTime(oneWeekAgo);
lastWednesday.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
String lastWednesdayFormatted = formatDate(lastWednesday.getTime());
runProjectAnalysis(orchestrator, PROJECT_SAMPLE_PATH, "sonar.projectDate", lastWednesdayFormatted);
// Execute an analysis thursday last week
Calendar lastThursday = Calendar.getInstance();
lastThursday.setTime(oneWeekAgo);
lastThursday.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
String lastThursdayFormatted = formatDate(lastThursday.getTime());
runProjectAnalysis(orchestrator, PROJECT_SAMPLE_PATH, "sonar.projectDate", lastThursdayFormatted);
// Now only keep 1 snapshot per week
setServerProperty(orchestrator, "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByWeek", "0");
// Execute an analysis today to execute the purge of previous weeks snapshots
runProjectAnalysis(orchestrator, PROJECT_SAMPLE_PATH);
// Check that only analysis from last thursday is kept (as it's the last one from previous week)
WsResponse response = newAdminWsClient(orchestrator).wsConnector().call(
new GetRequest("/api/timemachine/index")
.setParam("resource", PROJECT_KEY)
.setParam("metrics", "ncloc"))
.failIfNotSuccessful();
String content = response.content();
assertThat(content).contains(lastThursdayFormatted);
assertThat(content).doesNotContain(lastWednesdayFormatted);
}
/**
* SONAR-3120
*/
@Test
public void should_delete_removed_modules() {
scan("dbCleaner/modules/before");
assertSingleSnapshot("com.sonarsource.it.samples:multi-modules-sample:module_b");
assertSingleSnapshot("com.sonarsource.it.samples:multi-modules-sample:module_b:module_b1");
// we want the previous snapshot to be purged
setServerProperty(orchestrator, "sonar.dbcleaner.hoursBeforeKeepingOnlyOneSnapshotByDay", "0");
scan("dbCleaner/modules/after");
assertDeleted("com.sonarsource.it.samples:multi-modules-sample:module_b");
assertDeleted("com.sonarsource.it.samples:multi-modules-sample:module_b:module_b1");
assertSingleSnapshot("com.sonarsource.it.samples:multi-modules-sample:module_c:module_c1");
}
/**
* SONAR-3120
*/
@Test
public void should_delete_removed_files() {
scan("dbCleaner/files/before");
assertSingleSnapshot("com.sonarsource.it.samples:multi-modules-sample:module_a:module_a1:src/main/xoo/com/sonar/it/samples/modules/a1/HelloA1.xoo");
scan("dbCleaner/files/after");
assertDeleted("src/main/xoo/com/sonar/it/samples/modules/a1/HelloA1.xoo");
assertSingleSnapshot("com.sonarsource.it.samples:multi-modules-sample:module_a:module_a1:src/main/xoo/com/sonar/it/samples/modules/a1/NewHelloA1.xoo");
}
/**
* SONAR-2754
*/
@Test
public void should_delete_historical_data_of_directories_by_default() {
scan(PROJECT_SAMPLE_PATH, "2012-01-01");
int fileSnapshots = count(COUNT_FILE_SNAPSHOTS);
int fileMeasures = count(COUNT_FILE_MEASURES);
int directorySnapshots = count(COUNT_DIR_SNAPSHOTS);
int dirMeasures = count(COUNT_DIR_MEASURES);
scan(PROJECT_SAMPLE_PATH, "2012-02-02");
assertThat(count(COUNT_FILE_SNAPSHOTS)).isEqualTo(fileSnapshots);
assertThat(count(COUNT_FILE_MEASURES)).isEqualTo(fileMeasures);
assertThat(count(COUNT_DIR_SNAPSHOTS)).isEqualTo(directorySnapshots);
assertThat(count(COUNT_DIR_MEASURES)).isLessThan(2 * dirMeasures); // second analysis as NEW_* metrics
}
/**
* SONAR-2754
*/
@Test
public void should_not_delete_historical_data_of_directories() {
scan(PROJECT_SAMPLE_PATH, "2012-01-01");
int fileSnapshots = count(COUNT_FILE_SNAPSHOTS);
int fileMeasures = count(COUNT_FILE_MEASURES);
int directorySnapshots = count(COUNT_DIR_SNAPSHOTS);
int dirMeasures = count(COUNT_DIR_MEASURES);
setServerProperty(orchestrator, "sonar.dbcleaner.cleanDirectory", "false");
scan(PROJECT_SAMPLE_PATH, "2012-02-02");
assertThat(count(COUNT_FILE_SNAPSHOTS)).isEqualTo(fileSnapshots);
assertThat(count(COUNT_FILE_MEASURES)).isEqualTo(fileMeasures);
assertThat(count(COUNT_DIR_SNAPSHOTS)).isEqualTo(2 * directorySnapshots);
assertThat(count(COUNT_DIR_MEASURES)).isGreaterThan(2 * dirMeasures); // second analysis as NEW_* metrics
}
/**
* SONAR-2061
*/
@Test
public void should_delete_historical_data_of_flagged_metrics() {
scan(PROJECT_SAMPLE_PATH, "2012-01-01");
// historical data of complexity_in_classes is supposed to be deleted (see CoreMetrics)
String selectNcloc = "project_measures where metric_id in (select id from metrics where name='ncloc')";
String selectComplexityInClasses = "project_measures where metric_id in (select id from metrics where name='complexity_in_classes')";
int nclocCount = count(selectNcloc);
int complexitInClassesCount = count(selectComplexityInClasses);
scan(PROJECT_SAMPLE_PATH, "2012-02-02");
assertThat(count(selectNcloc)).isGreaterThan(nclocCount);
assertThat(count(selectComplexityInClasses)).isEqualTo(complexitInClassesCount);
}
private void assertDeleted(String key) {
assertThat(count("snapshots s where s.component_uuid=(select p.uuid from projects p where p.kee='" + key + "')")).isZero();
assertThat(count("resource_index ri where ri.component_uuid=(select p.uuid from projects p where p.kee='" + key + "')")).isZero();
}
private void assertSingleSnapshot(String key) {
assertThat(count("snapshots s where s.component_uuid=(select p.uuid from projects p where p.kee='" + key + "')")).isEqualTo(1);
assertThat(count("resource_index ri where ri.component_uuid=(select p.uuid from projects p where p.kee='" + key + "')")).isGreaterThan(1);
}
private BuildResult scan(String path, String date) {
return scan(path, "sonar.projectDate", date);
}
private BuildResult scan(String path, String... extraProperties) {
SonarScanner runner = configureRunner(path, extraProperties);
return orchestrator.executeBuild(runner);
}
private SonarScanner configureRunner(String projectPath, String... props) {
orchestrator.getServer().associateProjectToQualityProfile(PROJECT_KEY, "xoo", "one-issue-per-line-profile");
return SonarScanner.create(ItUtils.projectDir(projectPath)).setProperties(props);
}
private int count(String condition) {
return orchestrator.getDatabase().countSql("select count(1) from " + condition);
}
private void assertMeasuresCountForQualifier(String qualifier, int count) {
int result = countMeasures(qualifier);
if (result != count) {
logMeasures("GOT", qualifier);
}
collector.checkThat("Wrong number of measures for qualifier " + qualifier, result, equalTo(count));
}
private int countMeasures(String qualifier) {
String sql = "SELECT count(1) FROM project_measures pm, snapshots s, metrics m where pm.snapshot_id=s.id and pm.metric_id=m.id and s.qualifier='" + qualifier + "'";
return orchestrator.getDatabase().countSql(sql);
}
private void logMeasures(String title, String qualifier) {
String sql = "SELECT m.name as metricName, pm.value as value, pm.text_value as textValue, pm.variation_value_1, pm.variation_value_2, pm.variation_value_3 "
+
"FROM project_measures pm, snapshots s, metrics m " +
"WHERE pm.snapshot_id=s.id and pm.metric_id=m.id and s.qualifier='"
+ qualifier + "'";
List<Map<String, String>> rows = orchestrator.getDatabase().executeSql(sql);
System.out.println("---- " + title + " - measures on qualifier " + qualifier);
for (Map<String, String> row : rows) {
System.out.println(" " + row);
}
}
}