This repository has been archived by the owner on Jul 13, 2022. It is now read-only.
/
SWTBotUtils.java
520 lines (461 loc) · 17 KB
/
SWTBotUtils.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
/*******************************************************************************
* Copyright (c) 2012 VMware, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* VMware, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.test.util;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.withRegex;
import static org.eclipse.swtbot.swt.finder.waits.Conditions.waitForShell;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import junit.framework.Assert;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotPerspective;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.finders.ContextMenuFinder;
import org.eclipse.swtbot.swt.finder.finders.MenuFinder;
import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
import org.eclipse.swtbot.swt.finder.results.Result;
import org.eclipse.swtbot.swt.finder.results.VoidResult;
import org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences;
import org.eclipse.swtbot.swt.finder.utils.SWTUtils;
import org.eclipse.swtbot.swt.finder.utils.TableCollection;
import org.eclipse.swtbot.swt.finder.utils.TableRow;
import org.eclipse.swtbot.swt.finder.waits.Conditions;
import org.eclipse.swtbot.swt.finder.waits.DefaultCondition;
import org.eclipse.swtbot.swt.finder.waits.ICondition;
import org.eclipse.swtbot.swt.finder.waits.WaitForObjectCondition;
import org.eclipse.swtbot.swt.finder.widgets.AbstractSWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotList;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotStyledText;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.eclipse.ui.PlatformUI;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.springsource.ide.eclipse.commons.tests.util.StsTestUtil;
/**
* Utility methods that are useful in writing SWTBot tests.
* @author Kris De Volder
* @author Nieraj Singh
* @author Tomasz Zarna
*/
public class SWTBotUtils {
public static final long PROCESS_COMPLETION_TIMEOUT = 60000; //Needs enough time to finish running grails command like compile -non-interactive
public static final long WAIT_FOR_BUILD_TIMEOUT = 10000;
/**
* Open a particular perspective, or try to activate it if it can't be
* opened (maybe it already open)
*/
public static void openPerspective(SWTWorkbenchBot bot,
String perspectiveLabel) {
SWTBotShell shell = null;
try {
menu(bot, "Window").menu("Open Perspective").menu("Other...")
.click();
shell = bot.shell("Open Perspective");
// SWTBotUtils.screenshot("openPerspective_"+perspectiveLabel);
assertTrue(shell.isOpen());
bot.waitUntil(SWTBotUtils.widgetMakeActive(shell));
shell.bot().table().select(perspectiveLabel);
shell.bot().button("OK").click();
bot.waitUntil(Conditions.shellCloses(shell));
} catch (Exception e) {
if (shell != null && shell.isOpen())
shell.close();
System.err.println("Couldn't open perspective '" + perspectiveLabel
+ "'\n"
+ "trying to activate already open perspective instead");
// maybe somehow the perspective is already opened (by another test
// before us)
SWTBotPerspective perspective = bot
.perspectiveByLabel(perspectiveLabel);
perspective.activate();
assertTrue(perspective.isActive());
}
Assert.assertEquals(perspectiveLabel, bot.activePerspective()
.getLabel());
}
/**
* @return
*/
public static Shell getMainShell() {
Shell mainWidget = UIThreadRunnable.syncExec(new Result<Shell>() {
public Shell run() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell();
}
});
return mainWidget;
}
/**
* Create an SWTBot {@link ICondition} that tests whether a given resource
* exists.
*
* @param pathToResource
* Path starting from workspace root. For example
* "kris/src/Foo.java" would refer to file "Foo.java" in the
* "src" directory of project "kris". Path's ending with trailing
* "/" will be considered to point to "IFolder" path without
* trailing "/" will be treated as "IFile" references. Paths with
* no "/" at all will be treated as references to a project.
* @return
*/
public static ResourceExists resourceExists(String pathToResource) {
return new ResourceExists(pathToResource);
}
/**
* Wait for resource to be created.
*
* @param pathToResource
* Path starting from workspace root. For example
* "kris/src/Foo.java" would refer to file "Foo.java" in the
* "src" directory of project "kris". Path's ending with trailing
* "/" will be considered to point to "IFolder" path without
* trailing "/" will be treated as "IFile" references. Paths with
* on "/" at all will be treated as references to a project.
*/
public static void waitResourceCreated(SWTBot bot, String pathToResource,
long timeOut) {
bot.waitUntil(resourceExists(pathToResource), timeOut);
}
/**
* Wait for resource to be created.
*
* @param pathToResource
* Path starting from workspace root. For example
* "kris/src/Foo.java" would refer to file "Foo.java" in the
* "src" directory of project "kris". Path's ending with trailing
* "/" will be considered to point to "IFolder" path without
* trailing "/" will be treated as "IFile" references. Paths with
* on "/" at all will be treated as references to a project.
*/
public static void waitResourceCreated(SWTBot bot, String pathToResource) {
waitResourceCreated(bot, pathToResource, SWTBotPreferences.TIMEOUT);
}
/**
* @return a List of {@link Shell} under a parent.
* @param parent
* the parent under which a shell will be found.
*/
public static List<Shell> shells(SWTBotShell parent) {
Matcher<Shell> anyShell = widgetOfType(Shell.class);
WaitForObjectCondition<Shell> waitForShell = waitForShell(anyShell,
parent.widget);
parent.bot().waitUntilWidgetAppears(waitForShell);
List<Shell> allShells = waitForShell.getAllMatches();
System.err.println(">>> SWTBot Shells found:");
for (Shell shell : allShells) {
SWTBotShell bot = new SWTBotShell(shell);
System.err.println(" '" + bot.getText() + "'");
}
System.err.println("<<< SWTBot Shells found:");
return allShells;
}
/**
* @return the first shell that is present or appears under a given parent.
* @param parent
* the parent under which the shell will be found.
*/
public static SWTBotShell shell(SWTBotShell parentShell) {
return new SWTBotShell(shells(parentShell).get(0));
}
/**
* Wait for a shell with the given regular expression.
*
* @param bot the SWTBot
* @param regex the regular expression
*/
public static void waitForShellWithRegex(SWTBot bot, String regex) {
Matcher<Shell> withRegex = withRegex(regex);
WaitForObjectCondition<Shell> waitForShell = waitForShell(withRegex);
bot.waitUntilWidgetAppears(waitForShell);
}
public static void doubleClick(SWTWorkbenchBot bot,
final SWTBotTable table, int row, int col) {
table.click(row, col);
// Note: table.doubleClick() method doesn't work, table appears not to
// be listening to the events that are being posted by this method.
// Use this workaround instead:
// http://dev.eclipse.org/mhonarc/newsLists/news.eclipse.swtbot/msg00309.html
UIThreadRunnable.asyncExec(bot.getDisplay(), new VoidResult() {
public void run() {
table.widget.notifyListeners(SWT.DefaultSelection, new Event());
}
});
}
/**
* A better version of the "menu" method from SWTBot. This one will retry to
* get the active shell on each poll, rather than get the active shell at
* the start and then get stuck using the wrong shell.
*/
public static SWTBotMenu menu(SWTWorkbenchBot bot, String name) {
return new SWTBotMenu(SWTBotConditions.waitForShellMenuList(bot, name,
true).get(0));
}
/**
* Given a view name containing a tree, this method will attempt to select a
* node contained within a parent.
*
* @param bot
* containing shell with a tree
* @param shellName
* of the shell containing tree
* @param parentName
* parent containing the node to be selected
* @param childName
* node to be selected
* @return the selected node
*/
public static SWTBotTreeItem selectChildTreeElement(SWTBot bot,
String shellName, String parentName, String childName) {
SWTBotShell shell = bot.shell(shellName);
shell.activate();
SWTBotTreeItem parentNode = SWTBotConditions.waitForNodeExpanded(bot,
parentName);
SWTBotTreeItem childNode = SWTBotConditions.waitChildNodeToAppear(bot,
parentNode, childName);
return childNode.select();
}
/**
* Gets a view by name. It assumes the view MUST be opened, although not
* necessarily active. Open the view first if necessary.
*
* @return Active, focused explorer view
*/
public static SWTBotView getView(SWTWorkbenchBot bot, String name) {
SWTBotView explorer = bot.viewByTitle(name);
explorer.setFocus();
return explorer;
}
/**
* Selects a project in the currently opened view. A view must be opened
* prior to using this method.
*
* @param projectName
* @return
*/
public static SWTBotTree selectProject(SWTWorkbenchBot bot,
String projectName, String viewName) {
SWTBotView explorer = getView(bot, viewName);
SWTBotTree tree = explorer.bot().tree();
if (projectName != null) {
tree.select(projectName);
waitForSelection(bot, projectName, tree);
return tree;
} else {
tree.select(new String[0]);
waitForSelection(bot, "", tree);
return tree;
}
}
/**
* Sometimes widgets respond slowly to selection and key presses. Use this
* method to wait for a selection to become what you expect it to be.
* Otherwise, trying to proceed will probably fail the test.
*/
public static void waitForSelection(SWTWorkbenchBot bot,
final String expected, final SWTBotList list) {
bot.waitUntil(new DefaultCondition() {
public boolean test() throws Exception {
String selection = getSelection();
return expected.equals(selection);
}
private String getSelection() {
String[] selections = list.selection();
String selection = null;
if (selections.length == 1)
selection = selections[0];
return selection;
}
public String getFailureMessage() {
return "Was expecting selection '" + expected + " but found '"
+ getSelection() + "'";
}
});
}
/**
* Wait for a selection to become what you expect it to be. This method
* assumes a SWTBotTree that only has a single column selection.
*/
public static void waitForSelection(SWTWorkbenchBot bot,
final String expected, final SWTBotTree tree) {
bot.waitUntil(new DefaultCondition() {
public boolean test() throws Exception {
String selection = getSelection(tree);
return expected.equals(selection);
}
public String getFailureMessage() {
return "Was expecting selection \n----\n" + expected
+ "\n----\nbut found \n----\n" + getSelection(tree)
+ "\n-----";
}
});
}
public static String getSelection(SWTBotTree tree) {
TableCollection selections = tree.selection();
String selection = "";
for (int r = 0; r < selections.rowCount(); r++) {
if (r > 0)
selection += "\n";
TableRow row = selections.get(r);
for (int c = 0; c < row.columnCount(); c++) {
if (c > 0)
selection += " >> ";
selection += row.get(c);
}
}
return selection;
}
private static int screenshotNumber = 0;
/**
* Call this method to create extra screenshots along the way. A message
* will be printed to System.err when the screenshot is taken (look in error
* log to see which screenshot file was taken when). Scrreenshots will
* include a sequence number at the start of their name that makes it easy
* to see in what order they were taken.
*
* @filename The screenshot will be save as "screenshots/filename_<number>"
*/
public static void screenshot(String fileName) {
fileName = "screenshots/" + screenshotNumber() + fileName + "."
+ SWTBotPreferences.SCREENSHOT_FORMAT.toLowerCase();
System.err.println("Creating extra screenshot: " + fileName);
new File("screenshots").mkdirs(); //$NON-NLS-1$
SWTUtils.captureScreenshot(fileName);
}
private static String screenshotNumber() {
return String.format("%03d_", screenshotNumber++);
}
public static void waitForAllBuildJobs(SWTBot bot){
waitForAllProcessesToTerminate(bot);
waitForJobCompletions();
bot.sleep(WAIT_FOR_BUILD_TIMEOUT);
waitForJobCompletions();
}
private static void waitForJobCompletions() {
StsTestUtil.waitForAutoBuild();
StsTestUtil.waitForManualBuild();
StsTestUtil.waitForJobFamily(ResourcesPlugin.FAMILY_AUTO_REFRESH);
StsTestUtil.waitForJobFamily(ResourcesPlugin.FAMILY_MANUAL_REFRESH);
}
public static void waitForAllProcessesToTerminate(SWTBot bot) {
waitForAllProcessesToTerminate(bot, PROCESS_COMPLETION_TIMEOUT);
}
public static void waitForAllProcessesToTerminate(SWTBot bot, long timeout) {
bot.waitUntil(new ICondition() {
private IProcess activeProcess = null;
public boolean test() throws Exception {
IProcess[] processes = DebugPlugin.getDefault().getLaunchManager().getProcesses();
for (IProcess process : processes) {
if (!process.isTerminated()) {
print("Waiting for processes...");
print("active = "+process.getClass()+ " " + process.getLabel());
activeProcess = process;
return false;
}
}
print("Waiting for processes... DONE");
return true;
}
public void init(SWTBot bot) {
}
public String getFailureMessage() {
return "A process is still active:" +
"\n label = " + activeProcess.getLabel() +
"\n type = " + activeProcess.getAttribute(IProcess.ATTR_PROCESS_TYPE) +
"\n cmd = " + activeProcess.getAttribute(IProcess.ATTR_CMDLINE);
}
}, timeout);
}
/**
* This is only for debugging purposes, in case having trouble finding the
* menus...
*/
public static List<MenuItem> findAllContextMenus(Shell shell) {
MenuFinder menuFinder = new ContextMenuFinder(shell);
return menuFinder.findMenus(shell, anyMenuMatcher, true);
}
private static final Matcher<MenuItem> anyMenuMatcher = new BaseMatcher<MenuItem>() {
public boolean matches(Object item) {
boolean result = item instanceof MenuItem;
if (result) {
MenuItem menu = (MenuItem) item;
System.out.println("Found menu with text : '" + menu.getText()
+ "'");
}
return result;
}
public void describeTo(Description description) {
description.appendText("Any menu");
}
};
/**
* @param explorerTree
* @return
*/
public static ICondition widgetMakeActive(
final AbstractSWTBot<? extends Widget> widget) {
return new ICondition() {
public boolean test() throws Exception {
widget.setFocus();
return widget.isActive();
}
public void init(SWTBot bot) {
}
public String getFailureMessage() {
return "Widget not active: " + widget;
}
};
}
private static boolean enablePrinting = true;
public static void enablePrinting() {
enablePrinting = true;
}
public static void disablePrinting() {
enablePrinting = false;
}
public static void print(String message) {
if (enablePrinting) {
System.out.println(message);
}
}
public static ICondition widgetIsDisposed(
AbstractSWTBot<? extends Widget> widget) {
return new WidgetIsDisposed(widget);
}
public static String getConsoleText(SWTWorkbenchBot bot) {
SWTBotView console = bot.viewByTitle("Console");
SWTBotStyledText textWidget = console.bot().styledText();
return textWidget.getText();
}
/**
* Repeatedly try to find a submenu that contains a given String,
* until the menu appears, or until timeout happens.
*/
public static SWTBotMenu subMenuContaining(SWTBot bot, SWTBotMenu parentMenu, String text) {
Matcher<MenuItem> matcher = SWTBotConditions.withTextContaining(text);
SubMenusMatching condition = new SubMenusMatching(bot, parentMenu, matcher);
return new SWTBotMenu(condition.getMenus().get(0));
}
}