-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
AbstractGitTestCase.java
352 lines (303 loc) · 15.2 KB
/
AbstractGitTestCase.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
package hudson.plugins.git;
import com.cloudbees.plugins.credentials.CredentialsNameProvider;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.model.FreeStyleBuild;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.FreeStyleProject;
import hudson.model.Node;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.EnforceGitClient;
import hudson.plugins.git.extensions.impl.DisableRemotePoll;
import hudson.plugins.git.extensions.impl.PathRestriction;
import hudson.plugins.git.extensions.impl.RelativeTargetDirectory;
import hudson.plugins.git.extensions.impl.SparseCheckoutPath;
import hudson.plugins.git.extensions.impl.SparseCheckoutPaths;
import hudson.plugins.git.extensions.impl.UserExclusion;
import hudson.remoting.VirtualChannel;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.triggers.SCMTrigger;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import jenkins.MasterToSlaveFileCallable;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.JGitTool;
import org.junit.Before;
import org.junit.Rule;
import jenkins.plugins.git.GitSampleRepoRule;
import org.jvnet.hudson.test.CaptureEnvironmentBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import static org.junit.Assert.*;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* Base class for single repository git plugin tests.
*
* @author Kohsuke Kawaguchi
* @author ishaaq
*/
public abstract class AbstractGitTestCase {
@Rule
public JenkinsRule rule = new JenkinsRule();
@Rule
public GitSampleRepoRule sampleRepo = new GitSampleRepoRule();
protected TaskListener listener;
protected TestGitRepo testRepo;
// aliases of testRepo properties
protected PersonIdent johnDoe;
protected PersonIdent janeDoe;
protected File workDir; // aliases "gitDir"
protected FilePath workspace; // aliases "gitDirPath"
protected GitClient git;
@Before
public void setUp() throws Exception {
listener = StreamTaskListener.fromStderr();
testRepo = new TestGitRepo("unnamed", sampleRepo.getRoot(), listener);
johnDoe = testRepo.johnDoe;
janeDoe = testRepo.janeDoe;
workDir = testRepo.gitDir;
workspace = testRepo.gitDirPath;
git = testRepo.git;
}
protected String commit(final String fileName, final PersonIdent committer, final String message)
throws GitException, InterruptedException {
return testRepo.commit(fileName, committer, message);
}
protected String commit(final String fileName, final String fileContent, final PersonIdent committer, final String message)
throws GitException, InterruptedException {
return testRepo.commit(fileName, fileContent, committer, message);
}
protected String commit(final String fileName, final PersonIdent author, final PersonIdent committer,
final String message) throws GitException, InterruptedException {
return testRepo.commit(fileName, author, committer, message);
}
protected List<UserRemoteConfig> createRemoteRepositories() throws IOException {
return testRepo.remoteConfigs();
}
protected List<UserRemoteConfig> createRemoteRepositories(StandardCredentials credential) throws IOException {
return testRepo.remoteConfigs(credential);
}
protected FreeStyleProject createFreeStyleProject() throws IOException {
return rule.createFreeStyleProject();
}
protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter) throws Exception {
return setupProject(branchString, authorOrCommitter, null);
}
protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter,
String relativeTargetDir) throws Exception {
return setupProject(branchString, authorOrCommitter, relativeTargetDir, null, null, null);
}
protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter,
String relativeTargetDir,
String excludedRegions,
String excludedUsers,
String includedRegions) throws Exception {
return setupProject(branchString, authorOrCommitter, relativeTargetDir, excludedRegions, excludedUsers, null, false, includedRegions);
}
protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter,
String relativeTargetDir,
String excludedRegions,
String excludedUsers,
boolean fastRemotePoll,
String includedRegions) throws Exception {
return setupProject(branchString, authorOrCommitter, relativeTargetDir, excludedRegions, excludedUsers, null, fastRemotePoll, includedRegions);
}
protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter,
String relativeTargetDir, String excludedRegions,
String excludedUsers, String localBranch, boolean fastRemotePoll,
String includedRegions) throws Exception {
return setupProject(Collections.singletonList(new BranchSpec(branchString)),
authorOrCommitter, relativeTargetDir, excludedRegions,
excludedUsers, localBranch, fastRemotePoll,
includedRegions);
}
protected FreeStyleProject setupProject(String branchString, StandardCredentials credential) throws Exception {
return setupProject(Collections.singletonList(new BranchSpec(branchString)),
false, null, null,
null, null, false,
null, null, credential);
}
protected FreeStyleProject setupProject(List<BranchSpec> branches, boolean authorOrCommitter,
String relativeTargetDir, String excludedRegions,
String excludedUsers, String localBranch, boolean fastRemotePoll,
String includedRegions) throws Exception {
return setupProject(branches,
authorOrCommitter, relativeTargetDir, excludedRegions,
excludedUsers, localBranch, fastRemotePoll,
includedRegions, null, null);
}
protected FreeStyleProject setupProject(String branchString, List<SparseCheckoutPath> sparseCheckoutPaths) throws Exception {
return setupProject(Collections.singletonList(new BranchSpec(branchString)),
false, null, null,
null, null, false,
null, sparseCheckoutPaths, null);
}
protected FreeStyleProject setupProject(List<BranchSpec> branches, boolean authorOrCommitter,
String relativeTargetDir, String excludedRegions,
String excludedUsers, String localBranch, boolean fastRemotePoll,
String includedRegions, List<SparseCheckoutPath> sparseCheckoutPaths,
StandardCredentials credential) throws Exception {
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(credential),
branches,
null, null,
Collections.<GitSCMExtension>emptyList());
if (credential != null) {
project.getBuildersList().add(new HasCredentialBuilder(credential.getId()));
}
scm.getExtensions().add(new DisableRemotePoll()); // don't work on a file:// repository
if (relativeTargetDir!=null)
scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir));
if (excludedUsers!=null)
scm.getExtensions().add(new UserExclusion(excludedUsers));
if (excludedRegions!=null || includedRegions!=null)
scm.getExtensions().add(new PathRestriction(includedRegions,excludedRegions));
scm.getExtensions().add(new SparseCheckoutPaths(sparseCheckoutPaths));
project.setScm(scm);
project.getBuildersList().add(new CaptureEnvironmentBuilder());
return project;
}
/**
* Creates a new project and configures the GitSCM according the parameters.
* @param repos git remote repositories
* @param branchSpecs branch specs
* @param scmTriggerSpec scm trigger spec
* @param disableRemotePoll disable workspace-less polling via "git ls-remote"
* @param enforceGitClient enforce git client
* @return the created project
* @throws Exception on error
*/
protected FreeStyleProject setupProject(List<UserRemoteConfig> repos, List<BranchSpec> branchSpecs,
String scmTriggerSpec, boolean disableRemotePoll, EnforceGitClient enforceGitClient) throws Exception {
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
repos,
branchSpecs,
null, JGitTool.MAGIC_EXENAME,
Collections.<GitSCMExtension>emptyList());
if(disableRemotePoll) scm.getExtensions().add(new DisableRemotePoll());
if(enforceGitClient != null) scm.getExtensions().add(enforceGitClient);
project.setScm(scm);
if(scmTriggerSpec != null) {
SCMTrigger trigger = new SCMTrigger(scmTriggerSpec);
project.addTrigger(trigger);
trigger.start(project, true);
}
//project.getBuildersList().add(new CaptureEnvironmentBuilder());
project.save();
return project;
}
protected FreeStyleProject setupSimpleProject(String branchString) throws Exception {
return setupProject(branchString,false);
}
protected FreeStyleBuild build(final FreeStyleProject project, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception {
final FreeStyleBuild build = project.scheduleBuild2(0).get();
for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) {
assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists());
}
if(expectedResult != null) {
rule.assertBuildStatus(expectedResult, build);
}
return build;
}
protected FreeStyleBuild build(final FreeStyleProject project, final String parentDir, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception {
final FreeStyleBuild build = project.scheduleBuild2(0).get();
for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) {
assertTrue(build.getWorkspace().child(parentDir).child(expectedNewlyCommittedFile).exists());
}
if(expectedResult != null) {
rule.assertBuildStatus(expectedResult, build);
}
return build;
}
protected MatrixBuild build(final MatrixProject project, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception {
final MatrixBuild build = project.scheduleBuild2(0).get();
for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) {
assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists());
}
if(expectedResult != null) {
rule.assertBuildStatus(expectedResult, build);
}
return build;
}
protected EnvVars getEnvVars(FreeStyleProject project) {
for (hudson.tasks.Builder b : project.getBuilders()) {
if (b instanceof CaptureEnvironmentBuilder) {
return ((CaptureEnvironmentBuilder)b).getEnvVars();
}
}
return new EnvVars();
}
protected void setVariables(Node node, EnvironmentVariablesNodeProperty.Entry... entries) throws IOException {
node.getNodeProperties().replaceBy(
Collections.singleton(new EnvironmentVariablesNodeProperty(
entries)));
}
protected String getHeadRevision(AbstractBuild build, final String branch) throws IOException, InterruptedException {
return build.getWorkspace().act(new MasterToSlaveFileCallable<String>() {
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
try {
@SuppressWarnings("deprecation") // Local repository reference
org.eclipse.jgit.lib.Repository repo = Git.with(null, null).in(f).getClient().getRepository();
ObjectId oid = repo.resolve("refs/heads/" + branch);
return oid.name();
} catch (GitException e) {
throw new RuntimeException(e);
}
}
});
}
public static class HasCredentialBuilder extends Builder {
private final String id;
@DataBoundConstructor
public HasCredentialBuilder(String id) {
this.id = id;
}
public String getId() {
return id;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
IdCredentials credentials = CredentialsProvider.findCredentialById(id, IdCredentials.class, build);
if (credentials == null) {
listener.getLogger().printf("Could not find any credentials with id %s%n", id);
build.setResult(Result.FAILURE);
return false;
} else {
listener.getLogger().printf("Found %s credentials with id %s%n", CredentialsNameProvider.name(credentials), id);
return true;
}
}
@TestExtension
public static class DescriptorImpl extends BuildStepDescriptor<Builder> {
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@Override
public String getDisplayName() {
return "Check that credentials exist";
}
}
}
}