TestFinder.java revision 1008:459874975ef6
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.test.framework;
27
28import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_CHECK_COMPILE_MSG;
29import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_COMPARE;
30import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_EXPECT_COMPILE_FAIL;
31import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_EXPECT_RUN_FAIL;
32import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_FORK;
33import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_IGNORE_STD_ERROR;
34import static jdk.nashorn.internal.test.framework.TestConfig.OPTIONS_RUN;
35import static jdk.nashorn.internal.test.framework.TestConfig.TEST_FAILED_LIST_FILE;
36import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_ENABLE_STRICT_MODE;
37import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_EXCLUDES_FILE;
38import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_EXCLUDE_DIR;
39import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_EXCLUDE_LIST;
40import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_FRAMEWORK;
41import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_INCLUDES;
42import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_LIST;
43import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_ROOTS;
44import static jdk.nashorn.internal.test.framework.TestConfig.TEST_JS_UNCHECKED_DIR;
45
46import java.io.BufferedReader;
47import java.io.File;
48import java.io.FileReader;
49import java.io.IOException;
50import java.nio.file.FileSystem;
51import java.nio.file.FileSystems;
52import java.nio.file.FileVisitOption;
53import java.nio.file.FileVisitResult;
54import java.nio.file.Files;
55import java.nio.file.Path;
56import java.nio.file.SimpleFileVisitor;
57import java.nio.file.attribute.BasicFileAttributes;
58import java.util.ArrayList;
59import java.util.Collections;
60import java.util.EnumSet;
61import java.util.HashMap;
62import java.util.HashSet;
63import java.util.List;
64import java.util.Map;
65import java.util.Scanner;
66import java.util.Set;
67import javax.xml.xpath.XPath;
68import javax.xml.xpath.XPathConstants;
69import javax.xml.xpath.XPathExpressionException;
70import javax.xml.xpath.XPathFactory;
71import org.w3c.dom.NodeList;
72import org.xml.sax.InputSource;
73
74/**
75 * Utility class to find/parse script test files and to create 'test' instances.
76 * Actual 'test' object type is decided by clients of this class.
77 */
78final class TestFinder {
79    private TestFinder() {}
80
81    interface TestFactory<T> {
82        // 'test' instance type is decided by the client.
83        T createTest(final String framework, final File testFile, final List<String> engineOptions, final Map<String, String> testOptions, final List<String> arguments);
84        // place to log messages from TestFinder
85        void log(String mg);
86    }
87
88
89    // finds all tests from configuration and calls TestFactory to create 'test' instance for each script test found
90    static <T> void findAllTests(final List<T> tests, final Set<String> orphans, final TestFactory<T> testFactory) throws Exception {
91        final String framework = System.getProperty(TEST_JS_FRAMEWORK);
92        final String testList = System.getProperty(TEST_JS_LIST);
93        final String failedTestFileName = System.getProperty(TEST_FAILED_LIST_FILE);
94        if(failedTestFileName != null) {
95            final File failedTestFile = new File(failedTestFileName);
96            if(failedTestFile.exists() && failedTestFile.length() > 0L) {
97                try(final BufferedReader r = new BufferedReader(new FileReader(failedTestFile))) {
98                    for(;;) {
99                        final String testFileName = r.readLine();
100                        if(testFileName == null) {
101                            break;
102                        }
103                        handleOneTest(framework, new File(testFileName).toPath(), tests, orphans, testFactory);
104                    }
105                }
106                return;
107            }
108        }
109        if (testList == null || testList.length() == 0) {
110            // Run the tests under the test roots dir, selected by the
111            // TEST_JS_INCLUDES patterns
112            final String testRootsString = System.getProperty(TEST_JS_ROOTS, "test/script");
113            if (testRootsString == null || testRootsString.length() == 0) {
114                throw new Exception("Error: " + TEST_JS_ROOTS + " must be set");
115            }
116            final String testRoots[] = testRootsString.split(" ");
117            final FileSystem fileSystem = FileSystems.getDefault();
118            final Set<String> testExcludeSet = getExcludeSet();
119            final Path[] excludePaths = getExcludeDirs();
120            for (final String root : testRoots) {
121                final Path dir = fileSystem.getPath(root);
122                findTests(framework, dir, tests, orphans, excludePaths, testExcludeSet, testFactory);
123            }
124        } else {
125            // TEST_JS_LIST contains a blank speparated list of test file names.
126            final String strArray[] = testList.split(" ");
127            for (final String ss : strArray) {
128                handleOneTest(framework, new File(ss).toPath(), tests, orphans, testFactory);
129            }
130        }
131    }
132
133    private static boolean inExcludePath(final Path file, final Path[] excludePaths) {
134        if (excludePaths == null) {
135            return false;
136        }
137
138        for (final Path excludePath : excludePaths) {
139            if (file.startsWith(excludePath)) {
140                return true;
141            }
142        }
143        return false;
144    }
145
146    private static <T> void findTests(final String framework, final Path dir, final List<T> tests, final Set<String> orphanFiles, final Path[] excludePaths, final Set<String> excludedTests, final TestFactory<T> factory) throws Exception {
147        final String pattern = System.getProperty(TEST_JS_INCLUDES);
148        final String extension = pattern == null ? "js" : pattern;
149        final Exception[] exceptions = new Exception[1];
150        final List<String> excludedActualTests = new ArrayList<>();
151
152        if (! dir.toFile().isDirectory()) {
153            factory.log("WARNING: " + dir + " not found or not a directory");
154        }
155
156        Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
157            @Override
158            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
159                final String fileName = file.getName(file.getNameCount() - 1).toString();
160                if (fileName.endsWith(extension)) {
161                    final String namex = file.toString().replace('\\', '/');
162                    if (!inExcludePath(file, excludePaths) && !excludedTests.contains(file.getFileName().toString())) {
163                        try {
164                            handleOneTest(framework, file, tests, orphanFiles, factory);
165                        } catch (final Exception ex) {
166                            exceptions[0] = ex;
167                            return FileVisitResult.TERMINATE;
168                        }
169                    } else {
170                        excludedActualTests.add(namex);
171                    }
172                }
173                return FileVisitResult.CONTINUE;
174            }
175        });
176        Collections.sort(excludedActualTests);
177
178        for (final String excluded : excludedActualTests) {
179            factory.log("Excluding " + excluded);
180        }
181
182        if (exceptions[0] != null) {
183            throw exceptions[0];
184        }
185    }
186
187    private static final String uncheckedDirs[] = System.getProperty(TEST_JS_UNCHECKED_DIR, "test/script/external/test262/").split(" ");
188
189    private static boolean isUnchecked(final Path testFile) {
190        for (final String uncheckedDir : uncheckedDirs) {
191            if (testFile.startsWith(uncheckedDir)) {
192                return true;
193            }
194        }
195        return false;
196    }
197
198    private static <T> void handleOneTest(final String framework, final Path testFile, final List<T> tests, final Set<String> orphans, final TestFactory<T> factory) throws Exception {
199        final String name = testFile.getFileName().toString();
200
201        assert name.lastIndexOf(".js") > 0 : "not a JavaScript: " + name;
202
203        // defaults: testFile is a test and should be run
204        boolean isTest = isUnchecked(testFile);
205        boolean isNotTest = false;
206        boolean shouldRun = true;
207        boolean compileFailure = false;
208        boolean runFailure = false;
209        boolean checkCompilerMsg = false;
210        boolean noCompare = false;
211        boolean ignoreStdError = false;
212        boolean fork = false;
213
214        final List<String> engineOptions = new ArrayList<>();
215        final List<String> scriptArguments = new ArrayList<>();
216        boolean inComment = false;
217
218        try (Scanner scanner = new Scanner(testFile)) {
219            while (scanner.hasNext()) {
220                // TODO: Scan for /ref=file qualifiers, etc, to determine run
221                // behavior
222                String token = scanner.next();
223                if (token.startsWith("/*")) {
224                    inComment = true;
225                } else if (token.endsWith(("*/"))) {
226                    inComment = false;
227                } else if (!inComment) {
228                    continue;
229                }
230
231                // remove whitespace and trailing semicolons, if any
232                // (trailing semicolons are found in some sputnik tests)
233                token = token.trim();
234                final int semicolon = token.indexOf(';');
235                if (semicolon > 0) {
236                    token = token.substring(0, semicolon);
237                }
238                switch (token) {
239                case "@test":
240                    isTest = true;
241                    break;
242                case "@test/fail":
243                    isTest = true;
244                    compileFailure = true;
245                    break;
246                case "@test/compile-error":
247                    isTest = true;
248                    compileFailure = true;
249                    checkCompilerMsg = true;
250                    shouldRun = false;
251                    break;
252                case "@test/warning":
253                    isTest = true;
254                    checkCompilerMsg = true;
255                    break;
256                case "@test/nocompare":
257                    isTest = true;
258                    noCompare = true;
259                    break;
260                case "@subtest":
261                    isTest = false;
262                    isNotTest = true;
263                    break;
264                case "@runif": {
265                    final String prop = scanner.next();
266                    if (System.getProperty(prop) != null) {
267                        shouldRun = true;
268                    } else {
269                        factory.log("WARNING: (" + prop + ") skipping " + testFile);
270                        isTest = false;
271                        isNotTest = true;
272                    }
273                    break;
274                }
275                case "@run":
276                    shouldRun = true;
277                    break;
278                case "@run/fail":
279                    shouldRun = true;
280                    runFailure = true;
281                    break;
282                case "@run/ignore-std-error":
283                    shouldRun = true;
284                    ignoreStdError = true;
285                    break;
286                case "@argument":
287                    scriptArguments.add(scanner.next());
288                    break;
289                case "@option":
290                    engineOptions.add(scanner.next());
291                    break;
292                case "@fork":
293                    fork = true;
294                    break;
295                }
296
297                // negative tests are expected to fail at runtime only
298                // for those tests that are expected to fail at compile time,
299                // add @test/compile-error
300                if (token.equals("@negative") || token.equals("@strict_mode_negative")) {
301                    shouldRun = true;
302                    runFailure = true;
303                }
304
305                if (token.equals("@strict_mode") || token.equals("@strict_mode_negative") || token.equals("@onlyStrict") || token.equals("@noStrict")) {
306                    if (!strictModeEnabled()) {
307                        return;
308                    }
309                }
310            }
311        } catch (final Exception ignored) {
312            return;
313        }
314
315        if (isTest) {
316            final Map<String, String> testOptions = new HashMap<>();
317            if (compileFailure) {
318                testOptions.put(OPTIONS_EXPECT_COMPILE_FAIL, "true");
319            }
320            if (shouldRun) {
321                testOptions.put(OPTIONS_RUN, "true");
322            }
323            if (runFailure) {
324                testOptions.put(OPTIONS_EXPECT_RUN_FAIL, "true");
325            }
326            if (checkCompilerMsg) {
327                testOptions.put(OPTIONS_CHECK_COMPILE_MSG, "true");
328            }
329            if (!noCompare) {
330                testOptions.put(OPTIONS_COMPARE, "true");
331            }
332            if (ignoreStdError) {
333                testOptions.put(OPTIONS_IGNORE_STD_ERROR, "true");
334            }
335            if (fork) {
336                testOptions.put(OPTIONS_FORK, "true");
337            }
338
339            tests.add(factory.createTest(framework, testFile.toFile(), engineOptions, testOptions, scriptArguments));
340        } else if (!isNotTest) {
341            orphans.add(name);
342        }
343    }
344
345    private static boolean strictModeEnabled() {
346        return Boolean.getBoolean(TEST_JS_ENABLE_STRICT_MODE);
347    }
348
349    private static Set<String> getExcludeSet() throws XPathExpressionException {
350        final String testExcludeList = System.getProperty(TEST_JS_EXCLUDE_LIST);
351
352        String[] testExcludeArray = {};
353        if (testExcludeList != null) {
354            testExcludeArray = testExcludeList.split(" ");
355        }
356        final Set<String> testExcludeSet = new HashSet<>(testExcludeArray.length);
357        for (final String test : testExcludeArray) {
358            testExcludeSet.add(test);
359        }
360
361        final String testExcludesFile = System.getProperty(TEST_JS_EXCLUDES_FILE);
362        if (testExcludesFile != null && !testExcludesFile.isEmpty()) {
363            try {
364                loadExcludesFile(testExcludesFile, testExcludeSet);
365            } catch (final XPathExpressionException e) {
366                System.err.println("Error: unable to load test excludes from " + testExcludesFile);
367                e.printStackTrace();
368                throw e;
369            }
370        }
371        return testExcludeSet;
372    }
373
374    private static void loadExcludesFile(final String testExcludesFile, final Set<String> testExcludeSet) throws XPathExpressionException {
375        final XPath xpath = XPathFactory.newInstance().newXPath();
376        final NodeList testIds = (NodeList)xpath.evaluate("/excludeList/test/@id", new InputSource(testExcludesFile), XPathConstants.NODESET);
377        for (int i = testIds.getLength() - 1; i >= 0; i--) {
378            testExcludeSet.add(testIds.item(i).getNodeValue());
379        }
380    }
381
382    private static Path[] getExcludeDirs() {
383        final String excludeDirs[] = System.getProperty(TEST_JS_EXCLUDE_DIR, "test/script/currently-failing").split(" ");
384        final Path[] excludePaths = new Path[excludeDirs.length];
385        final FileSystem fileSystem = FileSystems.getDefault();
386        int i = 0;
387        for (final String excludeDir : excludeDirs) {
388            excludePaths[i++] = fileSystem.getPath(excludeDir);
389        }
390        return excludePaths;
391    }
392}
393