-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathHudsonTestCase.java
1820 lines (1585 loc) · 69.4 KB
/
HudsonTestCase.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-2011, 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 com.gargoylesoftware.css.parser.CSSErrorHandler;
import com.gargoylesoftware.css.parser.CSSException;
import com.gargoylesoftware.css.parser.CSSParseException;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.WebClientUtil;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlFormUtil;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.javascript.AbstractJavaScriptEngine;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
import com.google.inject.Injector;
import hudson.ClassicPluginStrategy;
import hudson.CloseProofOutputStream;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.EnvVars;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Functions;
import hudson.Functions.ThreadGroupMap;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.Main;
import hudson.PluginManager;
import hudson.Util;
import hudson.WebAppMain;
import hudson.model.*;
import hudson.model.Executor;
import hudson.model.Node.Mode;
import hudson.model.Queue.Executable;
import hudson.os.PosixAPI;
import hudson.security.ACL;
import hudson.security.AbstractPasswordBasedSecurityRealm;
import hudson.security.GroupDetails;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.ComputerConnector;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
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 java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
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.Method;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsAdaptor;
import junit.framework.TestCase;
import net.sf.json.JSONObject;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextFactory;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.beanutils.PropertyUtils;
import org.eclipse.jetty.http.MimeTypes;
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.util.security.Password;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting;
import org.jvnet.hudson.test.recipes.Recipe;
import org.jvnet.hudson.test.recipes.Recipe.Runner;
import org.jvnet.hudson.test.recipes.WithPlugin;
import org.jvnet.hudson.test.rhino.JavaScriptDebugger;
import org.kohsuke.stapler.ClassDescriptor;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.Dispatcher;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.MetaClassLoader;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.mozilla.javascript.tools.debugger.Dim;
import org.mozilla.javascript.tools.shell.Global;
import org.springframework.dao.DataAccessException;
import org.xml.sax.SAXException;
import com.gargoylesoftware.htmlunit.AjaxController;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.DefaultCssErrorHandler;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory;
import com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import java.net.HttpURLConnection;
import jenkins.model.JenkinsLocationConfiguration;
/**
* Base class for all Jenkins test cases.
*
* @see <a href="http://wiki.jenkins-ci.org/display/JENKINS/Unit+Test">Wiki article about unit testing in Hudson</a>
* @author Kohsuke Kawaguchi
* @deprecated New code should use {@link JenkinsRule}.
*/
@Deprecated
@SuppressWarnings("rawtypes")
public abstract class HudsonTestCase extends TestCase implements RootAction {
/**
* Points to the same object as {@link #jenkins} does.
*/
public Hudson hudson;
public Jenkins jenkins;
protected final TestEnvironment env = new TestEnvironment(this);
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 Hudson deployed?
* <p>
* Just like {@link ServletContext#getContextPath()}, starts with '/' but doesn't end with '/'.
*/
protected String contextPath = "";
/**
* {@link Runnable}s to be invoked at {@link #tearDown()}.
*/
protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>();
protected List<Runner> recipes = new ArrayList<Runner>();
/**
* Remember {@link WebClient}s that are created, to release them properly.
*/
private List<WebClient> clients = new ArrayList<WebClient>();
/**
* 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 WithPlugin} annotations, set to true.
* This will cause a fresh {@link 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}
*/
public boolean useLocalPluginManager;
/**
* Number of seconds until the test times out.
*/
public int timeout = Integer.getInteger("jenkins.test.timeout", 180);
private volatile Timer timeoutTimer;
/**
* 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 ComputerConnectorTester computerConnectorTester = new ComputerConnectorTester(this);
/**
* The directory where a war file gets exploded.
*/
protected File explodedWarDir;
private boolean origDefaultUseCache = true;
protected HudsonTestCase(String name) {
super(name);
}
protected HudsonTestCase() {
}
@Override
public void runBare() throws Throwable {
// override the thread name to make the thread dump more useful.
Thread t = Thread.currentThread();
String o = getClass().getName()+'.'+t.getName();
t.setName("Executing "+getName());
try {
super.runBare();
} finally {
t.setName(o);
}
}
@Override
protected void setUp() throws Exception {
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);
}
env.pin();
recipe();
for (Runner r : recipes) {
if (r instanceof WithoutJenkins.RunnerImpl)
return; // no setup
}
AbstractProject.WORKSPACE.toString();
User.clear();
// just in case tearDown failed in the middle, make sure to really clean them up so that there's no left-over from earlier tests
ExtensionList.clearLegacyInstances();
DescriptorExtensionList.clearLegacyInstances();
try {
jenkins = hudson = newHudson();
} catch (Exception e) {
// if Jenkins 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.setNoUsageStatistics(true); // collecting usage stats from tests are pointless.
jenkins.setCrumbIssuer(new TestCrumbIssuer());
jenkins.servletContext.setAttribute("app", jenkins);
jenkins.servletContext.setAttribute("version","?");
WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext));
JenkinsLocationConfiguration.get().setUrl(getURL().toString());
// set a default JDK to be the one that the harness is using.
jenkins.getJDKs().add(new JDK("default",System.getProperty("java.home")));
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);
// cause all the descriptors to reload.
// ideally we'd like to reset them to properly emulate the behavior, but that's not possible.
for( Descriptor d : jenkins.getExtensionList(Descriptor.class) )
d.load();
// allow the test class to inject Jenkins components
jenkins.lookup(Injector.class).injectMembers(this);
setUpTimeout();
}
protected void setUpTimeout() {
if (timeout<=0) return; // no timeout
final Thread testThread = Thread.currentThread();
timeoutTimer = new Timer();
timeoutTimer.schedule(new TimerTask() {
@Override
public void run() {
if (timeoutTimer!=null) {
LOGGER.warning(String.format("Test timed out (after %d seconds).", timeout));
testThread.interrupt();
}
}
}, TimeUnit.SECONDS.toMillis(timeout));
}
/**
* 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 {
final String updateCenterUrl = "http://localhost:"+ JavaNetReverseProxy.getInstance().localPort+"/update-center.json";
// 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
protected void tearDown() throws Exception {
try {
if (jenkins!=null) {
for (EndOfTestListener tl : jenkins.getExtensionList(EndOfTestListener.class))
tl.onTearDown();
}
if (timeoutTimer!=null) {
timeoutTimer.cancel();
timeoutTimer = null;
}
// cancel pending asynchronous operations, although this doesn't really seem to be working
for (WebClient client : clients) {
// unload the page to cancel asynchronous operations
client.getPage("about:blank");
client.close();
}
clients.clear();
} finally {
if (server!=null)
server.stop();
for (LenientRunnable r : tearDowns)
r.run();
if (jenkins!=null)
jenkins.cleanUp();
ExtensionList.clearLegacyInstances();
DescriptorExtensionList.clearLegacyInstances();
try {
env.dispose();
} catch (Exception x) {
x.printStackTrace();
}
// 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 http://bugs.sun.com/view_bug.do?bug_id=4950148
System.gc();
// restore defaultUseCache
if(Functions.isWindows()) {
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
aConnection.setDefaultUseCaches(origDefaultUseCache);
}
}
}
@Override
protected void runTest() throws Throwable {
System.out.println("=== Starting "+ getClass().getSimpleName() + "." + getName());
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
try {
super.runTest();
} catch (Throwable t) {
// 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) {}
// dump threads
ThreadInfo[] threadInfos = Functions.getThreadInfos();
ThreadGroupMap m = Functions.sortThreadsAndGetGroupMap(threadInfos);
for (ThreadInfo ti : threadInfos) {
System.err.println(Functions.dumpThreadInfo(ti, m));
}
throw t;
}
}
@SuppressWarnings("serial")
public static class BreakException extends Exception {}
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
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 {
File home = homeLoader.allocate();
for (Runner r : recipes)
r.decorateHome(this,home);
return new Hudson(home, createWebServer(), useLocalPluginManager ? null : pluginManager);
}
/**
* 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");
}
/**
* Prepares a webapp hosting environment to get {@link ServletContext} implementation
* that we need for testing.
*/
protected ServletContext createWebServer() throws Exception {
server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("Jetty Thread Pool");
return t;
}
})));
explodedWarDir = WarExploder.getExplodedDir();
WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
context.setResourceBase(explodedWarDir.getPath());
context.setClassLoader(getClass().getClassLoader());
context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
context.addBean(new NoListenerConfiguration(context));
server.setHandler(context);
context.setMimeTypes(MIME_TYPES);
context.getSecurityHandler().setLoginService(configureUserRealm());
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);
connector.setHost("localhost");
server.addConnector(connector);
server.start();
localPort = connector.getLocalPort();
return context.getServletContext();
}
/**
* Configures a security realm for a test.
*/
protected 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
//
protected FreeStyleProject createFreeStyleProject() throws IOException {
return createFreeStyleProject(createUniqueProjectName());
}
protected FreeStyleProject createFreeStyleProject(String name) throws IOException {
return jenkins.createProject(FreeStyleProject.class, name);
}
protected String createUniqueProjectName() {
return "test"+ jenkins.getItems().size();
}
/**
* Creates {@link LocalLauncher}. Useful for launching processes.
*/
protected LocalLauncher createLocalLauncher() {
return new LocalLauncher(StreamTaskListener.fromStdout());
}
/**
* Allocates a new temporary directory for the duration of this test.
*/
public File createTmpDir() throws IOException {
return env.temporaryDirectoryAllocator.allocate();
}
public DumbSlave createSlave() throws Exception {
return createSlave("",null);
}
/**
* Creates and launches a new slave on the local host.
*/
public DumbSlave createSlave(Label l) throws Exception {
return createSlave(l, null);
}
/**
* Creates a test {@link SecurityRealm} that recognizes username==password as valid.
*/
public SecurityRealm createDummySecurityRealm() {
return new AbstractPasswordBasedSecurityRealm() {
@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
if (username.equals(password))
return loadUserByUsername(username);
throw new BadCredentialsException(username);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
return new org.acegisecurity.userdetails.User(username,"",true,true,true,true,new GrantedAuthority[]{AUTHENTICATED_AUTHORITY});
}
@Override
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException(groupname);
}
};
}
/**
* Returns the URL of the webapp top page.
* URL ends with '/'.
*/
public URL getURL() throws IOException {
return new URL("http://localhost:"+localPort+contextPath+"/");
}
public DumbSlave createSlave(EnvVars env) throws Exception {
return createSlave("",env);
}
public DumbSlave createSlave(Label l, EnvVars env) throws Exception {
return createSlave(l==null ? null : l.getExpression(), env);
}
/**
* Creates a slave with certain additional environment variables
*/
public DumbSlave createSlave(String labels, EnvVars env) throws Exception {
synchronized (jenkins) {
int sz = jenkins.getNodes().size();
return createSlave("slave" + sz,labels,env);
}
}
public DumbSlave createSlave(String nodeName, String labels, EnvVars env) throws Exception {
synchronized (jenkins) {
DumbSlave slave = new DumbSlave(nodeName, "dummy",
createTmpDir().getPath(), "1", Mode.NORMAL, labels==null?"":labels, createComputerLauncher(env),
RetentionStrategy.NOOP, Collections.emptyList());
jenkins.addNode(slave);
return slave;
}
}
public PretendSlave createPretendSlave(FakeLauncher faker) throws Exception {
synchronized (jenkins) {
int sz = jenkins.getNodes().size();
PretendSlave slave = new PretendSlave("slave" + sz, createTmpDir().getPath(), "", createComputerLauncher(null), faker);
jenkins.addNode(slave);
return slave;
}
}
/**
* Creates a {@link ComputerLauncher} for launching a slave locally.
*
* @param env
* Environment variables to add to the slave process. Can be null.
*/
public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
int sz = jenkins.getNodes().size();
return new SimpleCommandLauncher(
String.format("\"%s/bin/java\" %s %s -jar \"%s\"",
System.getProperty("java.home"),
SLAVE_DEBUG_PORT>0 ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="+(SLAVE_DEBUG_PORT+sz): "",
"-Djava.awt.headless=true",
new File(jenkins.getJnlpJars("slave.jar").getURL().toURI()).getAbsolutePath()),
env);
}
/**
* Create a new slave on the local host and wait for it to come online
* before returning.
*/
public DumbSlave createOnlineSlave() throws Exception {
return createOnlineSlave(null);
}
/**
* Create a new slave on the local host and wait for it to come online
* before returning.
*/
public DumbSlave createOnlineSlave(Label l) throws Exception {
return createOnlineSlave(l, null);
}
/**
* Create a new slave on the local host and wait for it to come online
* before returning
*/
@SuppressWarnings("deprecation")
public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
ComputerListener waiter = new ComputerListener() {
@Override
public void onOnline(Computer C, TaskListener t) {
latch.countDown();
unregister();
}
};
waiter.register();
DumbSlave s = createSlave(l, env);
latch.await();
return s;
}
/**
* Blocks until the ENTER key is hit.
* This is useful during debugging a test so that one can inspect the state of Jenkins through the web browser.
*/
public void interactiveBreak() throws Exception {
System.out.println("Jenkins is running at http://localhost:"+localPort+"/");
new BufferedReader(new InputStreamReader(System.in)).readLine();
}
/**
* Returns the last item in the list.
*/
protected <T> T last(List<T> items) {
return items.get(items.size()-1);
}
/**
* Pauses the execution until ENTER is hit in the console.
* <p>
* This is often very useful so that you can interact with Hudson
* from an browser, while developing a test case.
*/
protected void pause() throws IOException {
new BufferedReader(new InputStreamReader(System.in)).readLine();
}
/**
* Performs a search from the search box.
*/
protected Page search(String q) throws Exception {
return new WebClient().search(q);
}
/**
* Hits the Hudson system configuration and submits without any modification.
*/
protected void configRoundtrip() throws Exception {
submit(createWebClient().goTo("configure").getFormByName("config"));
}
/**
* Loads a configuration page and submits it without any modifications, to
* perform a round-trip configuration test.
* <p>
* See http://wiki.jenkins-ci.org/display/JENKINS/Unit+Test#UnitTest-Configurationroundtriptesting
*/
protected <P extends Job> P configRoundtrip(P job) throws Exception {
submit(createWebClient().getPage(job,"configure").getFormByName("config"));
return job;
}
protected <P extends Item> P configRoundtrip(P job) throws Exception {
submit(createWebClient().getPage(job, "configure").getFormByName("config"));
return job;
}
/**
* Performs a configuration round-trip testing for a builder.
*/
@SuppressWarnings("unchecked")
protected <B extends Builder> B configRoundtrip(B before) throws Exception {
FreeStyleProject p = createFreeStyleProject();
p.getBuildersList().add(before);
configRoundtrip((Item)p);
return (B)p.getBuildersList().get(before.getClass());
}
/**
* Performs a configuration round-trip testing for a publisher.
*/
@SuppressWarnings("unchecked")
protected <P extends Publisher> P configRoundtrip(P before) throws Exception {
FreeStyleProject p = createFreeStyleProject();
p.getPublishersList().add(before);
configRoundtrip((Item) p);
return (P)p.getPublishersList().get(before.getClass());
}
@SuppressWarnings("unchecked")
protected <C extends ComputerConnector> C configRoundtrip(C before) throws Exception {
computerConnectorTester.connector = before;
submit(createWebClient().goTo("self/computerConnectorTester/configure").getFormByName("config"));
return (C)computerConnectorTester.connector;
}
protected User configRoundtrip(User u) throws Exception {
submit(createWebClient().goTo(u.getUrl()+"/configure").getFormByName("config"));
return u;
}
@SuppressWarnings("unchecked")
protected <N extends Node> N configRoundtrip(N node) throws Exception {
submit(createWebClient().goTo("/computer/" + node.getNodeName() + "/configure").getFormByName("config"));
return (N) jenkins.getNode(node.getNodeName());
}
protected <V extends View> V configRoundtrip(V view) throws Exception {
submit(createWebClient().getPage(view, "configure").getFormByName("viewConfig"));
return view;
}
/**
* Asserts that the outcome of the build is a specific outcome.
*/
public <R extends Run> R assertBuildStatus(Result status, R r) throws Exception {
if(status==r.getResult())
return r;
// dump the build output in failure message
String msg = "unexpected build status; build log was:\n------\n" + getLog(r) + "\n------\n";
assertEquals(msg, status,r.getResult());
return r;
}
/** Determines whether the specified HTTP status code is generally "good" */
public boolean isGoodHttpStatus(int status) {
if ((400 <= status) && (status <= 417)) {
return false;
}
if ((500 <= status) && (status <= 505)) {
return false;
}
return true;
}
/** Assert that the specified page can be served with a "good" HTTP status,
* eg, the page is not missing and can be served without a server error
* @param page
*/
public void assertGoodStatus(Page page) {
assertTrue(isGoodHttpStatus(page.getWebResponse().getStatusCode()));
}
public <R extends Run> R assertBuildStatusSuccess(R r) throws Exception {
assertBuildStatus(Result.SUCCESS, r);
return r;
}
public <R extends Run> R assertBuildStatusSuccess(Future<? extends R> r) throws Exception {
assertNotNull("build was actually scheduled", r);
return assertBuildStatusSuccess(r.get());
}
public <J extends AbstractProject<J,R>,R extends AbstractBuild<J,R>> R buildAndAssertSuccess(J job) throws Exception {
return assertBuildStatusSuccess(job.scheduleBuild2(0));
}
/**
* Avoids need for cumbersome {@code this.<J,R>buildAndAssertSuccess(...)} type hints under JDK 7 javac (and supposedly also IntelliJ).
*/
public FreeStyleBuild buildAndAssertSuccess(FreeStyleProject job) throws Exception {
return assertBuildStatusSuccess(job.scheduleBuild2(0));
}
/**
* Asserts that the console output of the build contains the given substring.
*/
public void assertLogContains(String substring, Run run) throws Exception {
String log = getLog(run);
assertTrue("Console output of "+run+" didn't contain "+substring+":\n"+log,log.contains(substring));
}
/**
* Asserts that the console output of the build does not contain the given substring.
*/
public void assertLogNotContains(String substring, Run run) throws Exception {
String log = getLog(run);
assertFalse("Console output of "+run+" contains "+substring+":\n"+log,log.contains(substring));
}
/**
* Get entire log file (this method is deprecated in hudson.model.Run,
* but in tests it is OK to load entire log).
*/
protected static String getLog(Run run) throws IOException {
return Util.loadFile(run.getLogFile(), run.getCharset());
}
/**
* Asserts that the XPath matches.
*/
public void assertXPath(HtmlPage page, String xpath) {
assertNotNull("There should be an object that matches XPath:" + xpath,
DomNodeUtil.selectSingleNode(page.getDocumentElement(), xpath));
}
/** Asserts that the XPath matches the contents of a DomNode page. This
* variant of assertXPath(HtmlPage page, String xpath) allows us to
* examine XmlPages.
* @param page
* @param xpath
*/
public void assertXPath(DomNode page, String xpath) {
List< ? extends Object> nodes = page.getByXPath(xpath);
assertFalse("There should be an object that matches XPath:" + xpath, nodes.isEmpty());
}
public void assertXPathValue(DomNode page, String xpath, String expectedValue) {
Object node = page.getFirstByXPath(xpath);
assertNotNull("no node found", node);
assertTrue("the found object was not a Node " + xpath, node instanceof org.w3c.dom.Node);
org.w3c.dom.Node n = (org.w3c.dom.Node) node;
String textString = n.getTextContent();
assertEquals("xpath value should match for " + xpath, expectedValue, textString);
}
public void assertXPathValueContains(DomNode page, String xpath, String needle) {
Object node = page.getFirstByXPath(xpath);
assertNotNull("no node found", node);
assertTrue("the found object was not a Node " + xpath, node instanceof org.w3c.dom.Node);
org.w3c.dom.Node n = (org.w3c.dom.Node) node;
String textString = n.getTextContent();
assertTrue("needle found in haystack", textString.contains(needle));
}
public void assertXPathResultsContainText(DomNode page, String xpath, String needle) {
List<? extends Object> nodes = page.getByXPath(xpath);
assertFalse("no nodes matching xpath found", nodes.isEmpty());
boolean found = false;
for (Object o : nodes) {
if (o instanceof org.w3c.dom.Node) {
org.w3c.dom.Node n = (org.w3c.dom.Node) o;
String textString = n.getTextContent();
if ((textString != null) && textString.contains(needle)) {
found = true;
break;
}
}
}
assertTrue("needle found in haystack", found);
}
/**
* Makes sure that all the images in the page loads successfully.
* (By default, HtmlUnit doesn't load images.)
*/
public void assertAllImageLoadSuccessfully(HtmlPage p) {
for (HtmlImage img : DomNodeUtil.<HtmlImage>selectNodes(p, "//IMG")) {
try {
img.getHeight();
} catch (IOException e) {
throw new Error("Failed to load "+img.getSrcAttribute(),e);
}
}
}
public void assertStringContains(String message, String haystack, String needle) {
assertTrue(message + " (seeking '" + needle + "')",haystack.contains(needle));
}
public void assertStringContains(String haystack, String needle) {
assertTrue("Could not find '" + needle + "'.",haystack.contains(needle));
}
/**
* Asserts that help files exist for the specified properties of the given instance.
*
* @param type
* The describable class type that should have the associated help files.
* @param properties
* ','-separated list of properties whose help files should exist.
*/
public void assertHelpExists(final Class<? extends Describable> type, final String properties) throws Exception {
executeOnServer(new Callable<Object>() {
public Object call() throws Exception {
Descriptor d = jenkins.getDescriptor(type);
WebClient wc = createWebClient();
for (String property : listProperties(properties)) {
String url = d.getHelpFile(property);
assertNotNull("Help file for the property "+property+" is missing on "+type, url);
wc.goTo(url); // make sure it successfully loads
}
return null;
}
});
}