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