aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-scanner-engine/src/test/java/org/sonar/scm/svn/SvnScmProviderTest.java
blob: c815fdda0bfd859313bf45ef779ebfbd781c0fee (plain)
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
/*
 * SonarQube
 * Copyright (C) 2009-2020 SonarSource SA
 * mailto:info 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 org.sonar.scm.svn;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.scm.ScmProvider;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNWCClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class SvnScmProviderTest {

  // Sample content for unified diffs
  // http://www.gnu.org/software/diffutils/manual/html_node/Example-Unified.html#Example-Unified
  private static final String CONTENT_LAO = "The Way that can be told of is not the eternal Way;\n"
    + "The name that can be named is not the eternal name.\n"
    + "The Nameless is the origin of Heaven and Earth;\n"
    + "The Named is the mother of all things.\n"
    + "Therefore let there always be non-being,\n"
    + "  so we may see their subtlety,\n"
    + "And let there always be being,\n"
    + "  so we may see their outcome.\n"
    + "The two are the same,\n"
    + "But after they are produced,\n"
    + "  they have different names.\n";

  private static final String CONTENT_TZU = "The Nameless is the origin of Heaven and Earth;\n"
    + "The named is the mother of all things.\n"
    + "\n"
    + "Therefore let there always be non-being,\n"
    + "  so we may see their subtlety,\n"
    + "And let there always be being,\n"
    + "  so we may see their outcome.\n"
    + "The two are the same,\n"
    + "But after they are produced,\n"
    + "  they have different names.\n"
    + "They both may be called deep and profound.\n"
    + "Deeper and more profound,\n"
    + "The door of all subtleties!";

  @Rule
  public TemporaryFolder temp = new TemporaryFolder();

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  private FindFork findFork = mock(FindFork.class);
  private SvnConfiguration config = mock(SvnConfiguration.class);
  private SvnTester svnTester;

  @Before
  public void before() throws IOException, SVNException {
    svnTester = new SvnTester(temp.newFolder().toPath());

    Path worktree = temp.newFolder().toPath();
    svnTester.checkout(worktree, "trunk");
    createAndCommitFile(worktree, "file-in-first-commit.xoo");
  }

  @Test
  public void sanityCheck() {
    SvnBlameCommand blameCommand = new SvnBlameCommand(config);
    SvnScmProvider svnScmProvider = new SvnScmProvider(config, blameCommand, findFork);
    assertThat(svnScmProvider.key()).isEqualTo("svn");
    assertThat(svnScmProvider.blameCommand()).isEqualTo(blameCommand);
  }

  @Test
  public void testAutodetection() throws IOException {
    ScmProvider scmBranchProvider = newScmProvider();

    File baseDirEmpty = temp.newFolder();
    assertThat(scmBranchProvider.supports(baseDirEmpty)).isFalse();

    File svnBaseDir = temp.newFolder();
    Files.createDirectory(svnBaseDir.toPath().resolve(".svn"));
    assertThat(scmBranchProvider.supports(svnBaseDir)).isTrue();

    File svnBaseDirSubFolder = temp.newFolder();
    Files.createDirectory(svnBaseDirSubFolder.toPath().resolve(".svn"));
    File projectBaseDir = new File(svnBaseDirSubFolder, "folder");
    Files.createDirectory(projectBaseDir.toPath());
    assertThat(scmBranchProvider.supports(projectBaseDir)).isTrue();
  }

  @Test
  public void branchChangedFiles_and_lines_from_diverged() throws IOException, SVNException {
    Path trunk = temp.newFolder().toPath();
    svnTester.checkout(trunk, "trunk");
    createAndCommitFile(trunk, "file-m1.xoo");
    createAndCommitFile(trunk, "file-m2.xoo");
    createAndCommitFile(trunk, "file-m3.xoo");
    createAndCommitFile(trunk, "lao.txt", CONTENT_LAO);

    // create branch from trunk
    svnTester.createBranch("b1");

    // still on trunk
    appendToAndCommitFile(trunk, "file-m3.xoo");
    createAndCommitFile(trunk, "file-m4.xoo");

    Path b1 = temp.newFolder().toPath();
    svnTester.checkout(b1, "branches/b1");
    Files.createDirectories(b1.resolve("sub"));
    createAndCommitFile(b1, "sub/file-b1.xoo");
    appendToAndCommitFile(b1, "file-m1.xoo");
    deleteAndCommitFile(b1, "file-m2.xoo");

    createAndCommitFile(b1, "file-m5.xoo");
    deleteAndCommitFile(b1, "file-m5.xoo");

    svnCopyAndCommitFile(b1, "file-m1.xoo", "file-m1-copy.xoo");
    appendToAndCommitFile(b1, "file-m1.xoo");

    // modify file without committing it -> should not be included (think generated files)
    svnTester.appendToFile(b1, "file-m3.xoo");

    svnTester.update(b1);

    Set<Path> changedFiles = newScmProvider().branchChangedFiles("trunk", b1);
    assertThat(changedFiles)
      .containsExactlyInAnyOrder(
        b1.resolve("sub/file-b1.xoo"),
        b1.resolve("file-m1.xoo"),
        b1.resolve("file-m1-copy.xoo"));

    // use a subset of changed files for .branchChangedLines to verify only requested files are returned
    assertThat(changedFiles.remove(b1.resolve("sub/file-b1.xoo"))).isTrue();

    // generate common sample diff
    createAndCommitFile(b1, "lao.txt", CONTENT_TZU);
    changedFiles.add(b1.resolve("lao.txt"));

    // a file that should not yield any results
    changedFiles.add(b1.resolve("nonexistent"));

    // modify file without committing to it
    svnTester.appendToFile(b1, "file-m1.xoo");

    Map<Path, Set<Integer>> expected = new HashMap<>();
    expected.put(b1.resolve("lao.txt"), new HashSet<>(Arrays.asList(2, 3, 11, 12, 13)));
    expected.put(b1.resolve("file-m1.xoo"), new HashSet<>(Arrays.asList(2, 3, 4)));
    expected.put(b1.resolve("file-m1-copy.xoo"), new HashSet<>(Arrays.asList(1, 2)));

    assertThat(newScmProvider().branchChangedLines("trunk", b1, changedFiles))
      .isEqualTo(expected);

    assertThat(newScmProvider().branchChangedLines("trunk", b1, Collections.singleton(b1.resolve("nonexistent"))))
      .isEmpty();
  }

  @Test
  public void branchChangedFiles_should_return_empty_when_no_local_changes() throws IOException, SVNException {
    Path b1 = temp.newFolder().toPath();
    svnTester.createBranch("b1");
    svnTester.checkout(b1, "branches/b1");

    assertThat(newScmProvider().branchChangedFiles("b1", b1)).isEmpty();
  }

  @Test
  public void branchChangedFiles_should_return_null_when_repo_nonexistent() throws IOException {
    assertThat(newScmProvider().branchChangedFiles("trunk", temp.newFolder().toPath())).isNull();
  }

  @Test
  public void branchChangedFiles_should_return_null_when_dir_nonexistent() {
    assertThat(newScmProvider().branchChangedFiles("trunk", temp.getRoot().toPath().resolve("nonexistent"))).isNull();
  }

  @Test
  public void branchChangedLines_should_return_null_when_repo_nonexistent() throws IOException {
    assertThat(newScmProvider().branchChangedLines("trunk", temp.newFolder().toPath(), Collections.emptySet())).isNull();
  }

  @Test
  public void branchChangedLines_should_return_null_when_dir_nonexistent() {
    assertThat(newScmProvider().branchChangedLines("trunk", temp.getRoot().toPath().resolve("nonexistent"), Collections.emptySet())).isNull();
  }

  @Test
  public void branchChangedLines_should_return_empty_when_no_local_changes() throws IOException, SVNException {
    Path b1 = temp.newFolder().toPath();
    svnTester.createBranch("b1");
    svnTester.checkout(b1, "branches/b1");

    assertThat(newScmProvider().branchChangedLines("b1", b1, Collections.emptySet())).isEmpty();
  }

  @Test
  public void branchChangedLines_should_return_null_when_invalid_diff_format() throws IOException, SVNException {
    Path b1 = temp.newFolder().toPath();
    svnTester.createBranch("b1");
    svnTester.checkout(b1, "branches/b1");

    SvnScmProvider scmProvider = new SvnScmProvider(config, new SvnBlameCommand(config), findFork) {
      @Override
      ChangedLinesComputer newChangedLinesComputer(Path rootBaseDir, Set<Path> changedFiles) {
        throw new IllegalStateException("crash");
      }
    };
    assertThat(scmProvider.branchChangedLines("b1", b1, Collections.emptySet())).isNull();
  }

  @Test
  public void forkDate_returns_null_if_no_fork_found() {
    assertThat(new SvnScmProvider(config, new SvnBlameCommand(config), findFork).forkDate("branch", Paths.get(""))).isNull();
  }

  @Test
  public void forkDate_returns_instant_if_fork_found() throws SVNException {
    Path rootBaseDir = Paths.get("");
    String referenceBranch = "branch";
    Instant forkDate = Instant.ofEpochMilli(123456789L);
    SvnScmProvider provider = new SvnScmProvider(config, new SvnBlameCommand(config), findFork);
    when(findFork.findDate(rootBaseDir, referenceBranch)).thenReturn(forkDate);

    assertThat(provider.forkDate(referenceBranch, rootBaseDir)).isEqualTo(forkDate);
  }

  @Test
  public void forkDate_returns_null_if_exception_occurs() throws SVNException {
    Path rootBaseDir = Paths.get("");
    String referenceBranch = "branch";
    SvnScmProvider provider = new SvnScmProvider(config, new SvnBlameCommand(config), findFork);
    when(findFork.findDate(rootBaseDir, referenceBranch)).thenThrow(new SVNCancelException());

    assertThat(provider.forkDate(referenceBranch, rootBaseDir)).isNull();
  }

  @Test
  public void computeChangedPaths_should_not_crash_when_getRepositoryRootURL_getPath_is_empty() throws SVNException {
    // verify assumptions about what SVNKit returns as svn root path for urls like http://svnserver/
    assertThat(SVNURL.parseURIEncoded("http://svnserver/").getPath()).isEmpty();
    assertThat(SVNURL.parseURIEncoded("http://svnserver").getPath()).isEmpty();

    SVNClientManager svnClientManagerMock = mock(SVNClientManager.class);

    SVNWCClient svnwcClientMock = mock(SVNWCClient.class);
    when(svnClientManagerMock.getWCClient()).thenReturn(svnwcClientMock);

    SVNLogClient svnLogClient = mock(SVNLogClient.class);
    when(svnClientManagerMock.getLogClient()).thenReturn(svnLogClient);

    SVNInfo svnInfoMock = mock(SVNInfo.class);
    when(svnwcClientMock.doInfo(any(), any())).thenReturn(svnInfoMock);

    // Simulate repository root on /, SVNKIT then returns an repository root url WITHOUT / at the end.
    when(svnInfoMock.getRepositoryRootURL()).thenReturn(SVNURL.parseURIEncoded("http://svnserver"));
    when(svnInfoMock.getURL()).thenReturn(SVNURL.parseURIEncoded("http://svnserver/myproject/trunk/"));

    assertThat(SvnScmProvider.computeChangedPaths(Paths.get("/"), svnClientManagerMock)).isEmpty();
  }

  private void createAndCommitFile(Path worktree, String filename, String content) throws IOException, SVNException {
    svnTester.createFile(worktree, filename, content);
    svnTester.add(worktree, filename);
    svnTester.commit(worktree);
  }

  private void createAndCommitFile(Path worktree, String filename) throws IOException, SVNException {
    createAndCommitFile(worktree, filename, filename + "\n");
  }

  private void appendToAndCommitFile(Path worktree, String filename) throws IOException, SVNException {
    svnTester.appendToFile(worktree, filename);
    svnTester.commit(worktree);
  }

  private void deleteAndCommitFile(Path worktree, String filename) throws IOException, SVNException {
    svnTester.deleteFile(worktree, filename);
    svnTester.commit(worktree);
  }

  private void svnCopyAndCommitFile(Path worktree, String src, String dst) throws SVNException {
    svnTester.copy(worktree, src, dst);
    svnTester.commit(worktree);
  }

  private SvnScmProvider newScmProvider() {
    return new SvnScmProvider(config, new SvnBlameCommand(config), findFork);
  }
}