-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathIntegrationTest.java
More file actions
905 lines (836 loc) · 29.4 KB
/
Copy pathIntegrationTest.java
File metadata and controls
905 lines (836 loc) · 29.4 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
package io.jenkins.plugins.util;
import org.junit.jupiter.api.Tag;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.JSONWebResponse;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import edu.hm.hafner.util.PathUtil;
import edu.hm.hafner.util.ResourceTest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import java.util.function.Function;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.flow.FlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.Action;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.FreeStyleProject;
import hudson.model.Node;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.Slave;
import hudson.model.TopLevelItem;
import hudson.model.labels.LabelAtom;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.plugins.sshslaves.verifiers.NonVerifyingKeyVerificationStrategy;
import hudson.slaves.DumbSlave;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.EnvironmentVariablesNodeProperty.Entry;
import hudson.tasks.BatchFile;
import hudson.tasks.Builder;
import hudson.tasks.Shell;
import jenkins.model.ParameterizedJobMixIn.ParameterizedJob;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assumptions.*;
/**
* Base class for integration tests in Jenkins.
*
* @author Ullrich Hafner
*/
@Tag("IntegrationTest")
@SuppressWarnings({"ClassDataAbstractionCoupling", "ClassFanOutComplexity", "SameParameterValue", "PMD.SystemPrintln", "PMD.CouplingBetweenObjects", "PMD.CyclomaticComplexity", "unused"})
public abstract class IntegrationTest extends ResourceTest {
private static final Charset UTF_8 = StandardCharsets.UTF_8;
/** Name of the agent when used in a {@code node()} statement. */
protected static final String DOCKER_AGENT_NAME = "docker-agent";
private static final String SSH_CREDENTIALS_ID = "sshCredentialsId";
private static final String USER = "jenkins";
private static final String PASSPHRASE = "";
private static final int SSH_PORT = 22;
private static final String AGENT_WORK_DIR = "/home/jenkins";
private static final String WINDOWS_FILE_ACCESS_READ_ONLY = "RX";
private static final String WINDOWS_FILE_DENY = "/deny";
/**
* Returns the Jenkins rule to manage the Jenkins instance.
*
* @return Jenkins rule
*/
protected abstract JenkinsRule getJenkins();
/**
* Creates a file with the specified content in the workspace.
*
* @param job
* the job to get the workspace for
* @param fileName
* the files to create
* @param content
* the content of the file
*/
protected void createFileInWorkspace(final TopLevelItem job, final String fileName, final String content) {
try {
var workspace = getWorkspace(job);
var child = workspace.child(fileName);
child.copyFrom(new ByteArrayInputStream(content.getBytes(UTF_8)));
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Copies the specified files to the workspace. The copied files will have the same file name in the workspace.
*
* @param job
* the job to get the workspace for
* @param fileNames
* the files to copy
*/
protected void copyMultipleFilesToWorkspace(final TopLevelItem job, final String... fileNames) {
copyWorkspaceFiles(job, fileNames, file -> Path.of(file).getFileName().toString());
}
/**
* Copies the specified file to the workspace.
*
* @param job
* the job to get the workspace for
* @param fileName
* the file to copy
*/
protected void copySingleFileToWorkspace(final TopLevelItem job, final String fileName) {
var workspace = getWorkspace(job);
copySingleFileToWorkspace(workspace, fileName, fileName);
}
/**
* Copies the specified files to the workspace. Uses the specified new file name in the workspace.
*
* @param job
* the job to get the workspace for
* @param from
* the file to copy
* @param to
* the file name in the workspace
*/
protected void copySingleFileToWorkspace(final TopLevelItem job, final String from, final String to) {
var workspace = getWorkspace(job);
copySingleFileToWorkspace(workspace, from, to);
}
/**
* Copies the specified files to the workspace. The file names of the copied files will be determined by the
* specified mapper.
*
* @param job
* the job to get the workspace for
* @param fileNames
* the files to copy
* @param fileNameMapper
* maps input file names to output file names
*/
protected void copyWorkspaceFiles(final TopLevelItem job, final String[] fileNames,
final Function<String, String> fileNameMapper) {
Arrays.stream(fileNames)
.forEach(fileName -> copySingleFileToWorkspace(job, fileName, fileNameMapper.apply(fileName)));
}
/**
* Returns the console log as a String.
*
* @param build
* the build to get the log for
*
* @return the console log
*/
protected String getConsoleLog(final Run<?, ?> build) {
try {
return JenkinsRule.getLog(build);
}
catch (IOException e) {
throw new AssertionError(e);
}
}
/**
* Copies the specified file to the workspace.
*
* @param job
* the job to get the workspace for
* @param fileName
* the file to copy
*/
protected void copyFileToWorkspace(final TopLevelItem job, final String fileName) {
var workspace = getWorkspace(job);
copyFileToWorkspace(workspace, fileName, fileName);
}
/**
* Copies the specified files to the workspace. Uses the specified new file name in the workspace.
*
* @param job
* the job to get the workspace for
* @param from
* the file to copy
* @param to
* the file name in the workspace
*/
protected void copyFileToWorkspace(final TopLevelItem job, final String from, final String to) {
var workspace = getWorkspace(job);
copyFileToWorkspace(workspace, from, to);
}
/**
* Copies the specified files to the workspace.
*
* @param job
* the job to get the workspace for
* @param fileNames
* the files to copy
*/
protected void copyFilesToWorkspace(final TopLevelItem job, final String... fileNames) {
Arrays.stream(fileNames).forEach(fileName -> copyFileToWorkspace(job, fileName, fileName));
}
/**
* Copies the specified directory recursively to the workspace.
*
* @param job
* the job to get the workspace for
* @param directory
* the directory to copy
*/
protected void copyDirectoryToWorkspace(final TopLevelItem job, final String directory) {
try {
var resource = getTestResourceClass().getResource(directory);
assertThat(resource).as("No such file: %s", directory).isNotNull();
var destination = new FilePath(new File(resource.getFile()));
assertThat(destination.exists()).as("Directory %s does not exist", resource.getFile()).isTrue();
destination.copyRecursiveTo(getWorkspace(job));
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
private void copyFileToWorkspace(final FilePath workspace, final String from, final String to) {
try {
workspace.child(to).copyFrom(asInputStream(from));
System.out.format("Copying file '%s' as workspace file '%s'%n", from, to);
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Returns the workspace for the specified job.
*
* @param job
* the job to get the workspace for
*
* @return the workspace
*/
protected FilePath getWorkspace(final TopLevelItem job) {
var workspace = getJenkins().jenkins.getWorkspaceFor(job);
assertThat(workspace).isNotNull();
return workspace;
}
/**
* Returns the absolute path of the specified file.
*
* @param job
* the job with the workspace that contains the file
* @param fileName
* the file name
*
* @return the workspace
*/
protected String getAbsolutePathOfWorkspaceFile(final TopLevelItem job, final String fileName) {
return new PathUtil().createAbsolutePath(getWorkspace(job).getRemote(), fileName);
}
private void copySingleFileToWorkspace(final FilePath workspace, final String from, final String to) {
try {
workspace.child(to).copyFrom(asInputStream(from));
System.out.format("Copying file '%s' as workspace file '%s'%n (workspace '%s')", from, to, workspace);
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Creates an {@link DumbSlave agent} with the specified label.
*
* @param label
* the label of the agent
*
* @return the agent
*/
@SuppressWarnings("illegalcatch")
protected Slave createAgent(final String label) {
try {
return getJenkins().createOnlineSlave(new LabelAtom(label));
}
catch (Exception e) {
throw new AssertionError(e);
}
}
/**
* Creates an {@link Node agent} that runs in the provided docker container.
*
* @param agentContainer
* the docker container to use as agent
* @param label
* the label to use for the agent
*
* @return the agent
*/
protected Node createDockerAgent(final AgentContainer agentContainer, final String label) {
try {
var agent = createDockerAgent(agentContainer);
agent.setLabelString(label);
return agent;
}
catch (IOException exception) {
throw new AssertionError(exception);
}
}
/**
* Creates an {@link Node agent} that runs in the provided docker container.
*
* @param agentContainer
* the docker container to use as agent
*
* @return the agent
*/
protected Node createDockerAgent(final AgentContainer agentContainer) {
try {
var node = createPermanentAgent(agentContainer.getHost(), agentContainer.getMappedPort(SSH_PORT));
waitForAgentConnected(node);
return node;
}
catch (FormException | IOException | InterruptedException exception) {
throw new AssertionError(exception);
}
}
private Node createPermanentAgent(final String host, final int sshPort)
throws Descriptor.FormException, IOException {
var privateKey = toString("/ssh/rsa_private_key");
var privateKeySource = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(privateKey);
var credentials = new BasicSSHUserPrivateKey(CredentialsScope.SYSTEM, SSH_CREDENTIALS_ID, USER, privateKeySource,
PASSPHRASE, "Private Key ssh credentials");
SystemCredentialsProvider.getInstance().getDomainCredentialsMap().put(Domain.global(),
Collections.singletonList(credentials));
var launcher = new SSHLauncher(host, sshPort, SSH_CREDENTIALS_ID);
launcher.setSshHostKeyVerificationStrategy(new NonVerifyingKeyVerificationStrategy());
var agent = new DumbSlave(DOCKER_AGENT_NAME, AGENT_WORK_DIR, launcher);
agent.setNodeProperties(Collections.singletonList(new EnvironmentVariablesNodeProperty(new Entry("JAVA_HOME", "/usr/lib/jvm/java-11-openjdk-amd64"))));
var jenkins = getJenkins().jenkins;
jenkins.addNode(agent);
return jenkins.getNode(agent.getNodeName());
}
@SuppressWarnings({"BusyWait", "PMD.DoNotUseThreads"})
private void waitForAgentConnected(final Node node) throws InterruptedException {
int count = 0;
while (!Objects.requireNonNull(node.toComputer()).isOnline() && count < 150) {
Thread.sleep(1000);
count++;
}
assertThat(Objects.requireNonNull(node.toComputer()).isOnline()).isTrue();
}
/**
* Creates an {@link DumbSlave agent} with the specified label. Master - agent security will be enabled.
*
* @param label
* the label of the agent
*
* @return the agent
*/
protected Slave createAgentWithEnabledSecurity(final String label) {
try {
var agent = createAgent(label);
var child = getJenkins().getInstance()
.getRootPath()
.child("secrets/filepath-filters.d/30-default.conf");
child.delete();
child.write("", "ISO_8859_1");
getJenkins().jenkins.save();
return agent;
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Returns the agent workspace of a job.
*
* @param agent
* the agent
* @param job
* the job
*
* @return path to the workspace
*/
protected FilePath getAgentWorkspace(final Node agent, final TopLevelItem job) {
var workspace = agent.getWorkspaceFor(job);
assertThat(workspace).isNotNull();
return workspace;
}
/**
* Creates the specified file with the given content to the workspace of the specified agent.
*
* @param agent
* the agent to get the workspace for
* @param job
* the job to get the workspace for
* @param fileName
* the file name
* @param content
* the content to write
*/
protected void createFileInAgentWorkspace(final Node agent, final TopLevelItem job, final String fileName,
final String content) {
try {
var workspace = getAgentWorkspace(agent, job);
var child = workspace.child(fileName);
child.copyFrom(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Copies the specified files to the workspace of the specified agent. Uses the specified new file name in the
* workspace.
*
* @param agent
* the agent to get the workspace for
* @param job
* the job to get the workspace for
* @param fileName
* the file to copy
*/
protected void copySingleFileToAgentWorkspace(final Node agent, final TopLevelItem job,
final String fileName) {
copySingleFileToAgentWorkspace(agent, job, fileName, fileName);
}
/**
* Copies the specified files to the workspace of the specified agent. Uses the specified new file name in the
* workspace.
*
* @param agent
* the agent to get the workspace for
* @param job
* the job to get the workspace for
* @param from
* the file to copy
* @param to
* the file name in the workspace
*/
protected void copySingleFileToAgentWorkspace(final Node agent, final TopLevelItem job,
final String from, final String to) {
var workspace = getAgentWorkspace(agent, job);
copyFileToWorkspace(workspace, from, to);
}
/**
* Creates a new {@link FreeStyleProject freestyle job}. The job will get a generated name.
*
* @return the created job
*/
protected FreeStyleProject createFreeStyleProject() {
return createProject(FreeStyleProject.class);
}
/**
* Creates a new {@link FreeStyleProject freestyle job} and copies the specified resources to the workspace folder.
* The job will get a generated name.
*
* @param fileNames
* the files to copy to the workspace
*
* @return the created job
*/
protected FreeStyleProject createFreeStyleProjectWithWorkspaceFiles(final String... fileNames) {
var job = createFreeStyleProject();
copyFilesToWorkspace(job, fileNames);
return job;
}
/**
* Creates a new job of the specified type. The job will get a generated name.
*
* @param type
* type of the job
* @param <T>
* the project type
*
* @return the created job
*/
protected <T extends TopLevelItem> T createProject(final Class<T> type) {
try {
return getJenkins().createProject(type);
}
catch (IOException e) {
throw new AssertionError(e);
}
}
/**
* Creates a new job of the specified type.
*
* @param type
* type of the job
* @param name
* the name of the job
* @param <T>
* the project type
*
* @return the created job
*/
protected <T extends TopLevelItem> T createProject(final Class<T> type, final String name) {
try {
return getJenkins().createProject(type, name);
}
catch (IOException e) {
throw new AssertionError(e);
}
}
/**
* Wraps the specified steps into a stage.
*
* @param steps
* the steps of the stage
*
* @return the pipeline script
*/
@SuppressWarnings({"UseOfSystemOutOrSystemErr", "PMD.ConsecutiveLiteralAppends"})
protected CpsFlowDefinition asStage(final String... steps) {
var script = new StringBuilder(1024);
script.append("node {\n");
script.append(" stage ('Integration Test') {\n");
for (String step : steps) {
script.append(" ");
script.append(step);
script.append('\n');
}
script.append(" }\n");
script.append("}\n");
var jenkinsFile = script.toString();
logJenkinsFile(jenkinsFile);
return createPipelineScript(jenkinsFile);
}
/**
* Creates an empty pipeline job and populates the workspace of that job with copies of the specified files.
*
* @param fileNames
* the files to copy to the workspace
*
* @return the pipeline job
*/
protected WorkflowJob createPipelineWithWorkspaceFiles(final String... fileNames) {
var job = createPipeline();
copyFilesToWorkspace(job, fileNames);
return job;
}
/**
* Creates an empty pipeline job.
*
* @return the pipeline job
*/
protected WorkflowJob createPipeline() {
return createProject(WorkflowJob.class);
}
/**
* Creates an empty pipeline job with the specified name.
*
* @param name
* the name of the job
*
* @return the pipeline job
*/
protected WorkflowJob createPipeline(final String name) {
return createProject(WorkflowJob.class, name);
}
/**
* Reads a JenkinsFile (i.e. a {@link FlowDefinition}) from the specified file.
*
* @param fileName
* path to the JenkinsFile
*
* @return the JenkinsFile as {@link FlowDefinition} instance
*/
protected FlowDefinition readJenkinsFile(final String fileName) {
var script = toString(fileName);
logJenkinsFile(script);
return createPipelineScript(script);
}
/**
* Creates {@link CpsFlowDefinition a pipeline} from the specified script.
*
* @param script the pipeline script (scripted pipeline)
* @return the pipeline definition
*/
protected CpsFlowDefinition createPipelineScript(final String script) {
try {
return new CpsFlowDefinition(script, true);
}
catch (FormException exception) {
throw new AssertionError(exception);
}
}
/**
* Schedules a build for the specified job and waits for the job to finish. After the build has been finished the
* builds result is checked to be equals to {@link Result#SUCCESS}.
*
* @param job
* the job to schedule
*
* @return the finished build with status {@link Result#SUCCESS}
*/
protected Run<?, ?> buildSuccessfully(final ParameterizedJob<?, ?> job) {
return buildWithResult(job, Result.SUCCESS);
}
/**
* Asserts that the builds result is equal to {@link Result#SUCCESS}.
*
* @param run
* the run to check
*/
@SuppressWarnings("checkstyle:IllegalCatch")
protected void assertSuccessfulBuild(final Run<?, ?> run) {
try {
getJenkins().assertBuildStatus(Result.SUCCESS, run);
}
catch (Exception exception) {
throw new AssertionError(exception);
}
}
/**
* Schedules a build for the specified job and waits for the job to finish. After the build has been finished the
* builds result is checked to be equals to {@code expectedResult}.
*
* @param job
* the job to schedule
* @param expectedResult
* the expected result for the build
*
* @return the finished build with status {@code expectedResult}
*/
@SuppressWarnings({"illegalcatch", "OverlyBroadCatchBlock"})
protected Run<?, ?> buildWithResult(final ParameterizedJob<?, ?> job, final Result expectedResult) {
try {
return getJenkins().assertBuildStatus(expectedResult,
Objects.requireNonNull(job.scheduleBuild2(0, new Action[0])));
}
catch (Exception e) {
throw new AssertionError(e);
}
}
/**
* Prints the content of the JenkinsFile to StdOut.
*
* @param script
* the script
*/
@SuppressWarnings("PMD.SystemPrintln")
private void logJenkinsFile(final String script) {
System.out.println("----------------------------------------------------------------------");
System.out.println(script);
System.out.println("----------------------------------------------------------------------");
}
/**
* Prints the console log of the specified build to StdOut.
*
* @param build
* the build
*/
protected void printConsoleLog(final Run<?, ?> build) {
System.out.println("----- Console Log -----");
try (var reader = build.getLogReader()) {
try (var bufferedReader = new BufferedReader(reader)) {
bufferedReader.lines().forEach(System.out::println);
}
}
catch (IOException exception) {
throw new AssertionError(exception);
}
}
/**
* Makes the specified file unreadable.
*
* @param file
* the specified file
*/
protected void makeFileUnreadable(final Path file) {
makeFileUnreadable(file.toString());
}
/**
* Makes the specified file unreadable.
*
* @param absolutePath
* the specified file
*/
protected void makeFileUnreadable(final String absolutePath) {
var nonReadableFile = new File(absolutePath);
if (Functions.isWindows()) {
setAccessModeOnWindows(absolutePath, WINDOWS_FILE_DENY, WINDOWS_FILE_ACCESS_READ_ONLY);
}
else {
assertThat(nonReadableFile.setReadable(false, false)).isTrue();
assumeThat(nonReadableFile.canRead())
.as("File ´%s´ could not be made unreadable (OS configuration problem?)", absolutePath)
.isFalse();
}
}
private void setAccessModeOnWindows(final String path, final String command, final String accessMode) {
try {
var process = new ProcessBuilder("icacls",
path, command, "*S-1-1-0:" + accessMode)
.redirectErrorStream(true)
.start();
var exitCode = process.waitFor();
if (exitCode != 0) {
String output;
try (var in = process.getInputStream()) {
output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
throw new AssertionError("icacls failed with exit code " + exitCode + ": " + output);
}
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Adds a script as a {@link Shell} or {@link BatchFile} depending on the current OS.
*
* @param project
* the project
* @param script
* the script to run
*
* @return the created script step
*/
protected Builder addScriptStep(final FreeStyleProject project, final String script) {
Builder item;
if (Functions.isWindows()) {
item = new BatchFile(script);
}
else {
item = new Shell(script);
}
project.getBuildersList().add(item);
return item;
}
/**
* Cleans the workspace of the specified job. Deletes all files in the workspace.
*
* @param job
* the workspace to clean
*/
protected void cleanWorkspace(final TopLevelItem job) {
try {
getWorkspace(job).deleteContents();
}
catch (IOException | InterruptedException e) {
throw new AssertionError(e);
}
}
/**
* Add a build step that simply fails the build.
*
* @param project
* the job to add the step
*
* @return the created build step
*/
protected Builder addFailureStep(final FreeStyleProject project) {
return addScriptStep(project, "exit 1");
}
/**
* Removes the specified builder from the list of registered builders.
*
* @param project
* the job to add the step
* @param builder
* the builder to remove
*/
protected void removeBuilder(final FreeStyleProject project, final Builder builder) {
project.getBuildersList().remove(builder);
}
/**
* Joins the specified arguments as list of comma separated values. Note that the first element is separated with a
* comma as well.
* <blockquote>For example,
* <pre>{@code
* String message = join("Java", "is", "cool");
* // message returned is: ",Java,is,cool"
* }</pre></blockquote>
*
* @param arguments
* th arguments to join
*
* @return the concatenated string
*/
protected String join(final String... arguments) {
var builder = new StringBuilder();
for (String argument : arguments) {
builder.append(", ");
builder.append(argument);
}
return builder.toString();
}
/**
* Calls Jenkins remote API with the specified URL. Calls the JSON format.
*
* @param url
* the URL to call
*
* @return the JSON response
*/
protected JSONWebResponse callJsonRemoteApi(final String url) {
try {
return getJenkins().getJSON(url);
}
catch (IOException e) {
throw new AssertionError(e);
}
}
/**
* Calls Jenkins remote API with the specified URL. Calls the XML format.
*
* @param url
* the URL to call
*
* @return the XML response
*/
protected Document callXmlRemoteApi(final String url) {
try {
try (var webClient = getJenkins().createWebClient()) {
return webClient.goToXml(url).getXmlDocument();
}
}
catch (IOException | SAXException e) {
throw new AssertionError(e);
}
}
/**
* Docker container to be used as Jenkins build agent. Provides tools like make, gcc, java 11, or maven.
*/
public static final class AgentContainer extends GenericContainer<AgentContainer> {
/**
* Creates a new container that exposes port {@link #SSH_PORT} for SSH connections.
*/
public AgentContainer() {
super(new ImageFromDockerfile(DOCKER_AGENT_NAME, false)
.withFileFromClasspath("ssh/authorized_keys", "/ssh/authorized_keys")
.withFileFromClasspath("ssh/rsa-key", "/ssh/rsa_private_key")
.withFileFromClasspath("ssh/rsa-key.pub", "/ssh/rsa_public_key")
.withFileFromClasspath("ssh/sshd_config", "/ssh/sshd_config")
.withFileFromClasspath("Dockerfile", "/ssh/Dockerfile"));
setExposedPorts(Collections.singletonList(SSH_PORT));
}
}
}