9b9adf815ff5a7cbf22b6d184c0df84662c03855
[jalview.git] / test / jalview / bin / CommandLineOperations.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import static org.testng.Assert.assertNotNull;
24 import static org.testng.Assert.assertTrue;
25
26 import java.io.BufferedReader;
27 import java.io.File;
28 import java.io.IOException;
29 import java.io.InputStreamReader;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33
34 import org.testng.Assert;
35 import org.testng.FileAssert;
36 import org.testng.annotations.BeforeClass;
37 import org.testng.annotations.BeforeTest;
38 import org.testng.annotations.DataProvider;
39 import org.testng.annotations.Test;
40
41 import io.github.classgraph.ClassGraph;
42 import io.github.classgraph.ModuleRef;
43 import io.github.classgraph.ScanResult;
44 import jalview.gui.JvOptionPane;
45
46 public class CommandLineOperations
47 {
48
49   @BeforeClass(alwaysRun = true)
50   public void setUpJvOptionPane()
51   {
52     JvOptionPane.setInteractiveMode(false);
53     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
54   }
55
56   // Note longer timeout needed on full test run than on individual tests
57   private static final int TEST_TIMEOUT = 23000;
58
59   private static final int SETUP_TIMEOUT = 9500;
60
61   private static final int MINFILESIZE_SMALL = 2096;
62
63   private static final int MINFILESIZE_BIG = 4096;
64
65   private ArrayList<String> successfulCMDs = new ArrayList<>();
66
67   /***
68    * from
69    * http://stackoverflow.com/questions/808276/how-to-add-a-timeout-value-when
70    * -using-javas-runtime-exec
71    * 
72    * @author jimp
73    * 
74    */
75   private static class Worker extends Thread
76   {
77     private final Process process;
78
79     private BufferedReader outputReader;
80
81     private BufferedReader errorReader;
82
83     private Integer exit;
84
85     private Worker(Process process)
86     {
87       this.process = process;
88     }
89
90     @Override
91     public void run()
92     {
93       try
94       {
95         exit = process.waitFor();
96       } catch (InterruptedException ignore)
97       {
98         return;
99       }
100     }
101
102     public BufferedReader getOutputReader()
103     {
104       return outputReader;
105     }
106
107     public void setOutputReader(BufferedReader outputReader)
108     {
109       this.outputReader = outputReader;
110     }
111
112     public BufferedReader getErrorReader()
113     {
114       return errorReader;
115     }
116
117     public void setErrorReader(BufferedReader errorReader)
118     {
119       this.errorReader = errorReader;
120     }
121   }
122
123   private static ClassGraph scanner = null;
124
125   private static String classpath = null;
126
127   private static String modules = null;
128
129   private static String java_exe = null;
130
131   public synchronized static String getClassPath()
132   {
133     if (scanner == null)
134     {
135       scanner = new ClassGraph();
136       ScanResult scan = scanner.scan();
137       classpath = scan.getClasspath();
138       modules = "";
139       for (ModuleRef mr : scan.getModules())
140       {
141         modules.concat(mr.getName());
142       }
143       java_exe = System.getProperty("java.home") + File.separator + "bin"
144               + File.separator + "java";
145
146     }
147     while (classpath == null)
148     {
149       try
150       {
151         Thread.sleep(10);
152       } catch (InterruptedException x)
153       {
154
155       }
156     }
157     return classpath;
158   }
159
160   private Worker getJalviewDesktopRunner(boolean withAwt, String cmd,
161           int timeout)
162   {
163     // Note: JAL-3065 - don't include quotes for lib/* because the arguments are
164     // not expanded by the shell
165     String classpath = getClassPath();
166     String _cmd = java_exe + " "
167             + (withAwt ? "-Djava.awt.headless=true" : "") + " -classpath "
168             + classpath
169             + (modules.length() > 2 ? "--add-modules=\"" + modules + "\""
170                     : "")
171             + " jalview.bin.Jalview ";
172     Process ls2_proc = null;
173     Worker worker = null;
174     try
175     {
176       ls2_proc = Runtime.getRuntime().exec(_cmd + cmd);
177     } catch (Throwable e1)
178     {
179       e1.printStackTrace();
180     }
181     if (ls2_proc != null)
182     {
183       BufferedReader outputReader = new BufferedReader(
184               new InputStreamReader(ls2_proc.getInputStream()));
185       BufferedReader errorReader = new BufferedReader(
186               new InputStreamReader(ls2_proc.getErrorStream()));
187       worker = new Worker(ls2_proc);
188       worker.start();
189       try
190       {
191         worker.join(timeout);
192       } catch (InterruptedException e)
193       {
194         System.err.println("Thread interrupted");
195       }
196       worker.setOutputReader(outputReader);
197       worker.setErrorReader(errorReader);
198     }
199     return worker;
200   }
201
202   @Test(groups = { "Functional" })
203   public void reportCurrentWorkingDirectory()
204   {
205     try
206     {
207       Path currentRelativePath = Paths.get("");
208       String s = currentRelativePath.toAbsolutePath().toString();
209       System.out.println("Test CWD is " + s);
210     } catch (Exception q)
211     {
212       q.printStackTrace();
213     }
214   }
215
216   @BeforeTest(alwaysRun = true)
217   public void initialize()
218   {
219     new CommandLineOperations();
220   }
221
222   @BeforeTest(alwaysRun = true)
223   public void setUpForHeadlessCommandLineInputOperations()
224           throws IOException
225   {
226     String cmds = "nodisplay -open examples/uniref50.fa -sortbytree -props test/jalview/bin/testProps.jvprops -colour zappo "
227             + "-jabaws http://www.compbio.dundee.ac.uk/jabaws -nosortbytree "
228             + "-features examples/testdata/plantfdx.features -annotations examples/testdata/plantfdx.annotations -tree examples/testdata/uniref50_test_tree";
229     Worker worker = getJalviewDesktopRunner(true, cmds, SETUP_TIMEOUT);
230     String ln = null;
231     while ((ln = worker.getOutputReader().readLine()) != null)
232     {
233       System.out.println(ln);
234       successfulCMDs.add(ln);
235     }
236     while ((ln = worker.getErrorReader().readLine()) != null)
237     {
238       System.err.println(ln);
239     }
240   }
241
242   @BeforeTest(alwaysRun = true)
243   public void setUpForCommandLineInputOperations() throws IOException
244   {
245     String cmds = "-open examples/uniref50.fa -noquestionnaire -nousagestats";
246     final Worker worker = getJalviewDesktopRunner(false, cmds,
247             SETUP_TIMEOUT);
248
249     // number of lines expected on STDERR when Jalview starts up normally
250     // may need to adjust this if Jalview is excessively noisy ?
251     final int STDERR_SETUPLINES = 50;
252
253     // thread monitors stderr - bails after SETUP_TIMEOUT or when
254     // STDERR_SETUPLINES have been read
255     Thread runner = new Thread(new Runnable()
256     {
257       @Override
258       public void run()
259       {
260         String ln = null;
261         int count = 0;
262         try
263         {
264           while ((ln = worker.getErrorReader().readLine()) != null)
265           {
266             System.out.println(ln);
267             successfulCMDs.add(ln);
268             if (++count > STDERR_SETUPLINES)
269             {
270               break;
271             }
272           }
273         } catch (Exception e)
274         {
275           System.err.println(
276                   "Unexpected Exception reading stderr from the Jalview process");
277           e.printStackTrace();
278         }
279       }
280     });
281     long t = System.currentTimeMillis() + SETUP_TIMEOUT;
282     runner.start();
283     while (!runner.isInterrupted() && System.currentTimeMillis() < t)
284     {
285       try
286       {
287         Thread.sleep(500);
288       } catch (InterruptedException e)
289       {
290       }
291     }
292     runner.interrupt();
293     if (worker != null && worker.exit == null)
294     {
295       worker.interrupt();
296       Thread.currentThread().interrupt();
297       worker.process.destroy();
298     }
299   }
300
301   @Test(groups = { "Functional" }, dataProvider = "allInputOperationsData")
302   public void testAllInputOperations(String expectedString,
303           String failureMsg)
304   {
305     Assert.assertTrue(successfulCMDs.contains(expectedString), failureMsg);
306   }
307
308   @Test(
309     groups =
310     { "Functional" },
311     dataProvider = "headlessModeOutputOperationsData")
312   public void testHeadlessModeOutputOperations(String harg, String type,
313           String fileName, boolean withAWT, int expectedMinFileSize,
314           int timeout)
315   {
316     String cmd = harg + type + " " + fileName;
317     // System.out.println(">>>>>>>>>>>>>>>> Command : " + cmd);
318     File file = new File(fileName);
319     file.deleteOnExit();
320     Worker worker = getJalviewDesktopRunner(withAWT, cmd, timeout);
321     assertNotNull(worker, "worker is null");
322     String msg = "Didn't create an output" + type + " file.[" + harg + "]";
323     assertTrue(file.exists(), msg);
324     FileAssert.assertFile(file, msg);
325     FileAssert.assertMinLength(file, expectedMinFileSize);
326     if (worker != null && worker.exit == null)
327     {
328       worker.interrupt();
329       Thread.currentThread().interrupt();
330       worker.process.destroy();
331       Assert.fail("Jalview did not exit after " + type
332               + " generation (try running test again to verify - timeout at "
333               + timeout + "ms). [" + harg + "]");
334     }
335     file.delete();
336   }
337
338   @DataProvider(name = "allInputOperationsData")
339   public Object[][] getHeadlessModeInputParams()
340   {
341     return new Object[][] {
342         // headless mode input operations
343         { "CMD [-colour zappo] executed successfully!",
344             "Failed command : -colour zappo" },
345         { "CMD [-props test/jalview/bin/testProps.jvprops] executed successfully!",
346             "Failed command : -props File" },
347         { "CMD [-sortbytree] executed successfully!",
348             "Failed command : -sortbytree" },
349         { "CMD [-jabaws http://www.compbio.dundee.ac.uk/jabaws] executed successfully!",
350             "Failed command : -jabaws http://www.compbio.dundee.ac.uk/jabaws" },
351         { "CMD [-open examples/uniref50.fa] executed successfully!",
352             "Failed command : -open examples/uniref50.fa" },
353         { "CMD [-nosortbytree] executed successfully!",
354             "Failed command : -nosortbytree" },
355         { "CMD [-features examples/testdata/plantfdx.features]  executed successfully!",
356             "Failed command : -features examples/testdata/plantfdx.features" },
357         { "CMD [-annotations examples/testdata/plantfdx.annotations] executed successfully!",
358             "Failed command : -annotations examples/testdata/plantfdx.annotations" },
359         { "CMD [-tree examples/testdata/uniref50_test_tree] executed successfully!",
360             "Failed command : -tree examples/testdata/uniref50_test_tree" },
361         // non headless mode input operations
362         { "CMD [-nousagestats] executed successfully!",
363             "Failed command : -nousagestats" },
364         { "CMD [-noquestionnaire] executed successfully!",
365             "Failed command : -noquestionnaire" } };
366   }
367
368   @DataProvider(name = "headlessModeOutputOperationsData")
369   public static Object[][] getHeadlessModeOutputParams()
370   {
371     // JBPNote: I'm not clear why need to specify full path for output file
372     // when running tests on build server, but we will keep this patch for now
373     // since it works.
374     // https://issues.jalview.org/browse/JAL-1889?focusedCommentId=21609&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-21609
375     String workingDir = "test/jalview/bin/";
376     return new Object[][] {
377         //
378         { "nodisplay -open examples/uniref50.fa", " -eps",
379             workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
380             TEST_TIMEOUT },
381         { "nodisplay -open examples/uniref50.fa", " -eps",
382             workingDir + "test_uniref50_out.eps", false, MINFILESIZE_BIG,
383             TEST_TIMEOUT },
384         { "nogui -open examples/uniref50.fa", " -eps",
385             workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
386             TEST_TIMEOUT },
387         { "nogui -open examples/uniref50.fa", " -eps",
388             workingDir + "test_uniref50_out.eps", false, MINFILESIZE_BIG,
389             TEST_TIMEOUT },
390         { "headless -open examples/uniref50.fa", " -eps",
391             workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
392             TEST_TIMEOUT },
393         { "headless -open examples/uniref50.fa", " -svg",
394             workingDir + "test_uniref50_out.svg", false, MINFILESIZE_BIG,
395             TEST_TIMEOUT },
396         { "headless -open examples/uniref50.fa", " -png",
397             workingDir + "test_uniref50_out.png", true, MINFILESIZE_BIG,
398             TEST_TIMEOUT },
399         { "headless -open examples/uniref50.fa", " -html",
400             workingDir + "test_uniref50_out.html", true, MINFILESIZE_BIG,
401             TEST_TIMEOUT },
402         { "headless -open examples/uniref50.fa", " -fasta",
403             workingDir + "test_uniref50_out.mfa", true, MINFILESIZE_SMALL,
404             TEST_TIMEOUT },
405         { "headless -open examples/uniref50.fa", " -clustal",
406             workingDir + "test_uniref50_out.aln", true, MINFILESIZE_SMALL,
407             TEST_TIMEOUT },
408         { "headless -open examples/uniref50.fa", " -msf",
409             workingDir + "test_uniref50_out.msf", true, MINFILESIZE_SMALL,
410             TEST_TIMEOUT },
411         { "headless -open examples/uniref50.fa", " -pileup",
412             workingDir + "test_uniref50_out.aln", true, MINFILESIZE_SMALL,
413             TEST_TIMEOUT },
414         { "headless -open examples/uniref50.fa", " -pir",
415             workingDir + "test_uniref50_out.pir", true, MINFILESIZE_SMALL,
416             TEST_TIMEOUT },
417         { "headless -open examples/uniref50.fa", " -pfam",
418             workingDir + "test_uniref50_out.pfam", true, MINFILESIZE_SMALL,
419             TEST_TIMEOUT },
420         { "headless -open examples/uniref50.fa", " -blc",
421             workingDir + "test_uniref50_out.blc", true, MINFILESIZE_SMALL,
422             TEST_TIMEOUT },
423         { "headless -open examples/uniref50.fa", " -jalview",
424             workingDir + "test_uniref50_out.jvp", true, MINFILESIZE_SMALL,
425             TEST_TIMEOUT },
426         //
427     };
428   }
429 }