KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > types > selectors > ModifiedSelectorTest


1 /*
2  * Copyright 2003-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17
18 package org.apache.tools.ant.types.selectors;
19
20
21 // Java
22
import java.io.File JavaDoc;
23 import java.io.FileWriter JavaDoc;
24 import java.util.Comparator JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.text.RuleBasedCollator JavaDoc;
27
28 // Ant
29
import org.apache.tools.ant.BuildException;
30 import org.apache.tools.ant.types.Parameter;
31
32 // The classes to test
33
import org.apache.tools.ant.types.selectors.modifiedselector.*;
34
35
36 /**
37  * Unit tests for ModifiedSelector.
38  *
39  * @version 2003-09-13
40  * @since Ant 1.6
41  */

42 public class ModifiedSelectorTest extends BaseSelectorTest {
43
44     /** Package of the CacheSelector classes. */
45     private static String JavaDoc pkg = "org.apache.tools.ant.types.selectors.modifiedselector";
46
47
48     public ModifiedSelectorTest(String JavaDoc name) {
49         super(name);
50     }
51
52
53     /**
54      * Factory method from base class. This should be overriden in child
55      * classes to return a specific Selector class (like here).
56      */

57     public BaseSelector getInstance() {
58         return new ModifiedSelector();
59     }
60
61
62     /** Test right use of cache names. */
63     public void testValidateWrongCache() {
64         String JavaDoc name = "this-is-not-a-valid-cache-name";
65         try {
66             ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName();
67             cacheName.setValue(name);
68             fail("CacheSelector.CacheName accepted invalid value.");
69         } catch (BuildException be) {
70             assertEquals(name + " is not a legal value for this attribute",
71                          be.getMessage());
72         }
73     }
74
75
76     /** Test right use of cache names. */
77     public void testValidateWrongAlgorithm() {
78         String JavaDoc name = "this-is-not-a-valid-algorithm-name";
79         try {
80             ModifiedSelector.AlgorithmName algoName
81                 = new ModifiedSelector.AlgorithmName();
82             algoName.setValue(name);
83             fail("CacheSelector.AlgorithmName accepted invalid value.");
84         } catch (BuildException be) {
85             assertEquals(name + " is not a legal value for this attribute",
86                          be.getMessage());
87         }
88     }
89
90
91     /** Test right use of comparator names. */
92     public void testValidateWrongComparator() {
93         String JavaDoc name = "this-is-not-a-valid-comparator-name";
94         try {
95             ModifiedSelector.ComparatorName compName
96                 = new ModifiedSelector.ComparatorName();
97             compName.setValue(name);
98             fail("ModifiedSelector.ComparatorName accepted invalid value.");
99         } catch (BuildException be) {
100             assertEquals(name + " is not a legal value for this attribute",
101                          be.getMessage());
102         }
103     }
104
105
106     /**
107      * Propertycache must have a set 'cachefile' attribute.
108      * The default in ModifiedSelector "cache.properties" is set by the selector.
109      */

110     public void testPropcacheInvalid() {
111         Cache cache = new PropertiesfileCache();
112         if (cache.isValid())
113             fail("PropertyfilesCache does not check its configuration.");
114     }
115
116
117     /**
118      * Tests whether the seldirs attribute is used.
119      */

120     public void testSeldirs() {
121         ModifiedSelector s = (ModifiedSelector)getSelector();
122         try {
123             makeBed();
124
125             StringBuffer JavaDoc sbTrue = new StringBuffer JavaDoc();
126             StringBuffer JavaDoc sbFalse = new StringBuffer JavaDoc();
127             for (int i=0; i<filenames.length; i++) {
128                 if (files[i].isDirectory()) {
129                     sbTrue.append("T");
130                     sbFalse.append("F");
131                 } else {
132                     sbTrue.append("T");
133                     sbFalse.append("T");
134                 }
135             }
136
137
138             s.setSeldirs(true);
139             performTests(s, sbTrue.toString());
140             s.getCache().delete();
141
142             s.setSeldirs(false);
143             performTests(s, sbFalse.toString());
144             s.getCache().delete();
145
146         } finally {
147             cleanupBed();
148             if (s!=null) s.getCache().delete();
149         }
150     }
151
152
153     /**
154      * Complex test scenario using default values (DigestAlgorithm with MD5,
155      * PropertiesfileCache with file=cache.properties, EqualComparator
156      * and update=true). <ol>
157      * <li> try fist time --> should select all </li>
158      * <li> try second time --> should select no files (only directories) </li>
159      * <li> modify timestamp of one file and content of a nother one </li>
160      * <li> try third time --> should select only the file with modified
161      * content </li>
162      */

163     public void testScenario1() {
164         BFT bft = null;
165         ModifiedSelector s = null;
166         try {
167             //
168
// ***** initialize test environment (called "bed") *****
169
//
170
makeBed();
171             String JavaDoc results = null;
172
173             // Configure the selector - only defaults are used
174
s = (ModifiedSelector)getSelector();
175
176             //
177
// ***** First Run *****
178
// the first call should get all files, because nothing is in
179
// the cache
180
//
181
performTests(s, "TTTTTTTTTTTT");
182
183             //
184
// ***** Second Run *****
185
// the second call should get no files, because no content
186
// has changed
187
//
188
performTests(s, "TFFFFFFFFFFT");
189
190             //
191
// ***** make some files dirty *****
192
//
193

194             // these files are made dirty --> 3+4 with different content
195
String JavaDoc f2name = "tar/bz2/asf-logo-huge.tar.bz2";
196             String JavaDoc f3name = "asf-logo.gif.md5";
197             String JavaDoc f4name = "copy.filterset.filtered";
198
199             // AccessObject to the test-Ant-environment
200
bft = new BFT();
201             // give some values (via property file) to that environment
202
bft.writeProperties("f2name="+f2name);
203             bft.writeProperties("f3name="+f3name);
204             bft.writeProperties("f4name="+f4name);
205             // call the target for making the files dirty
206
bft.doTarget("modifiedselectortest-makeDirty");
207
208
209             //
210
// ***** Third Run *****
211
// third call should get only those files, which CONTENT changed
212
// (no timestamp changes required!)
213
results = selectionString(s);
214
215             //
216
// ***** Check the result *****
217
//
218

219             // Mark all files which should be selected as (T)rue and all others
220
// as (F)alse. Directories are always selected so they always are
221
// (T)rue.
222
StringBuffer JavaDoc expected = new StringBuffer JavaDoc();
223             for (int i=0; i<filenames.length; i++) {
224                 String JavaDoc ch = "F";
225                 if (files[i].isDirectory()) ch = "T";
226                 // f2name shouldn't be selected: only timestamp has changed!
227
if (filenames[i].equalsIgnoreCase(f3name)) ch = "T";
228                 if (filenames[i].equalsIgnoreCase(f4name)) ch = "T";
229                 expected.append(ch);
230             }
231
232             assertEquals(
233                 "Wrong files selected. Differing files: " // info text
234
+ resolve(diff(expected.toString(), results)), // list of files
235
expected.toString(), // expected result
236
results // result
237
);
238
239         } finally {
240             // cleanup the environment
241
cleanupBed();
242             if (s!=null) s.getCache().delete();
243             if (bft!=null) bft.deletePropertiesfile();
244         }
245     }
246
247
248
249     /**
250      * This scenario is based on scenario 1, but does not use any
251      * default value and its based on <custom> selector. Used values are:<ul>
252      * <li><b>Cache: </b> Propertyfile,
253      * cachefile={java.io.tmpdir}/mycache.txt </li>
254      * <li><b>Algorithm: </b> Digest
255      * algorithm=SHA, Provider=null </li>
256      * <li><b>Comparator: </b> java.text.RuleBasedCollator
257      * <li><b>Update: </b> true </li>
258      */

259     public void testScenario2() {
260         ExtendSelector s = new ExtendSelector();
261         BFT bft = new BFT();
262         String JavaDoc cachefile = System.getProperty("java.io.tmpdir")+"/mycache.txt";
263         try {
264             makeBed();
265
266             s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
267
268             s.addParam(createParam("cache.cachefile", cachefile));
269             //s.addParam(createParam("algorithm.provider","---")); // i don't know any valid
270
s.addParam(createParam("cache","propertyfile"));
271             s.addParam(createParam("update","true"));
272             s.addParam(createParam("comparator","rule"));
273             s.addParam(createParam("algorithm.name","sha"));
274             s.addParam(createParam("algorithm","digest"));
275
276             // first and second run
277
performTests(s, "TTTTTTTTTTTT");
278             performTests(s, "TFFFFFFFFFFT");
279             // make dirty
280
String JavaDoc f2name = "tar/bz2/asf-logo-huge.tar.bz2";
281             String JavaDoc f3name = "asf-logo.gif.md5";
282             String JavaDoc f4name = "copy.filterset.filtered";
283             bft.writeProperties("f2name="+f2name);
284             bft.writeProperties("f3name="+f3name);
285             bft.writeProperties("f4name="+f4name);
286             bft.doTarget("modifiedselectortest-makeDirty");
287             // third run
288
String JavaDoc results = selectionString(s);
289             StringBuffer JavaDoc expected = new StringBuffer JavaDoc();
290             for (int i=0; i<filenames.length; i++) {
291                 String JavaDoc ch = "F";
292                 if (files[i].isDirectory()) ch = "T";
293                 if (filenames[i].equalsIgnoreCase(f3name)) ch = "T";
294                 if (filenames[i].equalsIgnoreCase(f4name)) ch = "T";
295                 expected.append(ch);
296             }
297             assertEquals(
298                 "Wrong files selected. Differing files: " // info text
299
+ resolve(diff(expected.toString(), results)), // list of files
300
expected.toString(), // expected result
301
results // result
302
);
303         } finally {
304             // cleanup the environment
305
cleanupBed();
306             (new java.io.File JavaDoc(cachefile)).delete();
307             if (bft!=null) bft.deletePropertiesfile();
308         }
309     }
310
311
312     /** Checks whether a cache file is created. */
313     public void testCreatePropertiesCacheDirect() {
314         File JavaDoc basedir = getSelector().getProject().getBaseDir();
315         File JavaDoc cachefile = new File JavaDoc(basedir, "cachefile.properties");
316
317         PropertiesfileCache cache = new PropertiesfileCache();
318         cache.setCachefile(cachefile);
319
320         cache.put("key", "value");
321         cache.save();
322
323         assertTrue("Cachefile not created.", cachefile.exists());
324
325         cache.delete();
326         assertFalse("Cachefile not deleted.", cachefile.exists());
327     }
328
329
330     /** Checks whether a cache file is created. */
331     public void testCreatePropertiesCacheViaModifiedSelector() {
332         File JavaDoc basedir = getSelector().getProject().getBaseDir();
333         File JavaDoc cachefile = new File JavaDoc(basedir, "cachefile.properties");
334         try {
335
336             // initialize test environment (called "bed")
337
makeBed();
338
339             // Configure the selector
340
ModifiedSelector s = (ModifiedSelector)getSelector();
341             s.addParam("cache.cachefile", cachefile);
342
343             ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName();
344             cacheName.setValue("propertyfile");
345             s.setCache(cacheName);
346
347             s.setUpdate(true);
348
349             // does the selection
350
String JavaDoc results = selectionString(s);
351
352             // evaluate correctness
353
assertTrue("Cache file is not created.", cachefile.exists());
354         } finally {
355             cleanupBed();
356             if (cachefile!=null) cachefile.delete();
357         }
358     }
359
360
361     /**
362      * In earlier implementations there were problems with the <i>order</i>
363      * of the <param>s. The scenario was <pre>
364      * <custom class="ModifiedSelector">
365      * <param name="cache.cachefile" value="mycache.properties" />
366      * <param name="cache" value="propertyfiles" />
367      * </custom>
368      * </pre> It was important first to set the cache and then to set
369      * the cache's configuration parameters. That results in the reorganized
370      * configure() method of ModifiedSelector. This testcase tests that.
371      */

372     public void testCreatePropertiesCacheViaCustomSelector() {
373         File JavaDoc cachefile = org.apache.tools.ant.util.FileUtils.newFileUtils()
374                          .createTempFile("tmp-cache-", ".properties", null);
375         try {
376             // initialize test environment (called "bed")
377
makeBed();
378
379             // Configure the selector
380

381             ExtendSelector s = new ExtendSelector();
382             s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
383             s.addParam(createParam("update", "true"));
384             s.addParam(createParam("cache.cachefile", cachefile.getAbsolutePath()));
385             s.addParam(createParam("cache", "propertyfile"));
386
387             // does the selection
388
String JavaDoc results = selectionString(s);
389
390             // evaluate correctness
391
assertTrue("Cache file is not created.", cachefile.exists());
392         } finally {
393             cleanupBed();
394             if (cachefile!=null) cachefile.delete();
395         }
396     }
397
398
399     public void testEqualComparatorViaSelector() {
400         ModifiedSelector s = (ModifiedSelector)getSelector();
401         ModifiedSelector.ComparatorName compName = new ModifiedSelector.ComparatorName();
402         compName.setValue("equal");
403         s.setComparator(compName);
404         try {
405             performTests(s, "TTTTTTTTTTTT");
406         } finally {
407             s.getCache().delete();
408         }
409     }
410
411
412     public void testRuleComparatorViaSelector() {
413         ModifiedSelector s = (ModifiedSelector)getSelector();
414         ModifiedSelector.ComparatorName compName = new ModifiedSelector.ComparatorName();
415         compName.setValue("rule");
416         s.setComparator(compName);
417         try {
418             performTests(s, "TTTTTTTTTTTT");
419         } finally {
420             s.getCache().delete();
421         }
422     }
423
424
425     public void testHashvalueAlgorithm() {
426         HashvalueAlgorithm algo = new HashvalueAlgorithm();
427         doTest(algo);
428     }
429
430     public void testDigestAlgorithmMD5() {
431         DigestAlgorithm algo = new DigestAlgorithm();
432         algo.setAlgorithm("MD5");
433         doTest(algo);
434     }
435
436     public void testDigestAlgorithmSHA() {
437         DigestAlgorithm algo = new DigestAlgorithm();
438         algo.setAlgorithm("SHA");
439         doTest(algo);
440     }
441
442
443     public void testPropertyfileCache() {
444         PropertiesfileCache cache = new PropertiesfileCache();
445         File JavaDoc cachefile = new File JavaDoc("cache.properties");
446         cache.setCachefile(cachefile);
447         doTest(cache);
448         assertFalse("Cache file not deleted.", cachefile.exists());
449     }
450
451
452     public void testEqualComparator() {
453         EqualComparator comp = new EqualComparator();
454         doTest(comp);
455     }
456
457
458     public void testRuleComparator() {
459         RuleBasedCollator JavaDoc comp = (RuleBasedCollator JavaDoc)RuleBasedCollator.getInstance();
460         doTest(comp);
461     }
462
463
464     public void testScenarioCoreSelectorDefaults() {
465         doScenarioTest("modifiedselectortest-scenario-coreselector-defaults", "cache.properties");
466     }
467
468
469
470     public void testSceanrioCoreSelectorSettings() {
471         doScenarioTest("modifiedselectortest-scenario-coreselector-settings", "core.cache.properties");
472     }
473
474
475     public void testScenarioCustomSelectorSettings() {
476         doScenarioTest("modifiedselectortest-scenario-customselector-settings", "core.cache.properties");
477     }
478
479
480     public void doScenarioTest(String JavaDoc target, String JavaDoc cachefilename) {
481         BFT bft = new BFT();
482         bft.setUp();
483         File JavaDoc basedir = bft.getProject().getBaseDir();
484         File JavaDoc cachefile = new File JavaDoc(basedir, cachefilename);
485         try {
486             // do the actions
487
bft.doTarget("modifiedselectortest-scenario-clean");
488             bft.doTarget(target);
489
490             // the directories to check
491
File JavaDoc to1 = new File JavaDoc(basedir, "selectortest/to-1");
492             File JavaDoc to2 = new File JavaDoc(basedir, "selectortest/to-2");
493             File JavaDoc to3 = new File JavaDoc(basedir, "selectortest/to-3");
494
495             // do the checks
496
assertTrue("Cache file not created.", cachefile.exists());
497             assertTrue("Not enough files copied on first time.", to1.list().length>5);
498             assertTrue("Too much files copied on second time.", to2.list().length==0);
499             assertTrue("Too much files copied on third time.", to3.list().length==2);
500         // don't catch the JUnit exceptions
501
} finally {
502             bft.doTarget("modifiedselectortest-scenario-clean");
503             bft.deletePropertiesfile();
504             bft.tearDown();
505             cachefile.delete();
506         }
507     }
508
509
510     // ==================== Test interface semantic ===================
511

512
513     /**
514      * This method does some common test for algorithm implementations.
515      * An algorithm must return always the same value for the same file and
516      * it must not return <i>null</i>.
517      *
518      * @param algo configured test object
519      */

520     protected void doTest(Algorithm algo) {
521         assertTrue("Algorithm not proper configured.", algo.isValid());
522         try {
523             makeBed();
524
525             for (int i=0; i<files.length; i++) {
526                 File JavaDoc file = files[i]; // must not be a directory
527
if (file.isFile()) {
528                     // get the Hashvalues
529
String JavaDoc hash1 = algo.getValue(file);
530                     String JavaDoc hash2 = algo.getValue(file);
531                     String JavaDoc hash3 = algo.getValue(file);
532                     String JavaDoc hash4 = algo.getValue(file);
533                     String JavaDoc hash5 = algo.getValue(new File JavaDoc(file.getAbsolutePath()));
534
535                     // Assert !=null and equality
536
assertNotNull("Hashvalue was null for "+file.getAbsolutePath(), hash1);
537                     assertNotNull("Hashvalue was null for "+file.getAbsolutePath(), hash2);
538                     assertNotNull("Hashvalue was null for "+file.getAbsolutePath(), hash3);
539                     assertNotNull("Hashvalue was null for "+file.getAbsolutePath(), hash4);
540                     assertNotNull("Hashvalue was null for "+file.getAbsolutePath(), hash5);
541                     assertEquals("getHashvalue() returned different value for "+file.getAbsolutePath(), hash1, hash2);
542                     assertEquals("getHashvalue() returned different value for "+file.getAbsolutePath(), hash1, hash3);
543                     assertEquals("getHashvalue() returned different value for "+file.getAbsolutePath(), hash1, hash4);
544                     assertEquals("getHashvalue() returned different value for "+file.getAbsolutePath(), hash1, hash5);
545                 }//if-isFile
546
}//for
547
} finally {
548             cleanupBed();
549         }
550     }
551
552
553     /**
554      * This method does some common test for cache implementations.
555      * A cache must return a stored value and a valid iterator.
556      * After calling the delete() the cache must be empty.
557      *
558      * @param algo configured test object
559      */

560     protected void doTest(Cache cache) {
561         assertTrue("Cache not proper configured.", cache.isValid());
562
563         String JavaDoc key1 = "key1";
564         String JavaDoc value1 = "value1";
565         String JavaDoc key2 = "key2";
566         String JavaDoc value2 = "value2";
567
568         // given cache must be empty
569
Iterator JavaDoc it1 = cache.iterator();
570         assertFalse("Cache is not empty", it1.hasNext());
571
572         // cache must return a stored value
573
cache.put(key1, value1);
574         cache.put(key2, value2);
575         assertEquals("cache returned wrong value", value1, cache.get(key1));
576         assertEquals("cache returned wrong value", value2, cache.get(key2));
577
578         // test the iterator
579
Iterator JavaDoc it2 = cache.iterator();
580         Object JavaDoc returned = it2.next();
581         boolean ok = (key1.equals(returned) || key2.equals(returned));
582         String JavaDoc msg = "Iterator returned unexpected value."
583                    + " key1.equals(returned)="+key1.equals(returned)
584                    + " key2.equals(returned)="+key2.equals(returned)
585                    + " returned="+returned
586                    + " ok="+ok;
587         assertTrue(msg, ok);
588
589         // clear the cache
590
cache.delete();
591         Iterator JavaDoc it3 = cache.iterator();
592         assertFalse("Cache is not empty", it1.hasNext());
593     }
594
595
596     /**
597      * This method does some common test for comparator implementations.
598      *
599      * @param algo configured test object
600      */

601     protected void doTest(Comparator JavaDoc comp) {
602         Object JavaDoc o1 = new String JavaDoc("string1");
603         Object JavaDoc o2 = new String JavaDoc("string2");
604         Object JavaDoc o3 = new String JavaDoc("string2"); // really "2"
605

606         assertTrue("Comparator gave wrong value.", comp.compare(o1, o2) != 0);
607         assertTrue("Comparator gave wrong value.", comp.compare(o1, o3) != 0);
608         assertTrue("Comparator gave wrong value.", comp.compare(o2, o3) == 0);
609     }
610
611
612     // ======================== Helper methods ========================
613

614
615     private Parameter createParam(String JavaDoc name, String JavaDoc value) {
616         Parameter p = new Parameter();
617         p.setName(name);
618         p.setValue(value);
619         return p;
620     }
621
622
623     private class BFT extends org.apache.tools.ant.BuildFileTest {
624         BFT() { super("nothing"); }
625         BFT(String JavaDoc name) {
626             super(name);
627         }
628         String JavaDoc propfile = "ModifiedSelectorTest.properties";
629
630         boolean isConfigured = false;
631
632         public void setUp() {
633             configureProject("src/etc/testcases/types/selectors.xml");
634             isConfigured = true;
635         }
636
637         public void tearDown() { }
638
639         public void doTarget(String JavaDoc target) {
640             if (!isConfigured) setUp();
641             executeTarget(target);
642         }
643
644         public void writeProperties(String JavaDoc line) {
645             if (!isConfigured) setUp();
646             File JavaDoc dir = getProject().getBaseDir();
647             File JavaDoc file = new File JavaDoc(dir, propfile);
648             try {
649                 java.io.FileWriter JavaDoc out =
650                     new java.io.FileWriter JavaDoc(file.getAbsolutePath(), true);
651                 out.write(line);
652                 out.write(System.getProperty("line.separator"));
653                 out.flush();
654                 out.close();
655             } catch (Exception JavaDoc e) {
656                 e.printStackTrace();
657             }
658         }
659
660         public void deletePropertiesfile() {
661             if (!isConfigured) setUp();
662             new File JavaDoc(getProject().getBaseDir(), propfile).delete();
663         }
664
665         public org.apache.tools.ant.Project getProject() {
666             return super.getProject();
667         }
668     }//class-BFT
669

670 }//class-ModifiedSelectorTest
671
Popular Tags