ef2f78afbbc3dcc8b003447e01d4f03709a50da2
[jalview.git] / test / jalview / bin / CommandLineOperationsNG.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.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 import org.testng.Assert;
37 import org.testng.FileAssert;
38 import org.testng.annotations.BeforeClass;
39 import org.testng.annotations.DataProvider;
40 import org.testng.annotations.Test;
41
42 import io.github.classgraph.ClassGraph;
43 import io.github.classgraph.ModuleRef;
44 import io.github.classgraph.ScanResult;
45 import jalview.gui.JvOptionPane;
46
47 public class CommandLineOperationsNG
48 {
49
50   @BeforeClass(alwaysRun = true)
51   public void setUpJvOptionPane()
52   {
53     JvOptionPane.setInteractiveMode(false);
54     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
55   }
56
57   // Note longer timeout needed on full test run than on individual tests
58   private static final int TEST_TIMEOUT = 13000;
59
60   private static final int SETUP_TIMEOUT = 9500;
61
62   private static final int MINFILESIZE_SMALL = 2096;
63
64   private static final int MINFILESIZE_BIG = 4096;
65
66   private List<String> successfulCMDs = new ArrayList<>();
67
68   /***
69    * from
70    * http://stackoverflow.com/questions/808276/how-to-add-a-timeout-value-when
71    * -using-javas-runtime-exec
72    * 
73    * @author jimp
74    * 
75    */
76   private static class Worker extends Thread
77   {
78     private final Process process;
79
80     private BufferedReader outputReader;
81
82     private BufferedReader errorReader;
83
84     private Integer exit;
85
86     private Worker(Process process)
87     {
88       this.process = process;
89     }
90
91     @Override
92     public void run()
93     {
94       try
95       {
96         exit = process.waitFor();
97       } catch (InterruptedException ignore)
98       {
99         return;
100       }
101     }
102
103     public BufferedReader getOutputReader()
104     {
105       return outputReader;
106     }
107
108     public void setOutputReader(BufferedReader outputReader)
109     {
110       this.outputReader = outputReader;
111     }
112
113     public BufferedReader getErrorReader()
114     {
115       return errorReader;
116     }
117
118     public void setErrorReader(BufferedReader errorReader)
119     {
120       this.errorReader = errorReader;
121     }
122   }
123
124   private static ClassGraph scanner = null;
125
126   private static String classpath = null;
127
128   private static String modules = null;
129
130   private static String java_exe = null;
131
132   public synchronized static String getClassPath()
133   {
134     if (scanner == null)
135     {
136       scanner = new ClassGraph();
137       ScanResult scan = scanner.scan();
138       classpath = scan.getClasspath();
139       modules = "";
140       for (ModuleRef mr : scan.getModules())
141       {
142         modules.concat(mr.getName());
143       }
144       java_exe = System.getProperty("java.home") + File.separator + "bin"
145               + File.separator + "java";
146
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     /*
166     boolean win = System.getProperty("os.name").indexOf("Win") >= 0;
167     String pwd = "";
168     try
169     {
170       Path currentRelativePath = Paths.get("");
171       pwd = currentRelativePath.toAbsolutePath().toString();
172     } catch (Exception q)
173     {
174       q.printStackTrace();
175     }
176     if (pwd == null || pwd.length() == 0)
177       pwd = ".";
178     String[] classpaths = new String[] { pwd + "/bin/main",
179         pwd + "/j11lib/*", pwd + "/resources", pwd + "/help" };
180     String classpath = String.join(win ? ";" : ":", classpaths);
181     getClassPath();
182     */
183     // Note: JAL-3065 - don't include quotes for lib/* because the arguments are
184     // not expanded by the shell
185     String classpath = getClassPath();
186     String _cmd = java_exe + " "
187             + (withAwt ? "-Djava.awt.headless=true" : "") + " -classpath "
188             + classpath
189             + ((modules != null && modules.length() > 2)
190                     ? "--add-modules=\"" + modules + "\""
191                     : "")
192             + " jalview.bin.Jalview ";
193     Process ls2_proc = null;
194     Worker worker = null;
195     try
196     {
197       cmd = " --testoutput " + cmd;
198       System.out.println("Running '" + _cmd + cmd + "'");
199       ls2_proc = Runtime.getRuntime().exec(_cmd + cmd);
200     } catch (Throwable e1)
201     {
202       e1.printStackTrace();
203     }
204     if (ls2_proc != null)
205     {
206       BufferedReader outputReader = new BufferedReader(
207               new InputStreamReader(ls2_proc.getInputStream()));
208       BufferedReader errorReader = new BufferedReader(
209               new InputStreamReader(ls2_proc.getErrorStream()));
210       worker = new Worker(ls2_proc);
211       worker.start();
212       try
213       {
214         worker.join(timeout);
215       } catch (InterruptedException e)
216       {
217         System.err.println("Thread interrupted");
218       }
219       worker.setOutputReader(outputReader);
220       worker.setErrorReader(errorReader);
221     }
222     return worker;
223   }
224
225   @Test(groups = { "Functional", "testTask1" })
226   public void reportCurrentWorkingDirectory()
227   {
228     try
229     {
230       Path currentRelativePath = Paths.get("");
231       String s = currentRelativePath.toAbsolutePath().toString();
232       System.out.println("Test CWD is " + s);
233     } catch (Exception q)
234     {
235       q.printStackTrace();
236     }
237   }
238
239   @BeforeClass(alwaysRun = true)
240   public void initialize()
241   {
242     new CommandLineOperationsNG();
243   }
244
245   @BeforeClass(alwaysRun = true)
246   public void setUpForHeadlessCommandLineInputOperations()
247           throws IOException
248   {
249     String cmds = "--headless " + "--open examples/uniref50.fa "
250             + "--sortbytree "
251             + "--props test/jalview/bin/testProps.jvprops "
252             + "--colour zappo "
253             + "--jabaws http://www.compbio.dundee.ac.uk/jabaws "
254             + "--features examples/testdata/plantfdx.features "
255             + "--annotations examples/testdata/plantfdx.annotations "
256             + "--tree examples/testdata/uniref50_test_tree "
257             + "--nousagestats ";
258     Worker worker = getJalviewDesktopRunner(true, cmds, SETUP_TIMEOUT);
259     String ln = null;
260     while ((ln = worker.getOutputReader().readLine()) != null)
261     {
262       System.out.println(ln);
263       successfulCMDs.add(ln);
264     }
265     while ((ln = worker.getErrorReader().readLine()) != null)
266     {
267       System.err.println(ln);
268     }
269   }
270
271   @BeforeClass(alwaysRun = true)
272   public void setUpForCommandLineInputOperations() throws IOException
273   {
274     String cmds = "--open examples/uniref50.fa --noquestionnaire --nousagestats";
275     final Worker worker = getJalviewDesktopRunner(false, cmds,
276             SETUP_TIMEOUT);
277
278     // number of lines expected on STDERR when Jalview starts up normally
279     // may need to adjust this if Jalview is excessively noisy ?
280     final int STDERR_SETUPLINES = 50;
281
282     // thread monitors stderr - bails after SETUP_TIMEOUT or when
283     // STDERR_SETUPLINES have been read
284     Thread runner = new Thread(new Runnable()
285     {
286       @Override
287       public void run()
288       {
289         String ln = null;
290         int count = 0;
291         try
292         {
293           while ((ln = worker.getOutputReader().readLine()) != null)
294           {
295             System.out.println(ln);
296             successfulCMDs.add(ln);
297             if (++count > STDERR_SETUPLINES)
298             {
299               break;
300             }
301           }
302         } catch (Exception e)
303         {
304           System.err.println(
305                   "Unexpected Exception reading stderr from the Jalview process");
306           e.printStackTrace();
307         }
308       }
309     });
310     long t = System.currentTimeMillis() + SETUP_TIMEOUT;
311     runner.start();
312     while (!runner.isInterrupted() && System.currentTimeMillis() < t)
313     {
314       try
315       {
316         Thread.sleep(500);
317       } catch (InterruptedException e)
318       {
319       }
320     }
321     runner.interrupt();
322     if (worker != null && worker.exit == null)
323     {
324       worker.interrupt();
325       Thread.currentThread().interrupt();
326       worker.process.destroy();
327     }
328   }
329
330   @Test(
331     groups =
332     { "Functional", "testTask1" },
333     dataProvider = "allInputOperationsData")
334   public void testAllInputOperations(String expectedString,
335           String failureMsg)
336   {
337     Assert.assertTrue(successfulCMDs.contains(expectedString),
338             failureMsg + "; was expecting '" + expectedString + "'");
339   }
340
341   @Test(
342     groups =
343     { "Functional", "testTask1" },
344     dataProvider = "headlessModeOutputOperationsData")
345   public void testHeadlessModeOutputOperations(String harg, String type,
346           String fileName, boolean withAWT, int expectedMinFileSize,
347           int timeout)
348   {
349     String cmd = harg + type + " " + fileName;
350     // System.out.println(">>>>>>>>>>>>>>>> Command : " + cmd);
351     File file = new File(fileName);
352     file.deleteOnExit();
353     Worker worker = getJalviewDesktopRunner(withAWT, cmd, timeout);
354     assertNotNull(worker, "worker is null");
355     String msg = "Didn't create an output" + type + " file '" + fileName
356             + "'. [" + cmd + "]";
357     assertTrue(file.exists(), msg);
358     FileAssert.assertFile(file, msg);
359     FileAssert.assertMinLength(file, expectedMinFileSize);
360     if (worker != null && worker.exit == null)
361     {
362       worker.interrupt();
363       Thread.currentThread().interrupt();
364       worker.process.destroy();
365       Assert.fail("Jalview did not exit after " + type
366               + " generation (try running test again to verify - timeout at "
367               + timeout + "ms). [" + harg + "]");
368     }
369     file.delete();
370   }
371
372   @Test(
373     groups =
374     { "Functional", "testTask1" },
375     dataProvider = "headlessModeOutputToStdout")
376   public void testHeadlessModeOutputToStdout(String args,
377           String comparisonFile, int timeout)
378   {
379     String cmd = args;
380     File file = new File(comparisonFile);
381     Worker worker = getJalviewDesktopRunner(true, cmd, timeout);
382     int b = -1;
383     StringBuilder sb = new StringBuilder();
384     try
385     {
386       while ((b = worker.getOutputReader().read()) != -1)
387       {
388         sb.append(Character.toChars(b));
389       }
390     } catch (IOException e)
391     {
392       Assert.fail("IOException whilst trying to read from jalview process");
393     }
394
395     String comparisonContent = null;
396     try
397     {
398       comparisonContent = new String(Files.readAllBytes(file.toPath()));
399     } catch (IOException e)
400     {
401       Assert.fail("IOException whilst trying to read comparison file");
402     }
403
404     Assert.assertEquals(sb.toString(), comparisonContent,
405             "STDOUT from jalview command did not match the comparison file");
406   }
407
408   @DataProvider(name = "allInputOperationsData")
409   public Object[][] getHeadlessModeInputParams()
410   {
411     return new Object[][] {
412         // headless mode input operations
413         { "[TESTOUTPUT] arg --colour='zappo' was set",
414             "Failed setting arg --colour" },
415         { "[TESTOUTPUT] arg --props='test/jalview/bin/testProps.jvprops' was set",
416             "Failed setting arg --props" },
417         { "[TESTOUTPUT] arg --sortbytree was set",
418             "Failed setting arg --sortbytree" },
419         { "[TESTOUTPUT] arg --jabaws='http://www.compbio.dundee.ac.uk/jabaws' was set",
420             "Failed setting arg --jabaws" },
421         { "[TESTOUTPUT] arg --open='examples/uniref50.fa' was set",
422             "Failed setting arg --open" },
423         { "[TESTOUTPUT] arg --features='examples/testdata/plantfdx.features' was set",
424             "Failed setting arg --features" },
425         { "[TESTOUTPUT] arg --annotations='examples/testdata/plantfdx.annotations' was set",
426             "Failed setting arg --annotations" },
427         { "[TESTOUTPUT] arg --tree='examples/testdata/uniref50_test_tree' was set",
428             "Failed setting arg --tree" },
429         // non headless mode input operations
430         { "[TESTOUTPUT] arg --nousagestats was set",
431             "Failed setting arg --nousagestats" },
432         { "[TESTOUTPUT] arg --noquestionnaire was set",
433             "Failed setting arg --noquestionnaire" }
434         //
435     };
436   }
437
438   @DataProvider(name = "headlessModeOutputOperationsData")
439   public static Object[][] getHeadlessModeOutputParams()
440   {
441     // JBPNote: I'm not clear why need to specify full path for output file
442     // when running tests on build server, but we will keep this patch for now
443     // since it works.
444     // https://issues.jalview.org/browse/JAL-1889?focusedCommentId=21609&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-21609
445     String workingDir = "test/jalview/bin/";
446     return new Object[][] {
447         //
448         { "--headless --open examples/uniref50.fa", " --image",
449             workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
450             TEST_TIMEOUT },
451         { "--headless --open examples/uniref50.fa", " --image",
452             workingDir + "test_uniref50_out.eps", false, MINFILESIZE_BIG,
453             TEST_TIMEOUT },
454         { "--headless --open examples/uniref50.fa", " --image",
455             workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
456             TEST_TIMEOUT },
457         { "--headless --open examples/uniref50.fa", " --image",
458             workingDir + "test_uniref50_out.eps", false, MINFILESIZE_BIG,
459             TEST_TIMEOUT },
460         { "--headless --open examples/uniref50.fa", " --image",
461             workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
462             TEST_TIMEOUT },
463         { "--headless --open examples/uniref50.fa", " --image",
464             workingDir + "test_uniref50_out.svg", false, MINFILESIZE_BIG,
465             TEST_TIMEOUT },
466         { "--headless --open examples/uniref50.fa", " --image",
467             workingDir + "test_uniref50_out.png", true, MINFILESIZE_BIG,
468             TEST_TIMEOUT },
469         { "--headless --open examples/uniref50.fa", " --image",
470             workingDir + "test_uniref50_out.html", true, MINFILESIZE_BIG,
471             TEST_TIMEOUT },
472         { "--headless --open examples/uniref50.fa", " --output",
473             workingDir + "test_uniref50_out.mfa", true, MINFILESIZE_SMALL,
474             TEST_TIMEOUT },
475         { "--headless --open examples/uniref50.fa", " --output",
476             workingDir + "test_uniref50_out.aln", true, MINFILESIZE_SMALL,
477             TEST_TIMEOUT },
478         { "--headless --open examples/uniref50.fa", " --output",
479             workingDir + "test_uniref50_out.msf", true, MINFILESIZE_SMALL,
480             TEST_TIMEOUT },
481         { "--headless --open examples/uniref50.fa", " --output",
482             workingDir + "test_uniref50_out.aln", true, MINFILESIZE_SMALL,
483             TEST_TIMEOUT },
484         { "--headless --open examples/uniref50.fa", " --output",
485             workingDir + "test_uniref50_out.pir", true, MINFILESIZE_SMALL,
486             TEST_TIMEOUT },
487         { "--headless --open examples/uniref50.fa", " --output",
488             workingDir + "test_uniref50_out.pfam", true, MINFILESIZE_SMALL,
489             TEST_TIMEOUT },
490         { "--headless --open examples/uniref50.fa", " --output",
491             workingDir + "test_uniref50_out.blc", true, MINFILESIZE_SMALL,
492             TEST_TIMEOUT },
493         { "--headless --open examples/uniref50.fa", " --output",
494             workingDir + "test_uniref50_out.jvp", true, MINFILESIZE_SMALL,
495             TEST_TIMEOUT },
496         //
497     };
498   }
499
500   @DataProvider(name = "headlessModeOutputToStdout")
501   public static Object[][] getHeadlessModeOutputToStdout()
502   {
503     // JBPNote: I'm not clear why need to specify full path for output file
504     // when running tests on build server, but we will keep this patch for now
505     // since it works.
506     // https://issues.jalview.org/browse/JAL-1889?focusedCommentId=21609&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-21609
507     String workingDir = "test/jalview/bin/";
508     return new Object[][] {
509         //
510         { "--open=examples/uniref50.fa --output=-",
511             workingDir + "/uniref50-output.fa", TEST_TIMEOUT },
512         { "--open examples/uniref50.fa --output -",
513             workingDir + "/uniref50-output.fa", TEST_TIMEOUT },
514         { "--open examples/uniref50.fa --output=[format=blc]-",
515             workingDir + "/uniref50-output.blc", TEST_TIMEOUT },
516         { "--open examples/uniref50.fa --output - --format blc",
517             workingDir + "/uniref50-output.blc", TEST_TIMEOUT },
518         //
519     };
520   }
521 }