File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\test\src\test\java\hudson\model\QueueTest.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.model;
25
26 import com.gargoylesoftware.htmlunit.html.HtmlFileInput;
27 import com.gargoylesoftware.htmlunit.html.HtmlForm;
28 import com.gargoylesoftware.htmlunit.html.HtmlPage;
29 import hudson.matrix.AxisList;
30 import hudson.matrix.MatrixBuild;
31 import hudson.matrix.MatrixProject;
32 import hudson.matrix.TextAxis;
33 import hudson.model.Cause.*;
34 import hudson.model.Queue.*;
35 import hudson.model.queue.QueueTaskFuture;
36 import hudson.tasks.Shell;
37 import hudson.triggers.SCMTrigger.SCMTriggerCause;
38 import hudson.triggers.TimerTrigger.TimerTriggerCause;
39 import hudson.util.XStream2;
40 import hudson.util.OneShotEvent;
41 import hudson.Launcher;
42 import org.apache.commons.fileupload.FileUploadException;
43 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
44 import org.apache.commons.fileupload.servlet.ServletFileUpload;
45 import org.apache.commons.io.FileUtils;
46 import org.jvnet.hudson.test.Bug;
47 import org.jvnet.hudson.test.HudsonTestCase;
48 import org.jvnet.hudson.test.SequenceLock;
49 import org.jvnet.hudson.test.TestBuilder;
50 import org.mortbay.jetty.Server;
51 import org.mortbay.jetty.bio.SocketConnector;
52 import org.mortbay.jetty.servlet.ServletHandler;
53 import org.mortbay.jetty.servlet.ServletHolder;
54
55 import javax.servlet.ServletException;
56 import javax.servlet.http.HttpServlet;
57 import javax.servlet.http.HttpServletRequest;
58 import javax.servlet.http.HttpServletResponse;
59 import java.io.File;
60 import java.io.IOException;
61 import java.util.ArrayList;
62 import java.util.List;
63 import java.util.concurrent.Future;
64
65 /**
66 * @author Kohsuke Kawaguchi
67 */
68 public class QueueTest extends HudsonTestCase {
69 /**
70 * Checks the persistence of queue.
71 */
72 public void testPersistence() throws Exception {
73 Queue q = jenkins.getQueue();
74
75 // prevent execution to push stuff into the queue
76 jenkins.setNumExecutors(0);
77 jenkins.setNodes(jenkins.getNodes());
78
79 FreeStyleProject testProject = createFreeStyleProject("test");
80 testProject.scheduleBuild(new UserIdCause());
81 q.save();
82
83 System.out.println(FileUtils.readFileToString(new File(jenkins.getRootDir(), "queue.xml")));
84
85 assertEquals(1,q.getItems().length);
86 q.clear();
87 assertEquals(0,q.getItems().length);
88
89 // load the contents back
90 q.load();
91 assertEquals(1,q.getItems().length);
92
93 // did it bind back to the same object?
94 assertSame(q.getItems()[0].task,testProject);
95 }
96
97 /**
98 * Can {@link Queue} successfully recover removal?
99 */
100 public void testPersistence2() throws Exception {
101 Queue q = jenkins.getQueue();
102
103 // prevent execution to push stuff into the queue
104 jenkins.setNumExecutors(0);
105 jenkins.setNodes(jenkins.getNodes());
106
107 FreeStyleProject testProject = createFreeStyleProject("test");
108 testProject.scheduleBuild(new UserIdCause());
109 q.save();
110
111 System.out.println(FileUtils.readFileToString(new File(jenkins.getRootDir(), "queue.xml")));
112
113 assertEquals(1,q.getItems().length);
114 q.clear();
115 assertEquals(0,q.getItems().length);
116
117 // delete the project before loading the queue back
118 testProject.delete();
119 q.load();
120 assertEquals(0,q.getItems().length);
121 }
122
123 /**
124 * {@link Queue.BlockedItem} is not static. Make sure its persistence doesn't end up re-persisting the whole Queue instance.
125 */
126 public void testPersistenceBlockedItem() throws Exception {
127 Queue q = jenkins.getQueue();
128 final SequenceLock seq = new SequenceLock();
129
130 FreeStyleProject p = createFreeStyleProject();
131 p.getBuildersList().add(new TestBuilder() {
132 @Override
133 public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
134 seq.phase(0); // first, we let one build going
135
136 seq.phase(2);
137 return true;
138 }
139 });
140
141 Future<FreeStyleBuild> b1 = p.scheduleBuild2(0);
142 seq.phase(1); // and make sure we have one build under way
143
144 // get another going
145 Future<FreeStyleBuild> b2 = p.scheduleBuild2(0);
146
147 Thread.sleep(1000);
148 Queue.Item[] items = q.getItems();
149 assertEquals(1,items.length);
150 assertTrue(items[0] instanceof BlockedItem);
151
152 q.save();
153 }
154
155 public static final class FileItemPersistenceTestServlet extends HttpServlet {
156 private static final long serialVersionUID = 1L;
157 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
158 resp.setContentType("text/html");
159 resp.getWriter().println(
160 "<html><body><form action='/' method=post name=main enctype='multipart/form-data'>" +
161 "<input type=file name=test><input type=submit>"+
162 "</form></body></html>"
163 );
164 }
165
166 @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
167 try {
168 ServletFileUpload f = new ServletFileUpload(new DiskFileItemFactory());
169 List<?> v = f.parseRequest(req);
170 assertEquals(1,v.size());
171 XStream2 xs = new XStream2();
172 System.out.println(xs.toXML(v.get(0)));
173 } catch (FileUploadException e) {
174 throw new ServletException(e);
175 }
176 }
177 }
178
179 public void testFileItemPersistence() throws Exception {
180 // TODO: write a synchronous connector?
181 byte[] testData = new byte[1024];
182 for( int i=0; i<testData.length; i++ ) testData[i] = (byte)i;
183
184
185 Server server = new Server();
186 SocketConnector connector = new SocketConnector();
187 server.addConnector(connector);
188
189 ServletHandler handler = new ServletHandler();
190 handler.addServletWithMapping(new ServletHolder(new FileItemPersistenceTestServlet()),"/");
191 server.addHandler(handler);
192
193 server.start();
194
195 localPort = connector.getLocalPort();
196
197 try {
198 WebClient wc = new WebClient();
199 HtmlPage p = (HtmlPage) wc.getPage("http://localhost:" + localPort + '/');
200 HtmlForm f = p.getFormByName("main");
201 HtmlFileInput input = (HtmlFileInput) f.getInputByName("test");
202 input.setData(testData);
203 f.submit();
204 } finally {
205 server.stop();
206 }
207 }
208
209 public void testFoldableCauseAction() throws Exception {
210 final OneShotEvent buildStarted = new OneShotEvent();
211 final OneShotEvent buildShouldComplete = new OneShotEvent();
212
213 setQuietPeriod(0);
214 FreeStyleProject project = createFreeStyleProject();
215 // Make build sleep a while so it blocks new builds
216 project.getBuildersList().add(new TestBuilder() {
217 public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
218 buildStarted.signal();
219 buildShouldComplete.block();
220 return true;
221 }
222 });
223
224 // Start one build to block others
225 assertTrue(project.scheduleBuild(new UserIdCause()));
226 buildStarted.block(); // wait for the build to really start
227
228 // Schedule a new build, and trigger it many ways while it sits in queue
229 Future<FreeStyleBuild> fb = project.scheduleBuild2(0, new UserIdCause());
230 assertNotNull(fb);
231 assertFalse(project.scheduleBuild(new SCMTriggerCause("")));
232 assertFalse(project.scheduleBuild(new UserIdCause()));
233 assertFalse(project.scheduleBuild(new TimerTriggerCause()));
234 assertFalse(project.scheduleBuild(new RemoteCause("1.2.3.4", "test")));
235 assertFalse(project.scheduleBuild(new RemoteCause("4.3.2.1", "test")));
236 assertFalse(project.scheduleBuild(new SCMTriggerCause("")));
237 assertFalse(project.scheduleBuild(new RemoteCause("1.2.3.4", "test")));
238 assertFalse(project.scheduleBuild(new RemoteCause("1.2.3.4", "foo")));
239 assertFalse(project.scheduleBuild(new SCMTriggerCause("")));
240 assertFalse(project.scheduleBuild(new TimerTriggerCause()));
241
242 // Wait for 2nd build to finish
243 buildShouldComplete.signal();
244 FreeStyleBuild build = fb.get();
245
246 // Make sure proper folding happened.
247 CauseAction ca = build.getAction(CauseAction.class);
248 assertNotNull(ca);
249 StringBuilder causes = new StringBuilder();
250 for (Cause c : ca.getCauses()) causes.append(c.getShortDescription() + "\n");
251 assertEquals("Build causes should have all items, even duplicates",
252 "Started by user SYSTEM\nStarted by an SCM change\n"
253 + "Started by user SYSTEM\nStarted by timer\n"
254 + "Started by remote host 1.2.3.4 with note: test\n"
255 + "Started by remote host 4.3.2.1 with note: test\n"
256 + "Started by an SCM change\n"
257 + "Started by remote host 1.2.3.4 with note: test\n"
258 + "Started by remote host 1.2.3.4 with note: foo\n"
259 + "Started by an SCM change\nStarted by timer\n",
260 causes.toString());
261
262 // View for build should group duplicates
263 WebClient wc = new WebClient();
264 String buildPage = wc.getPage(build, "").asText().replace('\n',' ');
265 assertTrue("Build page should combine duplicates and show counts: " + buildPage,
266 buildPage.contains("Started by user SYSTEM (2 times) "
267 + "Started by an SCM change (3 times) "
268 + "Started by timer (2 times) "
269 + "Started by remote host 1.2.3.4 with note: test (2 times) "
270 + "Started by remote host 4.3.2.1 with note: test "
271 + "Started by remote host 1.2.3.4 with note: foo"));
272 }
273
274 @Bug(8790)
275 public void testFlyweightTasks() throws Exception {
276 MatrixProject m = createMatrixProject();
277 m.addProperty(new ParametersDefinitionProperty(
278 new StringParameterDefinition("FOO","value")
279 ));
280 m.getBuildersList().add(new Shell("sleep 3"));
281 m.setAxes(new AxisList(new TextAxis("DoesntMatter", "aaa","bbb")));
282
283 List<Future<MatrixBuild>> r = new ArrayList<Future<MatrixBuild>>();
284
285 for (int i=0; i<3; i++)
286 r.add(m.scheduleBuild2(0,new UserIdCause(),new ParametersAction(new StringParameterValue("FOO","value"+i))));
287
288 for (Future<MatrixBuild> f : r)
289 assertBuildStatusSuccess(f);
290 }
291
292 public void testWaitForStart() throws Exception {
293 final OneShotEvent ev = new OneShotEvent();
294 FreeStyleProject p = createFreeStyleProject();
295 p.getBuildersList().add(new TestBuilder() {
296 @Override
297 public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
298 ev.block();
299 return true;
300 }
301 });
302
303 QueueTaskFuture<FreeStyleBuild> v = p.scheduleBuild2(0);
304 FreeStyleBuild b = v.waitForStart();
305 assertEquals(1,b.getNumber());
306 assertTrue(b.isBuilding());
307 assertSame(p,b.getProject());
308
309 ev.signal(); // let the build complete
310 FreeStyleBuild b2 = assertBuildStatusSuccess(v);
311 assertSame(b,b2);
312 }
313 }
314