0001: /*
0002: * Licensed to the Apache Software Foundation (ASF) under one or more
0003: * contributor license agreements. See the NOTICE file distributed with
0004: * this work for additional information regarding copyright ownership.
0005: * The ASF licenses this file to You under the Apache License, Version 2.0
0006: * (the "License"); you may not use this file except in compliance with
0007: * the License. You may obtain a copy of the License at
0008: *
0009: * http://www.apache.org/licenses/LICENSE-2.0
0010: *
0011: * Unless required by applicable law or agreed to in writing, software
0012: * distributed under the License is distributed on an "AS IS" BASIS,
0013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014: * See the License for the specific language governing permissions and
0015: * limitations under the License.
0016: *
0017: */
0018:
0019: package org.apache.tools.ant.types.selectors;
0020:
0021: // Java
0022: import java.io.File;
0023: import java.text.RuleBasedCollator;
0024: import java.util.Comparator;
0025: import java.util.Iterator;
0026:
0027: import org.apache.tools.ant.BuildException;
0028: import org.apache.tools.ant.Project;
0029: import org.apache.tools.ant.Target;
0030: import org.apache.tools.ant.Task;
0031: import org.apache.tools.ant.types.Parameter;
0032: import org.apache.tools.ant.types.Path;
0033: import org.apache.tools.ant.types.selectors.modifiedselector.Algorithm;
0034: import org.apache.tools.ant.types.selectors.modifiedselector.Cache;
0035: import org.apache.tools.ant.types.selectors.modifiedselector.ChecksumAlgorithm;
0036: import org.apache.tools.ant.types.selectors.modifiedselector.DigestAlgorithm;
0037: import org.apache.tools.ant.types.selectors.modifiedselector.EqualComparator;
0038: import org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm;
0039: import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector;
0040: import org.apache.tools.ant.types.selectors.modifiedselector.PropertiesfileCache;
0041: import org.apache.tools.ant.util.FileUtils;
0042:
0043: /**
0044: * Unit tests for ModifiedSelector.
0045: *
0046: * @since Ant 1.6
0047: */
0048: public class ModifiedSelectorTest extends BaseSelectorTest {
0049:
0050: /** Utilities used for file operations */
0051: private static final FileUtils FILE_UTILS = FileUtils
0052: .getFileUtils();
0053:
0054: // ===================== attributes =====================
0055:
0056: /** Package of the CacheSelector classes. */
0057: private static String pkg = "org.apache.tools.ant.types.selectors.modifiedselector";
0058:
0059: /** Path where the testclasses are. */
0060: private Path testclasses = null;
0061:
0062: // ===================== constructors, factories =====================
0063:
0064: public ModifiedSelectorTest(String name) {
0065: super (name);
0066: }
0067:
0068: /**
0069: * Factory method from base class. This should be overriden in child
0070: * classes to return a specific Selector class (like here).
0071: */
0072: public BaseSelector getInstance() {
0073: return new ModifiedSelector();
0074: }
0075:
0076: // ===================== JUnit stuff =====================
0077:
0078: public void setUp() {
0079: // project reference is set in super.setUp()
0080: super .setUp();
0081: // init the testclasses path object
0082: Project prj = getProject();
0083: if (prj != null) {
0084: testclasses = new Path(prj, prj
0085: .getProperty("build.tests.value"));
0086: }
0087: }
0088:
0089: /* * /
0090: // for test only - ignore tests where we arent work at the moment
0091: public static junit.framework.Test suite() {
0092: junit.framework.TestSuite suite= new junit.framework.TestSuite();
0093: suite.addTest(new ModifiedSelectorTest("testValidateWrongCache"));
0094: return suite;
0095: }
0096: /* */
0097:
0098: // ======= testcases for the attributes and nested elements of the selector =====
0099:
0100: /** Test right use of cache names. */
0101: public void testValidateWrongCache() {
0102: String name = "this-is-not-a-valid-cache-name";
0103: try {
0104: ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName();
0105: cacheName.setValue(name);
0106: fail("CacheSelector.CacheName accepted invalid value.");
0107: } catch (BuildException be) {
0108: assertEquals(name
0109: + " is not a legal value for this attribute", be
0110: .getMessage());
0111: }
0112: }
0113:
0114: /** Test right use of cache names. */
0115: public void testValidateWrongAlgorithm() {
0116: String name = "this-is-not-a-valid-algorithm-name";
0117: try {
0118: ModifiedSelector.AlgorithmName algoName = new ModifiedSelector.AlgorithmName();
0119: algoName.setValue(name);
0120: fail("CacheSelector.AlgorithmName accepted invalid value.");
0121: } catch (BuildException be) {
0122: assertEquals(name
0123: + " is not a legal value for this attribute", be
0124: .getMessage());
0125: }
0126: }
0127:
0128: /** Test right use of comparator names. */
0129: public void testValidateWrongComparator() {
0130: String name = "this-is-not-a-valid-comparator-name";
0131: try {
0132: ModifiedSelector.ComparatorName compName = new ModifiedSelector.ComparatorName();
0133: compName.setValue(name);
0134: fail("ModifiedSelector.ComparatorName accepted invalid value.");
0135: } catch (BuildException be) {
0136: assertEquals(name
0137: + " is not a legal value for this attribute", be
0138: .getMessage());
0139: }
0140: }
0141:
0142: public void testIllegalCustomAlgorithm() {
0143: try {
0144: String algo = getAlgoName("java.lang.Object");
0145: fail("Illegal classname used.");
0146: } catch (Exception e) {
0147: assertTrue("Wrong exception type: "
0148: + e.getClass().getName(),
0149: e instanceof BuildException);
0150: assertEquals(
0151: "Wrong exception message.",
0152: "Specified class (java.lang.Object) is not an Algorithm.",
0153: e.getMessage());
0154:
0155: }
0156: }
0157:
0158: public void testNonExistentCustomAlgorithm() {
0159: boolean noExcThrown = false;
0160: try {
0161: String algo = getAlgoName("non.existent.custom.Algorithm");
0162: noExcThrown = true;
0163: } catch (Exception e) {
0164: if (noExcThrown) {
0165: fail("does 'non.existent.custom.Algorithm' really exist?");
0166: }
0167: assertTrue("Wrong exception type: "
0168: + e.getClass().getName(),
0169: e instanceof BuildException);
0170: assertEquals(
0171: "Wrong exception message.",
0172: "Specified class (non.existent.custom.Algorithm) not found.",
0173: e.getMessage());
0174:
0175: }
0176: }
0177:
0178: public void testCustomAlgorithm() {
0179: String algo = getAlgoName("org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm");
0180: assertTrue("Wrong algorithm used: " + algo, algo
0181: .startsWith("HashvalueAlgorithm"));
0182: }
0183:
0184: public void testCustomAlgorithm2() {
0185: String algo = getAlgoName("org.apache.tools.ant.types.selectors.MockAlgorithm");
0186: assertTrue("Wrong algorithm used: " + algo, algo
0187: .startsWith("MockAlgorithm"));
0188: }
0189:
0190: public void testCustomClasses() {
0191: BFT bft = new BFT();
0192: bft.setUp();
0193: try {
0194: // do the actions
0195: bft.doTarget("modifiedselectortest-customClasses");
0196: // do the checks - the buildfile stores the fileset as property
0197: String fsFullValue = bft.getProperty("fs.full.value");
0198: String fsModValue = bft.getProperty("fs.mod.value");
0199:
0200: assertNotNull("'fs.full.value' must be set.", fsFullValue);
0201: assertTrue("'fs.full.value' must not be null.", !""
0202: .equals(fsFullValue));
0203: assertTrue("'fs.full.value' must contain ant.bat.",
0204: fsFullValue.indexOf("ant.bat") > -1);
0205:
0206: assertNotNull("'fs.mod.value' must be set.", fsModValue);
0207: // must be empty according to the Mock* implementations
0208: assertTrue("'fs.mod.value' must be empty.", ""
0209: .equals(fsModValue));
0210: // don't catch the JUnit exceptions
0211: } finally {
0212: bft.doTarget("modifiedselectortest-scenario-clean");
0213: bft.deletePropertiesfile();
0214: bft.tearDown();
0215: }
0216: }
0217:
0218: public void testDelayUpdateTaskFinished() {
0219: doDelayUpdateTest(1);
0220: }
0221:
0222: public void testDelayUpdateTargetFinished() {
0223: doDelayUpdateTest(2);
0224: }
0225:
0226: public void testDelayUpdateBuildFinished() {
0227: doDelayUpdateTest(3);
0228: }
0229:
0230: public void doDelayUpdateTest(int kind) {
0231: // no check for 1<=kind<=3 - only internal use therefore check it
0232: // while development
0233:
0234: // readable form of parameter kind
0235: String[] kinds = { "task", "target", "build" };
0236:
0237: // setup the "Ant project"
0238: MockProject project = new MockProject();
0239: File base = new File("base");
0240: File file1 = new File("file1");
0241: File file2 = new File("file2");
0242:
0243: // setup the selector
0244: ModifiedSelector sel = new ModifiedSelector();
0245: sel.setProject(project);
0246: sel.setUpdate(true);
0247: sel.setDelayUpdate(true);
0248: // sorry - otherwise we will get a ClassCastException because the MockCache
0249: // is loaded by two different classloader ...
0250: sel.setClassLoader(this .getClass().getClassLoader());
0251: sel.addClasspath(testclasses);
0252:
0253: sel
0254: .setAlgorithmClass("org.apache.tools.ant.types.selectors.MockAlgorithm");
0255: sel
0256: .setCacheClass("org.apache.tools.ant.types.selectors.MockCache");
0257: sel.configure();
0258:
0259: // get the cache, so we can check our things
0260: MockCache cache = (MockCache) sel.getCache();
0261:
0262: // the test
0263: assertFalse("Cache must not be saved before 1st selection.",
0264: cache.saved);
0265: sel.isSelected(base, "file1", file1);
0266: assertFalse("Cache must not be saved after 1st selection.",
0267: cache.saved);
0268: sel.isSelected(base, "file2", file2);
0269: assertFalse("Cache must not be saved after 2nd selection.",
0270: cache.saved);
0271: switch (kind) {
0272: case 1:
0273: project.fireTaskFinished();
0274: break;
0275: case 2:
0276: project.fireTargetFinished();
0277: break;
0278: case 3:
0279: project.fireBuildFinished();
0280: break;
0281: }
0282: assertTrue("Cache must be saved after " + kinds[kind - 1]
0283: + "Finished-Event.", cache.saved);
0284:
0285: // MockCache doesnt create a file - therefore no cleanup needed
0286: }
0287:
0288: /**
0289: * Extracts the real used algorithm name from the ModifiedSelector using
0290: * its toString() method.
0291: * @param classname the classname from the algorithm to use
0292: * @return the algorithm part from the toString() (without brackets)
0293: */
0294: private String getAlgoName(String classname) {
0295: ModifiedSelector sel = new ModifiedSelector();
0296: // add the test classes to its classpath
0297: sel.addClasspath(testclasses);
0298: sel.setAlgorithmClass(classname);
0299: // let the selector do its checks
0300: sel.validate();
0301: // extract the algorithm name (and config) from the selectors output
0302: String s1 = sel.toString();
0303: int posStart = s1.indexOf("algorithm=") + 10;
0304: int posEnd = s1.indexOf(" comparator=");
0305: String algo = s1.substring(posStart, posEnd);
0306: // '<' and '>' are only used if the algorithm has properties
0307: if (algo.startsWith("<"))
0308: algo = algo.substring(1);
0309: if (algo.endsWith(">"))
0310: algo = algo.substring(0, algo.length() - 1);
0311: // return the clean value
0312: return algo;
0313: }
0314:
0315: // ================ testcases for the cache implementations ================
0316:
0317: /**
0318: * Propertycache must have a set 'cachefile' attribute.
0319: * The default in ModifiedSelector "cache.properties" is set by the selector.
0320: */
0321: public void testPropcacheInvalid() {
0322: Cache cache = new PropertiesfileCache();
0323: if (cache.isValid())
0324: fail("PropertyfilesCache does not check its configuration.");
0325: }
0326:
0327: public void testPropertyfileCache() {
0328: PropertiesfileCache cache = new PropertiesfileCache();
0329: File cachefile = new File("cache.properties");
0330: cache.setCachefile(cachefile);
0331: doTest(cache);
0332: assertFalse("Cache file not deleted.", cachefile.exists());
0333: }
0334:
0335: /** Checks whether a cache file is created. */
0336: public void testCreatePropertiesCacheDirect() {
0337: File cachefile = new File(basedir, "cachefile.properties");
0338:
0339: PropertiesfileCache cache = new PropertiesfileCache();
0340: cache.setCachefile(cachefile);
0341:
0342: cache.put("key", "value");
0343: cache.save();
0344:
0345: assertTrue("Cachefile not created.", cachefile.exists());
0346:
0347: cache.delete();
0348: assertFalse("Cachefile not deleted.", cachefile.exists());
0349: }
0350:
0351: /** Checks whether a cache file is created. */
0352: public void testCreatePropertiesCacheViaModifiedSelector() {
0353: File cachefile = new File(basedir, "cachefile.properties");
0354: try {
0355:
0356: // initialize test environment (called "bed")
0357: makeBed();
0358:
0359: // Configure the selector
0360: ModifiedSelector s = (ModifiedSelector) getSelector();
0361: s.setDelayUpdate(false);
0362: s.addParam("cache.cachefile", cachefile);
0363:
0364: ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName();
0365: cacheName.setValue("propertyfile");
0366: s.setCache(cacheName);
0367:
0368: s.setUpdate(true);
0369:
0370: // does the selection
0371: String results = selectionString(s);
0372:
0373: // evaluate correctness
0374: assertTrue("Cache file is not created.", cachefile.exists());
0375: } finally {
0376: cleanupBed();
0377: if (cachefile != null)
0378: cachefile.delete();
0379: }
0380: }
0381:
0382: /**
0383: * In earlier implementations there were problems with the <i>order</i>
0384: * of the <param>s. The scenario was <pre>
0385: * <custom class="ModifiedSelector">
0386: * <param name="cache.cachefile" value="mycache.properties" />
0387: * <param name="cache" value="propertyfiles" />
0388: * </custom>
0389: * </pre> It was important first to set the cache and then to set
0390: * the cache's configuration parameters. That results in the reorganized
0391: * configure() method of ModifiedSelector. This testcase tests that.
0392: */
0393: public void testCreatePropertiesCacheViaCustomSelector() {
0394: File cachefile = FILE_UTILS.createTempFile("tmp-cache-",
0395: ".properties", null);
0396: try {
0397: // initialize test environment (called "bed")
0398: makeBed();
0399:
0400: // Configure the selector
0401:
0402: ExtendSelector s = new ExtendSelector();
0403: s
0404: .setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
0405: s.addParam(createParam("update", "true"));
0406: s.addParam(createParam("cache.cachefile", cachefile
0407: .getAbsolutePath()));
0408: s.addParam(createParam("cache", "propertyfile"));
0409:
0410: // does the selection
0411: String results = selectionString(s);
0412:
0413: // evaluate correctness
0414: assertTrue("Cache file is not created.", cachefile.exists());
0415: } finally {
0416: cleanupBed();
0417: if (cachefile != null)
0418: cachefile.delete();
0419: }
0420: }
0421:
0422: public void _testCustomCache() {
0423: // same logic as on algorithm, no testcases created
0424: }
0425:
0426: /**
0427: * Test the interface semantic of Caches.
0428: * This method does some common test for cache implementations.
0429: * A cache must return a stored value and a valid iterator.
0430: * After calling the delete() the cache must be empty.
0431: *
0432: * @param algo configured test object
0433: */
0434: protected void doTest(Cache cache) {
0435: assertTrue("Cache not proper configured.", cache.isValid());
0436:
0437: String key1 = "key1";
0438: String value1 = "value1";
0439: String key2 = "key2";
0440: String value2 = "value2";
0441:
0442: // given cache must be empty
0443: Iterator it1 = cache.iterator();
0444: assertFalse("Cache is not empty", it1.hasNext());
0445:
0446: // cache must return a stored value
0447: cache.put(key1, value1);
0448: cache.put(key2, value2);
0449: assertEquals("cache returned wrong value", value1, cache
0450: .get(key1));
0451: assertEquals("cache returned wrong value", value2, cache
0452: .get(key2));
0453:
0454: // test the iterator
0455: Iterator it2 = cache.iterator();
0456: Object returned = it2.next();
0457: boolean ok = (key1.equals(returned) || key2.equals(returned));
0458: String msg = "Iterator returned unexpected value."
0459: + " key1.equals(returned)=" + key1.equals(returned)
0460: + " key2.equals(returned)=" + key2.equals(returned)
0461: + " returned=" + returned + " ok=" + ok;
0462: assertTrue(msg, ok);
0463:
0464: // clear the cache
0465: cache.delete();
0466: Iterator it3 = cache.iterator();
0467: assertFalse("Cache is not empty", it1.hasNext());
0468: }
0469:
0470: // ============== testcases for the algorithm implementations ==============
0471:
0472: public void testHashvalueAlgorithm() {
0473: HashvalueAlgorithm algo = new HashvalueAlgorithm();
0474: doTest(algo);
0475: }
0476:
0477: public void testDigestAlgorithmMD5() {
0478: DigestAlgorithm algo = new DigestAlgorithm();
0479: algo.setAlgorithm("MD5");
0480: doTest(algo);
0481: }
0482:
0483: public void testDigestAlgorithmSHA() {
0484: DigestAlgorithm algo = new DigestAlgorithm();
0485: algo.setAlgorithm("SHA");
0486: doTest(algo);
0487: }
0488:
0489: public void testChecksumAlgorithm() {
0490: ChecksumAlgorithm algo = new ChecksumAlgorithm();
0491: doTest(algo);
0492: }
0493:
0494: public void testChecksumAlgorithmCRC() {
0495: ChecksumAlgorithm algo = new ChecksumAlgorithm();
0496: algo.setAlgorithm("CRC");
0497: doTest(algo);
0498: }
0499:
0500: public void testChecksumAlgorithmAdler() {
0501: ChecksumAlgorithm algo = new ChecksumAlgorithm();
0502: algo.setAlgorithm("Adler");
0503: doTest(algo);
0504: }
0505:
0506: /**
0507: * Test the interface semantic of Algorithms.
0508: * This method does some common test for algorithm implementations.
0509: * An algorithm must return always the same value for the same file and
0510: * it must not return <i>null</i>.
0511: *
0512: * @param algo configured test object
0513: */
0514: protected void doTest(Algorithm algo) {
0515: assertTrue("Algorithm not proper configured.", algo.isValid());
0516: try {
0517: makeBed();
0518:
0519: for (int i = 0; i < files.length; i++) {
0520: File file = files[i]; // must not be a directory
0521: if (file.isFile()) {
0522: // get the Hashvalues
0523: String hash1 = algo.getValue(file);
0524: String hash2 = algo.getValue(file);
0525: String hash3 = algo.getValue(file);
0526: String hash4 = algo.getValue(file);
0527: String hash5 = algo.getValue(new File(file
0528: .getAbsolutePath()));
0529:
0530: // Assert !=null and equality
0531: assertNotNull("Hashvalue was null for "
0532: + file.getAbsolutePath(), hash1);
0533: assertNotNull("Hashvalue was null for "
0534: + file.getAbsolutePath(), hash2);
0535: assertNotNull("Hashvalue was null for "
0536: + file.getAbsolutePath(), hash3);
0537: assertNotNull("Hashvalue was null for "
0538: + file.getAbsolutePath(), hash4);
0539: assertNotNull("Hashvalue was null for "
0540: + file.getAbsolutePath(), hash5);
0541: assertEquals(
0542: "getHashvalue() returned different value for "
0543: + file.getAbsolutePath(), hash1,
0544: hash2);
0545: assertEquals(
0546: "getHashvalue() returned different value for "
0547: + file.getAbsolutePath(), hash1,
0548: hash3);
0549: assertEquals(
0550: "getHashvalue() returned different value for "
0551: + file.getAbsolutePath(), hash1,
0552: hash4);
0553: assertEquals(
0554: "getHashvalue() returned different value for "
0555: + file.getAbsolutePath(), hash1,
0556: hash5);
0557: }//if-isFile
0558: }//for
0559: } finally {
0560: cleanupBed();
0561: }
0562: }
0563:
0564: // ============== testcases for the comparator implementations ==============
0565:
0566: public void testEqualComparator() {
0567: EqualComparator comp = new EqualComparator();
0568: doTest(comp);
0569: }
0570:
0571: public void testRuleComparator() {
0572: RuleBasedCollator comp = (RuleBasedCollator) RuleBasedCollator
0573: .getInstance();
0574: doTest(comp);
0575: }
0576:
0577: public void testEqualComparatorViaSelector() {
0578: ModifiedSelector s = (ModifiedSelector) getSelector();
0579: ModifiedSelector.ComparatorName compName = new ModifiedSelector.ComparatorName();
0580: compName.setValue("equal");
0581: s.setComparator(compName);
0582: try {
0583: performTests(s, "TTTTTTTTTTTT");
0584: } finally {
0585: s.getCache().delete();
0586: }
0587: }
0588:
0589: public void _testRuleComparatorViaSelector() { //not yet supported see note in selector
0590: ModifiedSelector s = (ModifiedSelector) getSelector();
0591: ModifiedSelector.ComparatorName compName = new ModifiedSelector.ComparatorName();
0592: compName.setValue("rule");
0593: s.setComparator(compName);
0594: try {
0595: performTests(s, "TTTTTTTTTTTT");
0596: } finally {
0597: s.getCache().delete();
0598: }
0599: }
0600:
0601: public void _testCustomComparator() {
0602: // same logic as on algorithm, no testcases created
0603: }
0604:
0605: public void testResourceSelectorSimple() {
0606: BFT bft = new BFT("modifiedselector");
0607: bft.doTarget("modifiedselectortest-ResourceSimple");
0608: bft.deleteCachefile();
0609: //new File("src/etc/testcases/types/resources/selectors/cache.properties").delete();
0610: }
0611:
0612: public void testResourceSelectorSelresTrue() {
0613: BFT bft = new BFT("modifiedselector");
0614: bft.doTarget("modifiedselectortest-ResourceSelresTrue");
0615: bft.assertLogContaining("does not provide an InputStream");
0616: bft.deleteCachefile();
0617: }
0618:
0619: public void testResourceSelectorSelresFalse() {
0620: BFT bft = new BFT("modifiedselector");
0621: bft.doTarget("modifiedselectortest-ResourceSelresFalse");
0622: bft.deleteCachefile();
0623: }
0624:
0625: public void testResourceSelectorScenarioSimple() {
0626: BFT bft = new BFT("modifiedselector");
0627: bft.doTarget("modifiedselectortest-scenario-resourceSimple");
0628: bft.doTarget("modifiedselectortest-scenario-clean");
0629: bft.deleteCachefile();
0630: }
0631:
0632: /**
0633: * Test the interface semantic of Comparators.
0634: * This method does some common test for comparator implementations.
0635: *
0636: * @param algo configured test object
0637: */
0638: protected void doTest(Comparator comp) {
0639: Object o1 = new String("string1");
0640: Object o2 = new String("string2");
0641: Object o3 = new String("string2"); // really "2"
0642:
0643: assertTrue("Comparator gave wrong value.",
0644: comp.compare(o1, o2) != 0);
0645: assertTrue("Comparator gave wrong value.",
0646: comp.compare(o1, o3) != 0);
0647: assertTrue("Comparator gave wrong value.",
0648: comp.compare(o2, o3) == 0);
0649: }
0650:
0651: // ===================== scenario tests =====================
0652:
0653: /**
0654: * Tests whether the seldirs attribute is used.
0655: */
0656: public void testSeldirs() {
0657: ModifiedSelector s = (ModifiedSelector) getSelector();
0658: try {
0659: makeBed();
0660:
0661: StringBuffer sbTrue = new StringBuffer();
0662: StringBuffer sbFalse = new StringBuffer();
0663: for (int i = 0; i < filenames.length; i++) {
0664: if (files[i].isDirectory()) {
0665: sbTrue.append("T");
0666: sbFalse.append("F");
0667: } else {
0668: sbTrue.append("T");
0669: sbFalse.append("T");
0670: }
0671: }
0672:
0673: s.setSeldirs(true);
0674: performTests(s, sbTrue.toString());
0675: s.getCache().delete();
0676:
0677: s.setSeldirs(false);
0678: performTests(s, sbFalse.toString());
0679: s.getCache().delete();
0680:
0681: } finally {
0682: cleanupBed();
0683: if (s != null)
0684: s.getCache().delete();
0685: }
0686: }
0687:
0688: /**
0689: * Complex test scenario using default values (DigestAlgorithm with MD5,
0690: * PropertiesfileCache with file=cache.properties, EqualComparator
0691: * and update=true). <ol>
0692: * <li> try fist time --> should select all </li>
0693: * <li> try second time --> should select no files (only directories) </li>
0694: * <li> modify timestamp of one file and content of a nother one </li>
0695: * <li> try third time --> should select only the file with modified
0696: * content </li>
0697: */
0698: public void testScenario1() {
0699: BFT bft = null;
0700: ModifiedSelector s = null;
0701: try {
0702: //
0703: // ***** initialize test environment (called "bed") *****
0704: //
0705: makeBed();
0706: String results = null;
0707:
0708: // Configure the selector - only defaults are used
0709: s = (ModifiedSelector) getSelector();
0710:
0711: //
0712: // ***** First Run *****
0713: // the first call should get all files, because nothing is in
0714: // the cache
0715: //
0716: performTests(s, "TTTTTTTTTTTT");
0717:
0718: //
0719: // ***** Second Run *****
0720: // the second call should get no files, because no content
0721: // has changed
0722: //
0723: performTests(s, "TFFFFFFFFFFT");
0724:
0725: //
0726: // ***** make some files dirty *****
0727: //
0728:
0729: // these files are made dirty --> 3+4 with different content
0730: String f2name = "tar/bz2/asf-logo-huge.tar.bz2";
0731: String f3name = "asf-logo.gif.md5";
0732: String f4name = "copy.filterset.filtered";
0733:
0734: // AccessObject to the test-Ant-environment
0735: bft = new BFT();
0736: // give some values (via property file) to that environment
0737: bft.writeProperties("f2name=" + f2name);
0738: bft.writeProperties("f3name=" + f3name);
0739: bft.writeProperties("f4name=" + f4name);
0740: // call the target for making the files dirty
0741: bft.doTarget("modifiedselectortest-makeDirty");
0742:
0743: //
0744: // ***** Third Run *****
0745: // third call should get only those files, which CONTENT changed
0746: // (no timestamp changes required!)
0747: results = selectionString(s);
0748:
0749: //
0750: // ***** Check the result *****
0751: //
0752:
0753: // Mark all files which should be selected as (T)rue and all others
0754: // as (F)alse. Directories are always selected so they always are
0755: // (T)rue.
0756: StringBuffer expected = new StringBuffer();
0757: for (int i = 0; i < filenames.length; i++) {
0758: String ch = "F";
0759: if (files[i].isDirectory())
0760: ch = "T";
0761: // f2name shouldn't be selected: only timestamp has changed!
0762: if (filenames[i].equalsIgnoreCase(f3name))
0763: ch = "T";
0764: if (filenames[i].equalsIgnoreCase(f4name))
0765: ch = "T";
0766: expected.append(ch);
0767: }
0768:
0769: assertEquals("Wrong files selected. Differing files: " // info text
0770: + resolve(diff(expected.toString(), results)), // list of files
0771: expected.toString(), // expected result
0772: results // result
0773: );
0774:
0775: } finally {
0776: // cleanup the environment
0777: cleanupBed();
0778: if (s != null)
0779: s.getCache().delete();
0780: if (bft != null)
0781: bft.deletePropertiesfile();
0782: }
0783: }
0784:
0785: /**
0786: * This scenario is based on scenario 1, but does not use any
0787: * default value and its based on <custom> selector. Used values are:<ul>
0788: * <li><b>Cache: </b> Propertyfile,
0789: * cachefile={java.io.tmpdir}/mycache.txt </li>
0790: * <li><b>Algorithm: </b> Digest
0791: * algorithm=SHA, Provider=null </li>
0792: * <li><b>Comparator: </b> java.text.RuleBasedCollator
0793: * <li><b>Update: </b> true </li>
0794: */
0795: public void _testScenario2() { // RuleBasedCollator not yet supported - see Selector:375 note
0796: ExtendSelector s = new ExtendSelector();
0797: BFT bft = new BFT();
0798: String cachefile = System.getProperty("java.io.tmpdir")
0799: + "/mycache.txt";
0800: try {
0801: makeBed();
0802:
0803: s
0804: .setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
0805:
0806: s.addParam(createParam("cache.cachefile", cachefile));
0807: //s.addParam(createParam("algorithm.provider","---")); // i don't know any valid
0808: s.addParam(createParam("cache", "propertyfile"));
0809: s.addParam(createParam("update", "true"));
0810: s.addParam(createParam("comparator", "rule"));
0811: s.addParam(createParam("algorithm.name", "sha"));
0812: s.addParam(createParam("algorithm", "digest"));
0813:
0814: // first and second run
0815: performTests(s, "TTTTTTTTTTTT");
0816: performTests(s, "TFFFFFFFFFFT");
0817: // make dirty
0818: String f2name = "tar/bz2/asf-logo-huge.tar.bz2";
0819: String f3name = "asf-logo.gif.md5";
0820: String f4name = "copy.filterset.filtered";
0821: bft.writeProperties("f2name=" + f2name);
0822: bft.writeProperties("f3name=" + f3name);
0823: bft.writeProperties("f4name=" + f4name);
0824: bft.doTarget("modifiedselectortest-makeDirty");
0825: // third run
0826: String results = selectionString(s);
0827: StringBuffer expected = new StringBuffer();
0828: for (int i = 0; i < filenames.length; i++) {
0829: String ch = "F";
0830: if (files[i].isDirectory())
0831: ch = "T";
0832: if (filenames[i].equalsIgnoreCase(f3name))
0833: ch = "T";
0834: if (filenames[i].equalsIgnoreCase(f4name))
0835: ch = "T";
0836: expected.append(ch);
0837: }
0838: assertEquals("Wrong files selected. Differing files: " // info text
0839: + resolve(diff(expected.toString(), results)), // list of files
0840: expected.toString(), // expected result
0841: results // result
0842: );
0843: } finally {
0844: // cleanup the environment
0845: cleanupBed();
0846: (new java.io.File(cachefile)).delete();
0847: if (bft != null)
0848: bft.deletePropertiesfile();
0849: }
0850: }
0851:
0852: public void testScenarioCoreSelectorDefaults() {
0853: doScenarioTest(
0854: "modifiedselectortest-scenario-coreselector-defaults",
0855: "cache.properties");
0856: }
0857:
0858: public void testScenarioCoreSelectorSettings() {
0859: doScenarioTest(
0860: "modifiedselectortest-scenario-coreselector-settings",
0861: "core.cache.properties");
0862: }
0863:
0864: public void testScenarioCustomSelectorSettings() {
0865: doScenarioTest(
0866: "modifiedselectortest-scenario-customselector-settings",
0867: "core.cache.properties");
0868: }
0869:
0870: public void doScenarioTest(String target, String cachefilename) {
0871: BFT bft = new BFT();
0872: bft.setUp();
0873: File cachefile = new File(basedir, cachefilename);
0874: try {
0875: // do the actions
0876: bft.doTarget("modifiedselectortest-scenario-clean");
0877: bft.doTarget(target);
0878:
0879: // the directories to check
0880: File to1 = new File(basedir, "selectortest/to-1");
0881: File to2 = new File(basedir, "selectortest/to-2");
0882: File to3 = new File(basedir, "selectortest/to-3");
0883:
0884: // do the checks
0885: assertTrue("Cache file not created.", cachefile.exists());
0886: assertTrue("Not enough files copied on first time.", to1
0887: .list().length > 5);
0888: assertTrue("Too much files copied on second time.", to2
0889: .list().length == 0);
0890: assertTrue("Too much files copied on third time.", to3
0891: .list().length == 2);
0892: // don't catch the JUnit exceptions
0893: } finally {
0894: bft.doTarget("modifiedselectortest-scenario-clean");
0895: bft.deletePropertiesfile();
0896: bft.tearDown();
0897: cachefile.delete();
0898: }
0899: }
0900:
0901: // ===================== helper methods and classes ====================
0902:
0903: /**
0904: * Creates a configured parameter object.
0905: * @param name name of the parameter
0906: * @param value value of the parameter
0907: * @return the parameter object
0908: */
0909: private Parameter createParam(String name, String value) {
0910: Parameter p = new Parameter();
0911: p.setName(name);
0912: p.setValue(value);
0913: return p;
0914: }
0915:
0916: /**
0917: * The BFT class wrapps the selector test-builfile inside an
0918: * ant project (BuildFileTest). It supports target execution
0919: * and property transfer to that project.
0920: */
0921: private class BFT extends org.apache.tools.ant.BuildFileTest {
0922: String buildfile = "src/etc/testcases/types/selectors.xml";
0923:
0924: BFT() {
0925: super ("nothing");
0926: }
0927:
0928: BFT(String name) {
0929: super (name);
0930: }
0931:
0932: String propfile = "ModifiedSelectorTest.properties";
0933:
0934: boolean isConfigured = false;
0935:
0936: public void setUp() {
0937: configureProject(buildfile);
0938: isConfigured = true;
0939: }
0940:
0941: /**
0942: * This stub teardown is here because the outer class needs to call the
0943: * tearDown method, and in the superclass it is protected.
0944: */
0945: public void tearDown() {
0946: try {
0947: super .tearDown();
0948: } catch (Exception e) {
0949: // ignore
0950: }
0951: }
0952:
0953: public void doTarget(String target) {
0954: if (!isConfigured)
0955: setUp();
0956: executeTarget(target);
0957: }
0958:
0959: public String getProperty(String property) {
0960: return project.getProperty(property);
0961: }
0962:
0963: public void writeProperties(String line) {
0964: if (!isConfigured)
0965: setUp();
0966: File dir = getProject().getBaseDir();
0967: File file = new File(dir, propfile);
0968: try {
0969: java.io.FileWriter out = new java.io.FileWriter(file
0970: .getAbsolutePath(), true);
0971: out.write(line);
0972: out.write(System.getProperty("line.separator"));
0973: out.flush();
0974: out.close();
0975: } catch (Exception e) {
0976: e.printStackTrace();
0977: }
0978: }
0979:
0980: public void deletePropertiesfile() {
0981: if (!isConfigured)
0982: setUp();
0983: new File(getProject().getBaseDir(), propfile).delete();
0984: }
0985:
0986: public void deleteCachefile() {
0987: File basedir = new File(buildfile).getParentFile();
0988: File cacheFile = new File(basedir, "cache.properties");
0989: cacheFile.delete();
0990: }
0991:
0992: public String getBuildfile() {
0993: return buildfile;
0994: }
0995:
0996: public void setBuildfile(String buildfile) {
0997: this .buildfile = buildfile;
0998: }
0999: }//class-BFT
1000:
1001: /**
1002: * MockProject wrappes a very small ant project (one target, one task)
1003: * but provides public methods to fire the build events.
1004: */
1005: private class MockProject extends Project {
1006: private Task task;
1007: private Target target;
1008:
1009: public MockProject() {
1010: task = new Task() {
1011: public void execute() {
1012: }
1013: };
1014: task.setTaskName("testTask");
1015: target = new Target();
1016: target.setName("testTarget");
1017: target.setProject(this );
1018: target.addTask(task);
1019: task.setOwningTarget(target);
1020: }
1021:
1022: public void fireBuildFinished() {
1023: super .fireBuildFinished(null);
1024: }
1025:
1026: public void fireSubBuildFinished() {
1027: super .fireSubBuildFinished(null);
1028: }
1029:
1030: public void fireTargetStarted() {
1031: super .fireTargetStarted(target);
1032: }
1033:
1034: public void fireTargetFinished() {
1035: super .fireTargetFinished(target, null);
1036: }
1037:
1038: public void fireTaskStarted() {
1039: super .fireTaskStarted(task);
1040: }
1041:
1042: public void fireTaskFinished() {
1043: super .fireTaskFinished(task, null);
1044: }
1045: }//class-MockProject
1046:
1047: }//class-ModifiedSelectorTest
|