KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > lib > EditorTestCase


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 /*
21  * EditorTestCase.java
22  *
23  * Created on 24. srpen 2004, 12:32
24  */

25
26 package lib;
27
28 import java.awt.datatransfer.Transferable JavaDoc;
29 import java.io.File JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import javax.swing.text.BadLocationException JavaDoc;
32 import javax.swing.text.Document JavaDoc;
33 import org.netbeans.jellytools.EditorOperator;
34 import org.netbeans.jellytools.JellyTestCase;
35 import org.netbeans.jellytools.NbDialogOperator;
36 import org.netbeans.jellytools.ProjectsTabOperator;
37 import org.netbeans.jellytools.nodes.Node;
38 import org.netbeans.jellytools.nodes.ProjectRootNode;
39 import org.netbeans.jemmy.JemmyException;
40 import org.netbeans.jemmy.JemmyProperties;
41 import org.netbeans.jemmy.TimeoutExpiredException;
42 import org.netbeans.jemmy.Waitable;
43 import org.netbeans.jemmy.Waiter;
44 import org.netbeans.jemmy.operators.ComponentOperator;
45 import org.netbeans.jemmy.operators.JEditorPaneOperator;
46 import org.netbeans.jemmy.operators.JTextFieldOperator;
47 //retouche:
48
//import org.netbeans.junit.ide.ProjectSupport;
49

50 /**
51  *
52  * @author Petr Felenda, Martin Roskanin
53  */

54 public class EditorTestCase extends JellyTestCase {
55     
56     private static final int OPENED_PROJECT_ACCESS_TIMEOUT = 1000;
57     
58     /** Default name of project is used if not specified in openProject method. */
59     private String JavaDoc defaultProjectName = "editor_test";
60     private String JavaDoc defaultSamplePackage = "dummy";
61     private String JavaDoc defaultSampleName = "sample1";
62
63     private static final char treeSeparator = '|';
64     private final String JavaDoc defaultPackageNameTreePath = "Source packages"+treeSeparator+"dummy";
65     private final String JavaDoc defaultFileName = "sample1";
66     private String JavaDoc projectName = null;
67     private String JavaDoc treeSubPackagePathToFile = null;
68     private String JavaDoc fileName = null;
69     private final String JavaDoc dialogSaveTitle = "Save"; // I18N
70
public static final int WAIT_MAX_MILIS_FOR_CLIPBOARD = 4000;
71     
72     /**
73      * Creates a new instance of EditorTestCase.
74      *
75      * <p>
76      * Initializes default sample file name (package and name)
77      * so that {@link #openDefaultSampleFile()} can be used.
78      * <br>
79      * The rule for naming is the same like for golden files
80      * i.e. package corresponds to the class name and the file
81      * name corresponds to test method name.
82      *
83      * @param testMethodName name of the test method
84      * that should be executed.
85      */

86     public EditorTestCase(String JavaDoc testMethodName) {
87         super(testMethodName);
88         
89         defaultSamplePackage = getClass().getName();
90         defaultSampleName = getName();
91     }
92     
93     /**
94      * Split class full name into package name and class name.
95      *
96      * @param full name of the class
97      * @return array containing package name and the class name.
98      */

99 /* public static String[] splitClassName(String classFullName) {
100         int lastDotIndex = classFullName.lastIndexOf('.');
101         return new String[] {
102             (lastDotIndex >= 0) ? classFullName.substring(0, lastDotIndex) : "", // pkg name
103             classFullName.substring(lastDotIndex + 1) // class name
104         };
105     }
106  */

107     
108     /** Open project. Before opening the project is checked opened projects.
109      * @param projectName is name of the project stored in .../editor/test/qa-functional/data/ directory.
110      */

111     public void openProject(String JavaDoc projectName) {
112         this.projectName = projectName;
113         File JavaDoc projectPath = new File JavaDoc(this.getDataDir() + "/projects", projectName);
114         log("data dir = "+this.getDataDir().toString());
115         
116         /* 1. check if project is open */
117         ProjectsTabOperator pto = new ProjectsTabOperator();
118         pto.invoke();
119         boolean isOpen = true;
120         try {
121             JemmyProperties.setCurrentTimeout("JTreeOperator.WaitNextNodeTimeout", OPENED_PROJECT_ACCESS_TIMEOUT);
122             ProjectRootNode prn = pto.getProjectRootNode(projectName);
123         } catch (TimeoutExpiredException ex) {
124             // This excpeiton is ok, project is not open;
125
//ex.printStackTrace();
126
isOpen = false;
127         }
128         
129         if ( isOpen ) {
130             log("Project is open!");
131             return;
132         }
133         
134         
135         /* 2. open project */
136 //retouche:
137
// Object prj= ProjectSupport.openProject(projectPath);
138

139     }
140    
141     /**
142      * Get the default project name to be used
143      * in {@link openDefaultProject()}.
144      * <br>
145      * The default value is "editor_test".
146      *
147      * @return default project name
148      */

149     protected String JavaDoc getDefaultProjectName() {
150         return defaultProjectName;
151     }
152     
153     
154     
155     /**
156      * Set the default project name to be used
157      * in {@link openDefaultProject()}.
158      *
159      * @param defaultProjectName new default project name.
160      */

161     /*
162     protected void setDefaultProjectName(String defaultProjectName) {
163         this.defaultProjectName = defaultProjectName;
164     }
165      */

166     
167     /**
168      * Open default project determined
169      * by {@link #getDefaultProjectName()}.
170      */

171     protected void openDefaultProject() {
172         openProject(getDefaultProjectName());
173     }
174     
175     /**
176      * Close the default project.
177      */

178     protected void closeDefaultProject() {
179         closeProject(getDefaultProjectName());
180     }
181     
182     protected void closeProject(String JavaDoc projectName) {
183 //retouche:
184
// ProjectSupport.closeProject(projectName);
185
}
186     
187     
188     /** Open file in open project
189      * @param treeSubPath e.g. "Source Packages|test","sample1" */

190     public void openFile(String JavaDoc treeSubPackagePathToFile, String JavaDoc fileName) {
191         // debug info, to be removed
192
this.treeSubPackagePathToFile = treeSubPackagePathToFile;
193         ProjectsTabOperator pto = new ProjectsTabOperator();
194         pto.invoke();
195         ProjectRootNode prn = pto.getProjectRootNode(projectName);
196         prn.select();
197         
198         // fix of issue #51191
199
// each of nodes is checked by calling method waitForChildNode
200
// before they are actually opened
201
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(treeSubPackagePathToFile,
202                 treeSeparator+"");
203         String JavaDoc token = "";
204         String JavaDoc oldtoken = "";
205         // if there are more then one tokens process each of them
206
if (st.countTokens()>1) {
207             token = st.nextToken();
208             String JavaDoc fullpath = token;
209             while (st.hasMoreTokens()) {
210                 token = st.nextToken();
211                 waitForChildNode(fullpath, token);
212                 fullpath += treeSeparator+token;
213             }
214         }
215         // last node
216
waitForChildNode(treeSubPackagePathToFile, fileName);
217         // end of fix of issue #51191
218

219         Node node = new Node(prn,treeSubPackagePathToFile+treeSeparator+fileName);
220         node.performPopupAction("Open");
221     }
222     
223     /**
224      * Waits for a child node to be shown in the IDE. Needed for test
225      * stabilization on slow machines.
226      * @param parentPath full path for parent, | used as a delimiter
227      * @param childName name of the child node
228      */

229     public void waitForChildNode(String JavaDoc parentPath, String JavaDoc childName) {
230         ProjectsTabOperator pto = new ProjectsTabOperator();
231         ProjectRootNode prn = pto.getProjectRootNode(projectName);
232         prn.select();
233         Node parent = new Node(prn, parentPath);
234         final String JavaDoc finalFileName = childName;
235         try {
236             // wait for max. 30 seconds for the file node to appear
237
JemmyProperties.setCurrentTimeout("Waiter.WaitingTime", 30000);
238             new Waiter(new Waitable() {
239                 public Object JavaDoc actionProduced(Object JavaDoc parent) {
240                     return ((Node)parent).isChildPresent(finalFileName) ?
241                             Boolean.TRUE: null;
242                 }
243                 public String JavaDoc getDescription() {
244                     return("Waiting for the tree to load.");
245                 }
246             }).waitAction(parent);
247         } catch (InterruptedException JavaDoc e) {
248             throw new JemmyException("Interrupted.", e);
249         }
250     }
251     
252     /** Open the default file in open project */
253     public void openFile() {
254         openFile(defaultPackageNameTreePath,defaultFileName);
255     }
256     
257     /** Close file in open project.
258      */

259     public void closeFile() {
260         try {
261             new EditorOperator(fileName).close();
262         } catch ( TimeoutExpiredException ex) {
263             log(ex.getMessage());
264             log("Can't close the file");
265         }
266     }
267     
268     /** Close file in open project.
269      */

270     public void closeFileWithSave() {
271         try {
272            new EditorOperator(fileName).close(true);
273         } catch ( TimeoutExpiredException ex) {
274             log(ex.getMessage());
275             log("Can't close the file");
276         }
277     }
278     
279     
280     /** Close file in open project.
281      */

282     public void closeFileWithDiscard() {
283         try {
284            new EditorOperator(fileName).closeDiscard();
285         } catch ( TimeoutExpiredException ex) {
286             log(ex.getMessage());
287             log("Can't close the file");
288         }
289     }
290     
291     /** Close dialog with added title
292      * @param title dialog title */

293     public void closeDialog(String JavaDoc title) {
294         NbDialogOperator dialog = new NbDialogOperator(title);
295         dialog.closeByButton();
296     }
297     
298     /**
299      * Write the text of the passed document to the ref file
300      * and compare the created .ref file with the golden file.
301      * <br>
302      * If the two files differ the test fails and generates the diff file.
303      *
304      * @param testDoc document to be written to the .ref file and compared.
305      */

306     protected void compareReferenceFiles(Document JavaDoc testDoc) {
307         try {
308             ref(testDoc.getText(0, testDoc.getLength()));
309             compareReferenceFiles();
310         } catch (BadLocationException JavaDoc e) {
311             e.printStackTrace(getLog());
312             fail();
313         }
314     }
315
316     /**
317      * Open a source file located in the "Source packages" in the editor.
318      *
319      * @param dir directory path with "|" separator.
320      * @param srcName source name without suffix.
321      */

322     protected void openSourceFile(String JavaDoc dir, String JavaDoc srcName) {
323         openFile(org.netbeans.jellytools.Bundle.getString("org.netbeans.modules.java.j2seproject.Bundle", "NAME_src.dir")+treeSeparator+dir, srcName);
324     }
325     
326     protected final String JavaDoc getDefaultSamplePackage() {
327         return defaultSamplePackage;
328     }
329     
330     protected final String JavaDoc getDefaultSampleName() {
331         return defaultSampleName;
332     }
333
334     protected void openDefaultSampleFile() {
335         openSourceFile(defaultSamplePackage, defaultSampleName);
336     }
337
338     protected EditorOperator getDefaultSampleEditorOperator() {
339         return new EditorOperator(defaultSampleName);
340     }
341
342     /** Method will wait max. <code> maxMiliSeconds </code> miliseconds for the <code> requiredValue </code>
343      * gathered by <code> resolver </code>.
344      *
345      * @param maxMiliSeconds maximum time to wait for requiredValue
346      * @param resolver resolver, which is gathering an actual value
347      * @param requiredValue if resolver value equals requiredValue the wait cycle is finished
348      *
349      * @return false if the given maxMiliSeconds time elapsed and the requiredValue wasn't obtained
350      */

351     protected boolean waitMaxMilisForValue(int maxMiliSeconds, ValueResolver resolver, Object JavaDoc requiredValue){
352         int time = (int) maxMiliSeconds / 100;
353         while (time > 0) {
354             Object JavaDoc resolvedValue = resolver.getValue();
355             if (requiredValue == null && resolvedValue == null){
356                 return true;
357             }
358             if (requiredValue != null && requiredValue.equals(resolvedValue)){
359                 return true;
360             }
361             try {
362                 Thread.currentThread().sleep(100);
363             } catch (InterruptedException JavaDoc ex) {
364                 time=0;
365             }
366             time--;
367         }
368         return false;
369     }
370     
371     /** Interface for value resolver needed for i.e. waitMaxMilisForValue method.
372      * For more details, please look at {@link #waitMaxMilisForValue()}.
373      */

374     public static interface ValueResolver{
375         /** Returns checked value */
376         Object JavaDoc getValue();
377     }
378
379     protected ValueResolver getClipboardResolver(final JEditorPaneOperator txtOper, final Transferable JavaDoc oldClipValue){
380         
381         ValueResolver clipboardValueResolver = new ValueResolver(){
382             public Object JavaDoc getValue(){
383                 Transferable JavaDoc newClipValue = txtOper.getToolkit().getSystemClipboard().getContents(txtOper);
384                 log("newClipValue:"+newClipValue);
385                 return (newClipValue == oldClipValue) ? Boolean.TRUE : Boolean.FALSE;
386             }
387         };
388         
389         return clipboardValueResolver;
390     }
391     
392     protected ValueResolver getTextFieldResolver(final JTextFieldOperator oper,final String JavaDoc newValue) {
393         ValueResolver textFieldResolver = new ValueResolver(){
394             public Object JavaDoc getValue(){
395                 String JavaDoc actVal = oper.getText();
396                 log("actual value:"+actVal);
397                 return (newValue.equals(actVal)) ? Boolean.TRUE : Boolean.FALSE;
398             }
399         };
400         
401         return textFieldResolver;
402     }
403
404     protected void cutCopyViaStrokes(JEditorPaneOperator txtOper, int key, int mod){
405         Transferable JavaDoc oldClipValue = txtOper.getToolkit().getSystemClipboard().getContents(txtOper);
406         log("");
407         log("oldClipValue:"+oldClipValue);
408         txtOper.pushKey(key, mod);
409         // give max WAIT_MAX_MILIS_FOR_CLIPBOARD milis for clipboard to change
410
boolean success = waitMaxMilisForValue(WAIT_MAX_MILIS_FOR_CLIPBOARD, getClipboardResolver(txtOper, oldClipValue), Boolean.FALSE);
411         if (success == false){
412             // give it one more chance. maybe selection was not ready at the time of
413
// copying
414
log("!!!! ONCE AGAIN");
415             txtOper.pushKey(key, mod);
416             // give max WAIT_MAX_MILIS_FOR_CLIPBOARD milis for clipboard to change
417
waitMaxMilisForValue(WAIT_MAX_MILIS_FOR_CLIPBOARD, getClipboardResolver(txtOper, oldClipValue), Boolean.FALSE);
418         }
419     }
420
421     protected void pasteViaStrokes(ComponentOperator compOper, int key, int mod, ValueResolver resolver){
422         compOper.pushKey(key, mod);
423         // give max WAIT_MAX_MILIS_FOR_CLIPBOARD milis for clipboard to change
424
if (resolver !=null){
425             boolean success = waitMaxMilisForValue(WAIT_MAX_MILIS_FOR_CLIPBOARD, resolver, Boolean.TRUE);
426             if (success == false){
427                 // give it one more chance.
428
compOper.pushKey(key, mod);
429                 // give max WAIT_MAX_MILIS_FOR_CLIPBOARD milis for clipboard to change
430
waitMaxMilisForValue(WAIT_MAX_MILIS_FOR_CLIPBOARD, resolver, Boolean.TRUE);
431             }
432         }
433     }
434     
435 }
436
Popular Tags