-
Notifications
You must be signed in to change notification settings - Fork 130
/
JenkinsRule.java
3095 lines (2773 loc) · 121 KB
/
JenkinsRule.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
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt,
* Yahoo! Inc., Tom Huybrechts, Olivier Lamy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jvnet.hudson.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.jvnet.hudson.test.QueryUtils.waitUntilElementIsPresent;
import static org.jvnet.hudson.test.QueryUtils.waitUntilStringIsNotPresent;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.CloseProofOutputStream;
import hudson.DescriptorExtensionList;
import hudson.EnvVars;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Functions;
import hudson.Launcher;
import hudson.Main;
import hudson.PluginManager;
import hudson.Util;
import hudson.WebAppMain;
import hudson.console.AnnotatedLargeText;
import hudson.init.InitMilestone;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.DownloadService;
import hudson.model.Executor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.Result;
import hudson.model.RootAction;
import hudson.model.Run;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.UpdateSite;
import hudson.model.User;
import hudson.model.View;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.WorkUnit;
import hudson.remoting.Which;
import hudson.security.ACL;
import hudson.security.AbstractPasswordBasedSecurityRealm;
import hudson.security.GroupDetails;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerConnector;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.DumbSlave;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.tools.ToolProperty;
import hudson.util.PersistedList;
import hudson.util.ReflectionUtils;
import hudson.util.StreamTaskListener;
import hudson.util.jna.GNUCLibrary;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletRequest;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.lang.annotation.Annotation;
import java.lang.management.ThreadInfo;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.nio.channels.ClosedByInterruptException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.jar.Manifest;
import java.util.logging.ConsoleHandler;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsAdaptor;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.security.ApiTokenProperty;
import jenkins.security.MasterToSlaveCallable;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.FileUtils;
import org.eclipse.jetty.ee9.webapp.Configuration;
import org.eclipse.jetty.ee9.webapp.WebAppContext;
import org.eclipse.jetty.ee9.webapp.WebXmlConfiguration;
import org.eclipse.jetty.ee9.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.UriCompliance;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.UserStore;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.util.security.Password;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.htmlunit.AjaxController;
import org.htmlunit.BrowserVersion;
import org.htmlunit.DefaultCssErrorHandler;
import org.htmlunit.ElementNotFoundException;
import org.htmlunit.FailingHttpStatusCodeException;
import org.htmlunit.HttpMethod;
import org.htmlunit.Page;
import org.htmlunit.WebClientOptions;
import org.htmlunit.WebClientUtil;
import org.htmlunit.WebRequest;
import org.htmlunit.WebResponse;
import org.htmlunit.WebResponseData;
import org.htmlunit.WebResponseListener;
import org.htmlunit.corejs.javascript.Context;
import org.htmlunit.corejs.javascript.ContextFactory;
import org.htmlunit.cssparser.parser.CSSErrorHandler;
import org.htmlunit.cssparser.parser.CSSException;
import org.htmlunit.cssparser.parser.CSSParseException;
import org.htmlunit.html.DomNode;
import org.htmlunit.html.DomNodeUtil;
import org.htmlunit.html.HtmlAnchor;
import org.htmlunit.html.HtmlButton;
import org.htmlunit.html.HtmlElement;
import org.htmlunit.html.HtmlElementUtil;
import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlFormUtil;
import org.htmlunit.html.HtmlImage;
import org.htmlunit.html.HtmlInput;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.html.SubmittableElement;
import org.htmlunit.javascript.AbstractJavaScriptEngine;
import org.htmlunit.javascript.JavaScriptEngine;
import org.htmlunit.javascript.host.xml.XMLHttpRequest;
import org.htmlunit.util.NameValuePair;
import org.htmlunit.util.WebResponseWrapper;
import org.htmlunit.xml.XmlPage;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.MethodRule;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.junit.runner.Description;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestTimedOutException;
import org.jvnet.hudson.test.recipes.Recipe;
import org.jvnet.hudson.test.recipes.WithTimeout;
import org.jvnet.hudson.test.rhino.JavaScriptDebugger;
import org.kohsuke.stapler.ClassDescriptor;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.Dispatcher;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.MetaClassLoader;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.xml.sax.SAXException;
/**
* JUnit rule to allow test cases to fire up a Jenkins instance.
*
* @see <a href="https://www.jenkins.io/doc/developer/testing/">Wiki article about unit testing in Jenkins</a>
* @author Stephen Connolly
* @since 1.436
* @see RestartableJenkinsRule
*/
@SuppressWarnings({"deprecation", "rawtypes"})
public class JenkinsRule implements TestRule, MethodRule, RootAction {
protected TestEnvironment env;
protected Description testDescription;
/**
* Points to the same object as {@link #jenkins} does.
*/
@Deprecated
public Hudson hudson;
public Jenkins jenkins;
protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW;
/**
* TCP/IP port that the server is listening on.
*/
protected int localPort;
protected Server server;
/**
* Where in the {@link Server} is Jenkins deployed?
* <p>
* Just like {@link jakarta.servlet.ServletContext#getContextPath()}, starts with '/' but doesn't end with '/'.
* Unlike {@link WebClient#getContextPath} this is not a complete URL.
*/
public String contextPath = "/jenkins";
/**
* {@link Runnable}s to be invoked at {@link #after()} .
*/
protected List<LenientRunnable> tearDowns = new ArrayList<>();
protected List<JenkinsRecipe.Runner> recipes = new ArrayList<>();
/**
* Remember {@link WebClient}s that are created, to release them properly.
*/
private List<WebClient> clients = new ArrayList<>();
/**
* JavaScript "debugger" that provides you information about the JavaScript call stack
* and the current values of the local variables in those stack frame.
*
* <p>
* Unlike Java debugger, which you as a human interfaces directly and interactively,
* this JavaScript debugger is to be interfaced by your program (or through the
* expression evaluation capability of your Java debugger.)
*/
protected JavaScriptDebugger jsDebugger = new JavaScriptDebugger();
/**
* If this test case has additional {@link org.jvnet.hudson.test.recipes.WithPlugin} annotations, set to true.
* This will cause a fresh {@link hudson.PluginManager} to be created for this test.
* Leaving this to false enables the test harness to use a pre-loaded plugin manager,
* which runs faster.
*
* @deprecated
* Use {@link #pluginManager}
*/
@Deprecated
public boolean useLocalPluginManager;
/**
* Number of seconds until the test times out.
*
* The {@link WithTimeout} rule can be used to specify this value per test.
*
* In case of debugging session, the default timeout behavior is removed. Otherwise it's set to 3 minutes.
*/
public int timeout = Integer.getInteger("jenkins.test.timeout", new DisableOnDebug(null).isDebugging() ? 0 : 180);
/**
* Set the plugin manager to be passed to {@link Jenkins} constructor.
*
* For historical reasons, {@link #useLocalPluginManager}==true will take the precedence.
*/
private PluginManager pluginManager = TestPluginManager.INSTANCE;
public JenkinsComputerConnectorTester computerConnectorTester = new JenkinsComputerConnectorTester(this);
private boolean origDefaultUseCache = true;
public Jenkins getInstance() {
return jenkins;
}
/**
* Override to set up your specific external resource.
* @throws Throwable if setup fails (which will disable {@code after}
*/
public void before() throws Throwable {
for (Handler h : Logger.getLogger("").getHandlers()) {
if (h instanceof ConsoleHandler) {
h.setFormatter(new DeltaSupportLogFormatter());
}
}
if (Thread.interrupted()) { // JENKINS-30395
LOGGER.warning("was interrupted before start");
}
if(Functions.isWindows()) {
// JENKINS-4409.
// URLConnection caches handles to jar files by default,
// and it prevents delete temporary directories on Windows.
// Disables caching here.
// Though defaultUseCache is a static field,
// its setter and getter are provided as instance methods.
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
origDefaultUseCache = aConnection.getDefaultUseCaches();
aConnection.setDefaultUseCaches(false);
}
// Not ideal (https://github.com/junit-team/junit/issues/116) but basically works.
if (Boolean.getBoolean("ignore.random.failures")) {
RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
if (rf != null) {
throw new AssumptionViolatedException("Known to randomly fail: " + rf.value());
}
}
env = new TestEnvironment(testDescription);
env.pin();
recipe();
AbstractProject.WORKSPACE.toString();
User.clear();
try {
Field theInstance = Jenkins.class.getDeclaredField("theInstance");
theInstance.setAccessible(true);
if (theInstance.get(null) != null) {
LOGGER.warning("Jenkins.theInstance was not cleared by a previous test, doing that now");
theInstance.set(null, null);
}
} catch (Exception x) {
LOGGER.log(Level.WARNING, null, x);
}
try {
jenkins = hudson = newHudson();
// If the initialization graph is corrupted, we cannot expect that Jenkins is in the good shape.
// Likely it is an issue in @Initializer() definitions (see JENKINS-37759).
// So we just fail the test.
if (jenkins.getInitLevel() != InitMilestone.COMPLETED) {
throw new Exception("Jenkins initialization has not reached the COMPLETED initialization stage. Current state is " + jenkins.getInitLevel() +
". Likely there is an issue with the Initialization task graph (e.g. usage of @Initializer(after = InitMilestone.COMPLETED)). See JENKINS-37759 for more info");
}
} catch (Exception e) {
// if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up.
Field f = Jenkins.class.getDeclaredField("theInstance");
f.setAccessible(true);
f.set(null,null);
throw e;
}
jenkins.setCrumbIssuer(new TestCrumbIssuer()); // TODO: Move to _configureJenkinsForTest after JENKINS-55240
_configureJenkinsForTest(jenkins);
configureUpdateCenter();
// expose the test instance as a part of URL tree.
// this allows tests to use a part of the URL space for itself.
jenkins.getActions().add(this);
JenkinsLocationConfiguration.get().setUrl(getURL().toString());
}
/**
* Configures a Jenkins instance for test.
*
* @param jenkins jenkins instance which has to be configured
* @throws Exception if unable to configure
* @since 2.50
*/
public static void _configureJenkinsForTest(Jenkins jenkins) throws Exception {
jenkins.setNoUsageStatistics(true); // collecting usage stats from tests is pointless.
jenkins.getServletContext().setAttribute("app", jenkins);
jenkins.getServletContext().setAttribute("version", "?");
WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.getServletContext()));
// set a default JDK to be the one that the harness is using.
jenkins.getJDKs().add(new JDK("default", System.getProperty("java.home")));
}
static void dumpThreads() {
ThreadInfo[] threadInfos = Functions.getThreadInfos();
Functions.ThreadGroupMap m = Functions.sortThreadsAndGetGroupMap(threadInfos);
for (ThreadInfo ti : threadInfos) {
System.err.println(Functions.dumpThreadInfo(ti, m));
}
}
/**
* Configures the update center setting for the test.
* By default, we load updates from local proxy to avoid network traffic as much as possible.
*/
protected void configureUpdateCenter() throws Exception {
_configureUpdateCenter(jenkins);
}
/**
* Internal method used to configure update center to avoid network traffic.
* @param jenkins the Jenkins to configure
* @since 2.50
*/
public static void _configureUpdateCenter(Jenkins jenkins) throws Exception {
final String updateCenterUrl;
jettyLevel(Level.WARNING);
try {
updateCenterUrl =
"http://localhost:" + JavaNetReverseProxy2.getInstance().localPort + "/update-center.json";
} finally {
jettyLevel(Level.INFO);
}
// don't waste bandwidth talking to the update center
DownloadService.neverUpdate = true;
UpdateSite.neverUpdate = true;
PersistedList<UpdateSite> sites = jenkins.getUpdateCenter().getSites();
sites.clear();
sites.add(new UpdateSite("default", updateCenterUrl));
}
/**
* Override to tear down your specific external resource.
*/
public void after() throws Exception {
try {
if (jenkins!=null) {
for (EndOfTestListener tl : jenkins.getExtensionList(EndOfTestListener.class)) {
tl.onTearDown();
}
}
// cancel asynchronous operations as best as we can
for (WebClient client : clients) {
// Adapt to https://github.com/HtmlUnit/htmlunit/issues/627
// See https://github.com/jenkinsci/jenkins-test-harness/pull/664
if (client.getJavaScriptEngine() != null) {
// wait until current asynchronous operations have finished executing
WebClientUtil.waitForJSExec(client);
}
// unload the page to prevent new asynchronous operations from being scheduled
try (client) {
// Adapt to https://github.com/HtmlUnit/htmlunit/issues/627
// See https://github.com/jenkinsci/jenkins-test-harness/pull/664
if (client.getCurrentWindow() != null) {
client.getPage("about:blank");
}
} catch (IOException e) {
// should never happen when loading "about:blank"
throw new UncheckedIOException(e);
}
}
clients.clear();
} finally {
_stopJenkins(server, tearDowns, jenkins);
// Jenkins creates ClassLoaders for plugins that hold on to file descriptors of its jar files,
// but because there's no explicit dispose method on ClassLoader, they won't get GC-ed until
// at some later point, leading to possible file descriptor overflow. So encourage GC now.
// see https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4950148
// TODO use URLClassLoader.close() in Java 7
System.gc();
try (var ignored = new SetConsoleLogger("hudson.XmlFile", Level.FINEST)) {
env.dispose();
} finally {
// restore defaultUseCache
if(Functions.isWindows()) {
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
aConnection.setDefaultUseCaches(origDefaultUseCache);
}
}
}
}
/**
* Internal method to stop Jenkins instance.
*
* @param server server on which Jenkins is running.
* @param tearDowns tear down methods for tests
* @param jenkins the jenkins instance
* @since 2.50
*/
public static void _stopJenkins(Server server, List<LenientRunnable> tearDowns, Jenkins jenkins) {
final RuntimeException exception = new RuntimeException("One or more problems while shutting down Jenkins");
jettyLevel(Level.WARNING);
try {
server.stop();
} catch (Exception e) {
exception.addSuppressed(e);
} finally {
jettyLevel(Level.INFO);
}
if (tearDowns != null) {
for (LenientRunnable r : tearDowns) {
try {
r.run();
} catch (Exception e) {
exception.addSuppressed(e);
}
}
}
if (jenkins != null) {
jenkins.cleanUp();
}
ExtensionList.clearLegacyInstances();
DescriptorExtensionList.clearLegacyInstances();
if (exception.getSuppressed().length > 0) {
throw exception;
}
}
/**
* Sets the given logger to the given level and applies it to the console handler,
* then returns an {@link AutoCloseable} that will restore the prior level.
*/
private static final class SetConsoleLogger implements AutoCloseable {
private final Handler handler;
private final Level priorHandlerLevel;
private final Logger logger;
private final Level priorLoggerLevel;
public SetConsoleLogger(@NonNull String loggerName, @NonNull Level level) {
logger = Logger.getLogger(loggerName);
priorLoggerLevel = logger.getLevel();
if (priorLoggerLevel == null || level.intValue() < priorLoggerLevel.intValue()) {
logger.setLevel(level);
}
handler = Arrays.stream(Logger.getLogger("").getHandlers()).filter(ConsoleHandler.class::isInstance).findFirst().orElse(null);
if (handler != null) {
priorHandlerLevel = handler.getLevel();
if (priorHandlerLevel == null || level.intValue() < priorHandlerLevel.intValue()) {
handler.setLevel(level);
}
} else {
priorHandlerLevel = null;
}
}
@Override
public void close() {
logger.setLevel(priorLoggerLevel);
if (handler != null) {
handler.setLevel(priorHandlerLevel);
}
}
}
private static void jettyLevel(Level level) {
Logger.getLogger("org.eclipse.jetty").setLevel(level);
}
/**
* Backward compatibility with JUnit 4.8.
*/
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return apply(base,Description.createTestDescription(method.getMethod().getDeclaringClass(), method.getName(), method.getAnnotations()));
}
@Override
public Statement apply(final Statement base, final Description description) {
if (description.getAnnotation(WithoutJenkins.class) != null) {
// request has been made to not create the instance for this test method
return base;
}
Statement wrapped = new Statement() {
@Override
public void evaluate() throws Throwable {
testDescription = description;
Thread t = Thread.currentThread();
String o = t.getName();
t.setName("Executing "+ testDescription.getDisplayName());
System.out.println("=== Starting " + testDescription.getDisplayName());
before();
Throwable testFailure = null;
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
try {
base.evaluate();
} catch (Throwable th) {
testFailure = th;
// allow the late attachment of a debugger in case of a failure. Useful
// for diagnosing a rare failure
try {
throw new BreakException();
} catch (BreakException e) {}
RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
if (rf != null) {
System.err.println("Note: known to randomly fail: " + rf.value());
}
throw th;
}
} finally {
try {
after();
} catch (Exception e) {
if (testFailure != null) {
// Exceptions thrown by the test itself are more important than those thrown during cleanup.
testFailure.addSuppressed(e);
throw testFailure;
} else {
throw e;
}
} finally {
testDescription = null;
t.setName(o);
}
}
}
};
final int testTimeout = getTestTimeoutOverride(description);
if (testTimeout <= 0) {
System.out.println("Test timeout disabled.");
return wrapped;
} else {
final Statement timeoutStatement = Timeout.seconds(testTimeout).apply(wrapped, description);
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
timeoutStatement.evaluate();
} catch (TestTimedOutException x) {
// withLookingForStuckThread does not work well; better to just have a full thread dump.
LOGGER.warning(String.format("Test timed out (after %d seconds).", testTimeout));
dumpThreads();
throw x;
}
}
};
}
}
private int getTestTimeoutOverride(Description description) {
WithTimeout withTimeout = description.getAnnotation(WithTimeout.class);
return withTimeout != null ? withTimeout.value(): this.timeout;
}
@SuppressWarnings("serial")
public static class BreakException extends Exception {}
@Override
public String getIconFileName() {
return null;
}
@Override
public String getDisplayName() {
return null;
}
@Override
public String getUrlName() {
return "self";
}
/**
* Creates a new instance of {@link jenkins.model.Jenkins}. If the derived class wants to create it in a different way,
* you can override it.
*/
protected Hudson newHudson() throws Exception {
jettyLevel(Level.WARNING);
ServletContext webServer = createWebServer2();
File home = homeLoader.allocate();
for (JenkinsRecipe.Runner r : recipes) {
r.decorateHome(this, home);
}
try {
return new Hudson(home, webServer, getPluginManager());
} catch (InterruptedException e) {
throw new AssumptionViolatedException("Jenkins startup interrupted", e);
} finally {
jettyLevel(Level.INFO);
}
}
public PluginManager getPluginManager() {
if (jenkins == null) {
return useLocalPluginManager ? null : pluginManager;
} else {
return jenkins.getPluginManager();
}
}
/**
* Sets the {@link PluginManager} to be used when creating a new {@link Jenkins} instance.
*
* @param pluginManager
* null to let Jenkins create a new instance of default plugin manager, like it normally does when running as a webapp outside the test.
*/
public void setPluginManager(PluginManager pluginManager) {
this.useLocalPluginManager = false;
this.pluginManager = pluginManager;
if (jenkins != null) {
throw new IllegalStateException("Too late to override the plugin manager");
}
}
public JenkinsRule with(PluginManager pluginManager) {
setPluginManager(pluginManager);
return this;
}
public File getWebAppRoot() throws Exception {
return WarExploder.getExplodedDir();
}
/**
* Prepares a webapp hosting environment to get {@link jakarta.servlet.ServletContext} implementation
* that we need for testing.
*/
protected ServletContext createWebServer2() throws Exception {
return createWebServer2(null);
}
/**
* Prepares a webapp hosting environment to get {@link jakarta.servlet.ServletContext} implementation
* that we need for testing.
*
* @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
* @since 2.63
*/
protected ServletContext createWebServer2(@CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
throws Exception {
WebAppContext context = _createWebAppContext2(
contextPath,
(x) -> localPort = x,
getClass().getClassLoader(),
localPort,
this::configureUserRealm,
contextAndServerConsumer);
server = context.getServer();
LOGGER.log(Level.INFO, "Running on {0}", getURL());
return context.getServletContext();
}
/**
* Creates a web server on which Jenkins can run
*
* @param contextPath the context path at which to put Jenkins
* @param portSetter the port on which the server runs will be set using this function
* @param classLoader the class loader for the {@link WebAppContext}
* @param localPort port on which the server runs
* @param loginServiceSupplier configures the {@link LoginService} for the instance
* @return the {@link Server}
* @since 2.50
*/
public static WebAppContext _createWebAppContext2(
String contextPath,
Consumer<Integer> portSetter,
ClassLoader classLoader,
int localPort,
Supplier<LoginService> loginServiceSupplier)
throws Exception {
return _createWebAppContext2(contextPath, portSetter, classLoader, localPort, loginServiceSupplier, null);
}
/**
* Creates a web server on which Jenkins can run
*
* @param contextPath the context path at which to put Jenkins
* @param portSetter the port on which the server runs will be set using this function
* @param classLoader the class loader for the {@link WebAppContext}
* @param localPort port on which the server runs
* @param loginServiceSupplier configures the {@link LoginService} for the instance
* @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
* @return the {@link Server}
* @since 2.50
*/
public static WebAppContext _createWebAppContext2(
String contextPath,
Consumer<Integer> portSetter,
ClassLoader classLoader,
int localPort,
Supplier<LoginService> loginServiceSupplier,
@CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
throws Exception {
QueuedThreadPool qtp = new QueuedThreadPool();
qtp.setName("Jetty (JenkinsRule)");
Server server = new Server(qtp);
WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath) {
@Override
protected ClassLoader configureClassLoader(ClassLoader loader) {
// Use flat classpath in tests
return loader;
}
};
context.setClassLoader(classLoader);
context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
context.addBean(new NoListenerConfiguration2(context));
context.setServer(server);
String compression = System.getProperty("jth.compression", "gzip");
if (compression.equals("gzip")) {
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setHandler(context);
server.setHandler(gzipHandler);
} else if (compression.equals("none")) {
server.setHandler(context);
} else {
throw new IllegalArgumentException("Unexpected compression scheme: " + compression);
}
JettyWebSocketServletContainerInitializer.configure(context, null);
context.getSecurityHandler().setLoginService(loginServiceSupplier.get());
context.setResourceBase(WarExploder.getExplodedDir().getPath());
ServerConnector connector = new ServerConnector(server);
HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
// use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
config.setRequestHeaderSize(12 * 1024);
config.setHttpCompliance(HttpCompliance.RFC7230);
config.setUriCompliance(UriCompliance.LEGACY);
connector.setHost("localhost");
if (System.getProperty("port") != null) {
connector.setPort(Integer.parseInt(System.getProperty("port")));
} else if (localPort != 0) {
connector.setPort(localPort);
}
server.addConnector(connector);
if (contextAndServerConsumer != null) {
contextAndServerConsumer.accept(context, server);
}
server.start();
portSetter.accept(connector.getLocalPort());
return context;
}
/**
* Configures a security realm for a test.
*/
protected LoginService configureUserRealm() {
return _configureUserRealm();
}
/**
* Creates a {@link HashLoginService} with three users: alice, bob and charlie
*
* The password is same as the username
* @return a new login service
* @since 2.50
*/
public static LoginService _configureUserRealm() {
HashLoginService realm = new HashLoginService();
realm.setName("default"); // this is the magic realm name to make it effective on everywhere
UserStore userStore = new UserStore();
realm.setUserStore( userStore );
userStore.addUser("alice", new Password("alice"), new String[]{"user","female"});
userStore.addUser("bob", new Password("bob"), new String[]{"user","male"});
userStore.addUser("charlie", new Password("charlie"), new String[]{"user","male"});
return realm;
}
//
// Convenience methods
//
/**
* Creates a new job.
*
* @param type Top level item type.
* @param name Item name.
*
* @throws IllegalArgumentException if the project of the given name already exists.
*/
public <T extends TopLevelItem> T createProject(Class<T> type, String name) throws IOException {
return jenkins.createProject(type, name);
}
/**
* Creates a new job with an unique name.
*
* @param type Top level item type.
*/
public <T extends TopLevelItem> T createProject(Class<T> type) throws IOException {
return jenkins.createProject(type, createUniqueProjectName());
}
public FreeStyleProject createFreeStyleProject() throws IOException {
return createFreeStyleProject(createUniqueProjectName());
}
public FreeStyleProject createFreeStyleProject(String name) throws IOException {
return createProject(FreeStyleProject.class, name);
}
/**
* Creates a simple folder that other jobs can be placed in.
* @since 1.494
*/
public MockFolder createFolder(String name) throws IOException {
return createProject(MockFolder.class, name);
}
protected String createUniqueProjectName() {
return "test"+jenkins.getItems().size();
}
/**
* Creates {@link hudson.Launcher.LocalLauncher}. Useful for launching processes.
*/
public Launcher.LocalLauncher createLocalLauncher() {
return new Launcher.LocalLauncher(StreamTaskListener.fromStdout());
}
/**
* Allocates a new temporary directory for the duration of this test.
* @deprecated Use {@link TemporaryFolder} instead.
*/
@Deprecated
public File createTmpDir() throws IOException {
return env.temporaryDirectoryAllocator.allocate();
}
@NonNull
public DumbSlave createSlave(boolean waitForChannelConnect) throws Exception {
DumbSlave slave = createSlave();
if (waitForChannelConnect) {