723279d83f547399020b8bef5c4bf25425b0eed7
[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.fa_BACKUPTEST-00000001");
112     correctindexmap.put(2, "backupfilestestTemp.fa_BACKUPTEST-00000002");
113     correctindexmap.put(3, "backupfilestestTemp.fa_BACKUPTEST-00000003");
114     correctindexmap.put(4, "backupfilestestTemp.fa_BACKUPTEST-00000004");
115     correctindexmap.put(5, "backupfilestestTemp.fa_BACKUPTEST-00000005");
116     correctindexmap.put(6, "backupfilestestTemp.fa_BACKUPTEST-00000006");
117     correctindexmap.put(7, "backupfilestestTemp.fa_BACKUPTEST-00000007");
118     correctindexmap.put(8, "backupfilestestTemp.fa_BACKUPTEST-00000008");
119     correctindexmap.put(9, "backupfilestestTemp.fa_BACKUPTEST-00000009");
120     correctindexmap.put(10, "backupfilestestTemp.fa_BACKUPTEST-00000010");
121     HashMap wrongindexmap = new HashMap();
122     wrongindexmap.put(1, "backupfilestestTemp.fa_BACKUPTEST-1");
123     wrongindexmap.put(2, "backupfilestestTemp.fa_BACKUPTEST-00000002");
124     wrongindexmap.put(3, "backupfilestestTemp.fa_BACKUPTEST-00000003");
125     wrongindexmap.put(4, "backupfilestestTemp.fa_BACKUPTEST-00000004");
126     wrongindexmap.put(5, "backupfilestestTemp.fa_BACKUPTEST-00000005");
127     wrongindexmap.put(6, "backupfilestestTemp.fa_BACKUPTEST-00000006");
128     wrongindexmap.put(7, "backupfilestestTemp.fa_BACKUPTEST-00000007");
129     wrongindexmap.put(8, "backupfilestestTemp.fa_BACKUPTEST-00000008");
130     wrongindexmap.put(9, "backupfilestestTemp.fa_BACKUPTEST-00000009");
131     wrongindexmap.put(10, "backupfilestestTemp.fa_BACKUPTEST-00000010");
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.fa_BACKUPTEST-00000009");
163     correctindexmap.put(10, "backupfilestestTemp.fa_BACKUPTEST-00000010");
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.fa_BACKUPTEST-00000001");
194     correctindexmap.put(2, "backupfilestestTemp.fa_BACKUPTEST-00000002");
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 = getBackupFiles(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(String f, String s, int i)
290   {
291     TreeMap<Integer, File> bfTreeMap = BackupFiles.getBackupFilesAsTreeMap(f,
292             s, i);
293     File[] backupFiles = new File[bfTreeMap.size()];
294     bfTreeMap.values().toArray(backupFiles);
295     return backupFiles;
296   }
297
298   private static File[] getBackupFiles()
299   {
300     return getBackupFiles(newFile, suffix, digits);
301   }
302
303   private static boolean checkBackupFiles(HashMap<Integer, String> indexmap)
304           throws IOException
305   {
306     TreeMap<Integer, File> map = BackupFiles.getBackupFilesAsTreeMap(newFile,
307             suffix, digits);
308     Enumeration<Integer> indexesenum = Collections
309             .enumeration(indexmap.keySet());
310     while (indexesenum.hasMoreElements())
311     {
312       int i = indexesenum.nextElement();
313       String indexfilename = indexmap.get(i);
314       if (!map.containsKey(i))
315       {
316         return false;
317       }
318       File f = map.get(i);
319       if (!filesContentEqual(newFile, f.getPath()))
320       {
321         return false;
322       }
323       map.remove(i);
324       if (f == null)
325       {
326         return false;
327       }
328       if (!f.getName().equals(indexfilename))
329       {
330         return false;
331       }
332     }
333     // should be nothing left in map
334     if (map.size() > 0)
335     {
336       return false;
337     }
338
339     return true;
340   }
341
342   private static boolean checkBackupFiles(int[] indexes) throws IOException
343   {
344     TreeMap<Integer, File> map = BackupFiles.getBackupFilesAsTreeMap(newFile,
345             suffix, digits);
346     for (int m = 0; m < indexes.length; m++)
347     {
348       int i = indexes[m];
349       if (!map.containsKey(i))
350       {
351         return false;
352       }
353       File f = map.get(i);
354       if (!filesContentEqual(newFile, f.getPath()))
355       {
356         return false;
357       }
358       map.remove(i);
359       if (f == null)
360       {
361         return false;
362       }
363       // check the filename -- although this uses the same code to forumulate the filename so not much of a test!
364       String filename = BackupFilenameParts.getBackupFilename(i,
365               newBasename + testExt, suffix, digits);
366       if (!filename.equals(f.getName()))
367       {
368         System.out.println("Supposed filename '" + filename
369                 + "' not equal to actual filename '" + f.getName() + "'");
370         return false;
371       }
372     }
373     // should be nothing left in map
374     if (map.size() > 0)
375     {
376       return false;
377     }
378
379     return true;
380   }
381
382   private static String[] getBackupFilesAsStrings()
383   {
384     File[] files = getBackupFiles(newFile, suffix, digits);
385     String[] filenames = new String[files.length];
386     for (int i = 0; i < files.length; i++)
387     {
388       filenames[i] = files[i].getPath();
389     }
390     return filenames;
391   }
392
393   public static boolean sequencesEqual(SequenceI s1, SequenceI s2) {
394     if (s1 == null && s2 == null) {
395       return true;
396     } else if (s1 == null || s2 == null) {
397       return false;
398     }
399     return (s1.getName().equals(s2.getName())
400             && s1.getDescription().equals(s2.getDescription())
401             && Arrays.equals(s1.getSequence(), s2.getSequence()));
402   }
403
404   public static boolean filesContentEqual(String fileName1,
405           String fileName2) throws IOException
406   {
407     Path file1 = Paths.get(fileName1);
408     Path file2 = Paths.get(fileName2);
409     byte[] bytes1 = Files.readAllBytes(file1);
410     byte[] bytes2 = Files.readAllBytes(file2);
411     return Arrays.equals(bytes1, bytes2);
412   }
413
414 }