a78936e7bc1d287a146367cb14a8ce53f1fb833a
[jalview.git] / test / jalview / io / BackupFilesTest.java
1 package jalview.io;
2
3 import jalview.bin.Cache;
4 import jalview.datamodel.AlignmentI;
5 import jalview.datamodel.Sequence;
6 import jalview.datamodel.SequenceI;
7 import jalview.gui.AlignFrame;
8 import jalview.gui.JvOptionPane;
9
10 import java.io.File;
11 import java.io.IOException;
12 import java.nio.file.Files;
13 import java.nio.file.Path;
14 import java.nio.file.Paths;
15 import java.util.Arrays;
16 import java.util.Collections;
17 import java.util.Enumeration;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.TreeMap;
21
22 import org.testng.Assert;
23 import org.testng.annotations.AfterClass;
24 import org.testng.annotations.BeforeClass;
25 import org.testng.annotations.Test;
26
27 public class BackupFilesTest
28 {
29   @BeforeClass(alwaysRun = true)
30   public void setUpJvOptionPane()
31   {
32     JvOptionPane.setInteractiveMode(false);
33     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
34   }
35
36   private static boolean actuallyDeleteTmpFiles = true;
37   private static String testDir = "examples";
38
39   private static String testBasename = "backupfilestest";
40
41   private static String testExt = ".fa";
42
43   private static String testFilename = testBasename + testExt;
44
45
46   private static String testFile = testDir + File.separatorChar
47           + testFilename;
48
49   private static String newBasename = testBasename + "Temp";
50
51   private static String newFilename = newBasename + testExt;
52
53   private static String newFile = testDir + File.separatorChar
54           + newFilename;
55
56   private static String sequenceName = "BACKUP_FILES";
57
58   private static String sequenceDescription = "backupfiles";
59
60   private static String sequenceData = "AAAARG";
61
62   private static String suffix = "_BACKUPTEST-%n";
63
64   private static int digits = 8;
65
66   private static int rollMax = 2;
67
68   private AlignFrame af;
69
70   // read and save with backupfiles disabled
71   @Test(groups = { "Functional" })
72   public void noBackupsEnabledTest() throws Exception
73   {
74     // set BACKUPFILES_ENABLED to false (i.e. turn off BackupFiles feature -- no
75     // backup files to be made when saving)
76     setBackupFilesOptions(false, true, true);
77
78     // init the newFile and backups (i.e. make sure newFile exists on its own
79     // and has no backups
80     initNewFileForTesting();
81
82     // now save again
83     save();
84
85     // check no backup files
86     File[] backupFiles = getBackupFiles();
87     Assert.assertTrue(backupFiles.length == 0);
88   }
89
90   // save keeping all backup files
91   @Test(groups = { "Functional" })
92   public void backupsEnabledNoRollMaxTest() throws Exception
93   {
94     // Enable BackupFiles and set noMax so all backupfiles get kept
95     setBackupFilesOptions(true, false, true);
96
97     // init the newFile and backups (i.e. make sure newFile exists on its own
98     // and has no backups)
99     initNewFileForTesting();
100
101     // now save a few times again. No rollMax so should have more than two
102     // backup files
103     int numSaves = 10;
104     for (int i = 0; i < numSaves; i++)
105     {
106       save();
107     }
108
109     // check 10 backup files
110     HashMap correctindexmap = new HashMap();
111     correctindexmap.put(1, "backupfilestestTemp_BACKUPTEST-00000001.fa");
112     correctindexmap.put(2, "backupfilestestTemp_BACKUPTEST-00000002.fa");
113     correctindexmap.put(3, "backupfilestestTemp_BACKUPTEST-00000003.fa");
114     correctindexmap.put(4, "backupfilestestTemp_BACKUPTEST-00000004.fa");
115     correctindexmap.put(5, "backupfilestestTemp_BACKUPTEST-00000005.fa");
116     correctindexmap.put(6, "backupfilestestTemp_BACKUPTEST-00000006.fa");
117     correctindexmap.put(7, "backupfilestestTemp_BACKUPTEST-00000007.fa");
118     correctindexmap.put(8, "backupfilestestTemp_BACKUPTEST-00000008.fa");
119     correctindexmap.put(9, "backupfilestestTemp_BACKUPTEST-00000009.fa");
120     correctindexmap.put(10, "backupfilestestTemp_BACKUPTEST-00000010.fa");
121     HashMap wrongindexmap = new HashMap();
122     wrongindexmap.put(1, "backupfilestestTemp_BACKUPTEST-1.fa");
123     wrongindexmap.put(2, "backupfilestestTemp_BACKUPTEST-00000002.fa");
124     wrongindexmap.put(3, "backupfilestestTemp_BACKUPTEST-00000003.fa");
125     wrongindexmap.put(4, "backupfilestestTemp_BACKUPTEST-00000004.fa");
126     wrongindexmap.put(5, "backupfilestestTemp_BACKUPTEST-00000005.fa");
127     wrongindexmap.put(6, "backupfilestestTemp_BACKUPTEST-00000006.fa");
128     wrongindexmap.put(7, "backupfilestestTemp_BACKUPTEST-00000007.fa");
129     wrongindexmap.put(8, "backupfilestestTemp_BACKUPTEST-00000008.fa");
130     wrongindexmap.put(9, "backupfilestestTemp_BACKUPTEST-00000009.fa");
131     wrongindexmap.put(10, "backupfilestestTemp_BACKUPTEST-00000010.fa");
132     int[] indexes2 = { 3, 4, 5, 6, 7, 8, 9, 10 };
133     int[] indexes3 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
134     Assert.assertTrue(checkBackupFiles(correctindexmap));
135     Assert.assertFalse(checkBackupFiles(wrongindexmap));
136     Assert.assertFalse(checkBackupFiles(indexes2));
137     Assert.assertFalse(checkBackupFiles(indexes3));
138   }
139
140   // save keeping only the last rollMax (2) backup files
141   @Test(groups = { "Functional" })
142   public void backupsEnabledRollMaxTest() throws Exception
143   {
144     // Enable BackupFiles and set noMax so all backupfiles get kept
145     setBackupFilesOptions(true, false, false);
146
147     // init the newFile and backups (i.e. make sure newFile exists on its own
148     // and has no backups)
149     initNewFileForTesting();
150
151     // now save a few times again. No rollMax so should have more than two
152     // backup files
153     int numSaves = 10;
154     for (int i = 0; i < numSaves; i++)
155     {
156       save();
157     }
158
159     // check there are "rollMax" backup files and they are all saved correctly
160     // check 10 backup files
161     HashMap correctindexmap = new HashMap();
162     correctindexmap.put(9, "backupfilestestTemp_BACKUPTEST-00000009.fa");
163     correctindexmap.put(10, "backupfilestestTemp_BACKUPTEST-00000010.fa");
164     int[] indexes2 = { 10 };
165     int[] indexes3 = { 8, 9, 10 };
166     Assert.assertTrue(checkBackupFiles(correctindexmap));
167     Assert.assertFalse(checkBackupFiles(indexes2));
168     Assert.assertFalse(checkBackupFiles(indexes3));
169   }
170
171   // save keeping only the last rollMax (2) backup files
172   @Test(groups = { "Functional" })
173   public void backupsEnabledReverseRollMaxTest() throws Exception
174   {
175     // Enable BackupFiles and set noMax so all backupfiles get kept
176     setBackupFilesOptions(true, true, false);
177
178     // init the newFile and backups (i.e. make sure newFile exists on its own
179     // and has no backups)
180     initNewFileForTesting();
181
182     // now save a few times again. No rollMax so should have more than two
183     // backup files
184     int numSaves = 10;
185     for (int i = 0; i < numSaves; i++)
186     {
187       save();
188     }
189
190     // check there are "rollMax" backup files and they are all saved correctly
191     // check 10 backup files
192     HashMap correctindexmap = new HashMap();
193     correctindexmap.put(1, "backupfilestestTemp_BACKUPTEST-00000001.fa");
194     correctindexmap.put(2, "backupfilestestTemp_BACKUPTEST-00000002.fa");
195     int[] indexes2 = { 1 };
196     int[] indexes3 = { 1, 2, 3 };
197     Assert.assertTrue(checkBackupFiles(correctindexmap));
198     Assert.assertFalse(checkBackupFiles(indexes2));
199     Assert.assertFalse(checkBackupFiles(indexes3));
200   }
201
202   private void setBackupFilesOptions()
203   {
204     setBackupFilesOptions(true, false, false);
205   }
206
207   private void setBackupFilesOptions(boolean enabled, boolean reverse,
208           boolean noMax)
209   {
210     Cache.loadProperties("test/jalview/io/testProps.jvprops");
211
212     Cache.applicationProperties.setProperty(BackupFiles.ENABLED,
213             Boolean.toString(enabled));
214     Cache.applicationProperties.setProperty(BackupFiles.SUFFIX, suffix);
215     Cache.applicationProperties.setProperty(BackupFiles.SUFFIX_DIGITS,
216             Integer.toString(digits));
217     Cache.applicationProperties.setProperty(BackupFiles.REVERSE_ORDER,
218             Boolean.toString(reverse));
219     Cache.applicationProperties.setProperty(BackupFiles.NO_MAX,
220             Boolean.toString(noMax));
221     Cache.applicationProperties.setProperty(BackupFiles.ROLL_MAX,
222             Integer.toString(rollMax));
223     Cache.applicationProperties.setProperty(BackupFiles.CONFIRM_DELETE_OLD,
224             "false");
225   }
226
227   private void save()
228   {
229     if (af != null)
230     {
231     af.saveAlignment(newFile, jalview.io.FileFormat.Fasta);
232     }
233   }
234
235   // this runs cleanTmpFiles and then writes the newFile once as a starting
236   // point for all tests
237   private void initNewFileForTesting() throws Exception
238   {
239     cleanupTmpFiles();
240
241     AppletFormatAdapter afa = new AppletFormatAdapter();
242     AlignmentI al = afa.readFile(testFile, DataSourceType.FILE,
243             jalview.io.FileFormat.Fasta);
244     List<SequenceI> l = al.getSequences();
245
246     // check this is right
247     if (l.size() != 1)
248     {
249       throw new Exception("single sequence from '" + testFile
250               + "' not read in correctly (should be a single short sequence). List<SequenceI> size is wrong.");
251     }
252     SequenceI s = l.get(0);
253     Sequence ref = new Sequence(sequenceName, sequenceData);
254     ref.setDescription(sequenceDescription);
255     if (!sequencesEqual(s, ref))
256     {
257       throw new Exception("single sequence from '" + testFile
258               + "' not read in correctly (should be a single short sequence). SequenceI name, description or data is wrong.");
259     }
260     // save alignment file to new filename -- this doesn't test backups disabled
261     // yet as this file shouldn't already exist
262     af = new AlignFrame(al, 0, 0);
263     af.saveAlignment(newFile, jalview.io.FileFormat.Fasta);
264   }
265
266   // this deletes the newFile (if it exists) and any saved backup file for it
267   @AfterClass(alwaysRun = true)
268   private void cleanupTmpFiles()
269   {
270     File newfile = new File(newFile);
271     if (newfile.exists())
272     {
273       newfile.delete();
274     }
275     File[] tmpFiles = BackupFiles.lsBackupFiles(newFile, suffix, digits);
276     for (int i = 0; i < tmpFiles.length; i++)
277     {
278       if (actuallyDeleteTmpFiles)
279       {
280         tmpFiles[i].delete();
281       }
282       else
283       {
284         System.out.println("Pretending to delete " + tmpFiles[i].getPath());
285       }
286     }
287   }
288
289   private static File[] getBackupFiles()
290   {
291     return BackupFiles.lsBackupFiles(newFile, suffix, digits);
292   }
293
294   private static boolean checkBackupFiles(HashMap<Integer, String> indexmap)
295           throws IOException
296   {
297     TreeMap<Integer, File> map = BackupFiles.lsBackupFilesAsTreeMap(newFile,
298             suffix, digits);
299     Enumeration<Integer> indexesenum = Collections
300             .enumeration(indexmap.keySet());
301     while (indexesenum.hasMoreElements())
302     {
303       int i = indexesenum.nextElement();
304       String indexfilename = indexmap.get(i);
305       if (!map.containsKey(i))
306       {
307         return false;
308       }
309       File f = map.get(i);
310       if (!filesContentEqual(newFile, f.getPath()))
311       {
312         return false;
313       }
314       map.remove(i);
315       if (f == null)
316       {
317         return false;
318       }
319       if (!f.getName().equals(indexfilename))
320       {
321         return false;
322       }
323     }
324     // should be nothing left in map
325     if (map.size() > 0)
326     {
327       return false;
328     }
329
330     return true;
331   }
332
333   private static boolean checkBackupFiles(int[] indexes) throws IOException
334   {
335     TreeMap<Integer, File> map = BackupFiles.lsBackupFilesAsTreeMap(newFile,
336             suffix, digits);
337     for (int m = 0; m < indexes.length; m++)
338     {
339       int i = indexes[m];
340       if (!map.containsKey(i))
341       {
342         return false;
343       }
344       File f = map.get(i);
345       if (!filesContentEqual(newFile, f.getPath()))
346       {
347         return false;
348       }
349       map.remove(i);
350       if (f == null)
351       {
352         return false;
353       }
354       // check the filename -- although this uses the same code to forumulate the filename so not much of a test!
355       String filename = BackupFilenameFilter.getBackupFilename(i,
356               newBasename, suffix, digits, testExt);
357       if (!filename.equals(f.getName()))
358       {
359         System.out.println("Supposed filename '" + filename
360                 + "' not equal to actual filename '" + f.getName() + "'");
361         return false;
362       }
363     }
364     // should be nothing left in map
365     if (map.size() > 0)
366     {
367       return false;
368     }
369
370     return true;
371   }
372
373   private static String[] getBackupFilesAsStrings()
374   {
375     File[] files = BackupFiles.lsBackupFiles(newFile, suffix, digits);
376     String[] filenames = new String[files.length];
377     for (int i = 0; i < files.length; i++)
378     {
379       filenames[i] = files[i].getPath();
380     }
381     return filenames;
382   }
383
384   public static boolean sequencesEqual(SequenceI s1, SequenceI s2) {
385     if (s1 == null && s2 == null) {
386       return true;
387     } else if (s1 == null || s2 == null) {
388       return false;
389     }
390     return (s1.getName().equals(s2.getName())
391             && s1.getDescription().equals(s2.getDescription())
392             && Arrays.equals(s1.getSequence(), s2.getSequence()));
393   }
394
395   public static boolean filesContentEqual(String fileName1,
396           String fileName2) throws IOException
397   {
398     Path file1 = Paths.get(fileName1);
399     Path file2 = Paths.get(fileName2);
400     byte[] bytes1 = Files.readAllBytes(file1);
401     byte[] bytes2 = Files.readAllBytes(file2);
402     return Arrays.equals(bytes1, bytes2);
403   }
404
405 }