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