TestFinder.java revision 1113:80be1cd8c2a2
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;
45import java.io.BufferedReader;
46import java.io.File;
47import java.io.FileReader;
48import java.io.IOException;
49import java.nio.ByteOrder;
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.Arrays;
60import java.util.Collections;
61import java.util.EnumSet;
62import java.util.HashMap;
63import java.util.HashSet;
64import java.util.List;
65import java.util.Map;
66import java.util.Scanner;
67import java.util.Set;
68import javax.xml.xpath.XPath;
69import javax.xml.xpath.XPathConstants;
70import javax.xml.xpath.XPathExpressionException;
71import javax.xml.xpath.XPathFactory;
72import org.w3c.dom.NodeList;
73import org.xml.sax.InputSource;
74
75/**
76 * Utility class to find/parse script test files and to create 'test' instances.
77 * Actual 'test' object type is decided by clients of this class.
78 */
79@SuppressWarnings("javadoc")
80public final class TestFinder {
81    private TestFinder() {}
82
83    interface TestFactory<T> {
84        // 'test' instance type is decided by the client.
85        T createTest(final String framework, final File testFile, final List<String> engineOptions, final Map<String, String> testOptions, final List<String> arguments);
86        // place to log messages from TestFinder
87        void log(String mg);
88    }
89
90
91    // finds all tests from configuration and calls TestFactory to create 'test' instance for each script test found
92    static <T> void findAllTests(final List<T> tests, final Set<String> orphans, final TestFactory<T> testFactory) throws Exception {
93        final String framework = System.getProperty(TEST_JS_FRAMEWORK);
94        final String testList = System.getProperty(TEST_JS_LIST);
95        final String failedTestFileName = System.getProperty(TEST_FAILED_LIST_FILE);
96        if(failedTestFileName != null) {
97            final File failedTestFile = new File(failedTestFileName);
98            if(failedTestFile.exists() && failedTestFile.length() > 0L) {
99                try(final BufferedReader r = new BufferedReader(new FileReader(failedTestFile))) {
100                    for(;;) {
101                        final String testFileName = r.readLine();
102                        if(testFileName == null) {
103                            break;
104                        }
105                        handleOneTest(framework, new File(testFileName).toPath(), tests, orphans, testFactory);
106                    }
107                }
108                return;
109            }
110        }
111        if (testList == null || testList.length() == 0) {
112            // Run the tests under the test roots dir, selected by the
113            // TEST_JS_INCLUDES patterns
114            final String testRootsString = System.getProperty(TEST_JS_ROOTS, "test/script");
115            if (testRootsString == null || testRootsString.length() == 0) {
116                throw new Exception("Error: " + TEST_JS_ROOTS + " must be set");
117            }
118            final String testRoots[] = testRootsString.split(" ");
119            final FileSystem fileSystem = FileSystems.getDefault();
120            final Set<String> testExcludeSet = getExcludeSet();
121            final Path[] excludePaths = getExcludeDirs();
122            for (final String root : testRoots) {
123                final Path dir = fileSystem.getPath(root);
124                findTests(framework, dir, tests, orphans, excludePaths, testExcludeSet, testFactory);
125            }
126        } else {
127            // TEST_JS_LIST contains a blank speparated list of test file names.
128            final String strArray[] = testList.split(" ");
129            for (final String ss : strArray) {
130                handleOneTest(framework, new File(ss).toPath(), tests, orphans, testFactory);
131            }
132        }
133    }
134
135    private static boolean inExcludePath(final Path file, final Path[] excludePaths) {
136        if (excludePaths == null) {
137            return false;
138        }
139
140        for (final Path excludePath : excludePaths) {
141            if (file.startsWith(excludePath)) {
142                return true;
143            }
144        }
145        return false;
146    }
147
148    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 {
149        final String pattern = System.getProperty(TEST_JS_INCLUDES);
150        final String extension = pattern == null ? "js" : pattern;
151        final Exception[] exceptions = new Exception[1];
152        final List<String> excludedActualTests = new ArrayList<>();
153
154        if (! dir.toFile().isDirectory()) {
155            factory.log("WARNING: " + dir + " not found or not a directory");
156        }
157
158        Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
159            @Override
160            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
161                final String fileName = file.getName(file.getNameCount() - 1).toString();
162                if (fileName.endsWith(extension)) {
163                    final String namex = file.toString().replace('\\', '/');
164                    if (!inExcludePath(file, excludePaths) && !excludedTests.contains(file.getFileName().toString())) {
165                        try {
166                            handleOneTest(framework, file, tests, orphanFiles, factory);
167                        } catch (final Exception ex) {
168                            exceptions[0] = ex;
169                            return FileVisitResult.TERMINATE;
170                        }
171                    } else {
172                        excludedActualTests.add(namex);
173                    }
174                }
175                return FileVisitResult.CONTINUE;
176            }
177        });
178        Collections.sort(excludedActualTests);
179
180        for (final String excluded : excludedActualTests) {
181            factory.log("Excluding " + excluded);
182        }
183
184        if (exceptions[0] != null) {
185            throw exceptions[0];
186        }
187    }
188
189    private static final String uncheckedDirs[] = System.getProperty(TEST_JS_UNCHECKED_DIR, "test/script/external/test262/").split(" ");
190
191    private static boolean isUnchecked(final Path testFile) {
192        for (final String uncheckedDir : uncheckedDirs) {
193            if (testFile.startsWith(uncheckedDir)) {
194                return true;
195            }
196        }
197        return false;
198    }
199
200    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 {
201        final String name = testFile.getFileName().toString();
202
203        assert name.lastIndexOf(".js") > 0 : "not a JavaScript: " + name;
204
205        // defaults: testFile is a test and should be run
206        boolean isTest = isUnchecked(testFile);
207        boolean isNotTest = false;
208        boolean shouldRun = true;
209        boolean compileFailure = false;
210        boolean runFailure = false;
211        boolean checkCompilerMsg = false;
212        boolean noCompare = false;
213        boolean ignoreStdError = false;
214        boolean fork = false;
215
216        final List<String> engineOptions = new ArrayList<>();
217        final List<String> scriptArguments = new ArrayList<>();
218        boolean inComment = false;
219
220        boolean explicitOptimistic = false;
221
222        try (Scanner scanner = new Scanner(testFile)) {
223            while (scanner.hasNext()) {
224                // TODO: Scan for /ref=file qualifiers, etc, to determine run
225                // behavior
226                String token = scanner.next();
227                if (token.startsWith("/*")) {
228                    inComment = true;
229                } else if (token.endsWith(("*/"))) {
230                    inComment = false;
231                } else if (!inComment) {
232                    continue;
233                }
234
235                // remove whitespace and trailing semicolons, if any
236                // (trailing semicolons are found in some sputnik tests)
237                token = token.trim();
238                final int semicolon = token.indexOf(';');
239                if (semicolon > 0) {
240                    token = token.substring(0, semicolon);
241                }
242                switch (token) {
243                case "@test":
244                    isTest = true;
245                    break;
246                case "@test/fail":
247                    isTest = true;
248                    compileFailure = true;
249                    break;
250                case "@test/compile-error":
251                    isTest = true;
252                    compileFailure = true;
253                    checkCompilerMsg = true;
254                    shouldRun = false;
255                    break;
256                case "@test/warning":
257                    isTest = true;
258                    checkCompilerMsg = true;
259                    break;
260                case "@test/nocompare":
261                    isTest = true;
262                    noCompare = true;
263                    break;
264                case "@subtest":
265                    isTest = false;
266                    isNotTest = true;
267                    break;
268                case "@bigendian":
269                    shouldRun = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
270                    break;
271                case "@littleendian":
272                    shouldRun = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
273                    break;
274                case "@runif": {
275                    final String prop = scanner.next();
276                    if (System.getProperty(prop) != null) {
277                        shouldRun = true;
278                    } else {
279                        factory.log("WARNING: (" + prop + ") skipping " + testFile);
280                        isTest = false;
281                        isNotTest = true;
282                    }
283                    break;
284                }
285                case "@run":
286                    shouldRun = true;
287                    break;
288                case "@run/fail":
289                    shouldRun = true;
290                    runFailure = true;
291                    break;
292                case "@run/ignore-std-error":
293                    shouldRun = true;
294                    ignoreStdError = true;
295                    break;
296                case "@argument":
297                    scriptArguments.add(scanner.next());
298                    break;
299                case "@option":
300                    final String next = scanner.next();
301                    engineOptions.add(next);
302                    if (next.startsWith("--optimistic-types")) {
303                        explicitOptimistic = true;
304                    }
305                    break;
306                case "@fork":
307                    fork = true;
308                    break;
309                default:
310                    break;
311                }
312
313                // negative tests are expected to fail at runtime only
314                // for those tests that are expected to fail at compile time,
315                // add @test/compile-error
316                if (token.equals("@negative") || token.equals("@strict_mode_negative")) {
317                    shouldRun = true;
318                    runFailure = true;
319                }
320
321                if (token.equals("@strict_mode") || token.equals("@strict_mode_negative") || token.equals("@onlyStrict") || token.equals("@noStrict")) {
322                    if (!strictModeEnabled()) {
323                        return;
324                    }
325                }
326            }
327        } catch (final Exception ignored) {
328            return;
329        }
330
331        if (isTest) {
332            final Map<String, String> testOptions = new HashMap<>();
333            if (compileFailure) {
334                testOptions.put(OPTIONS_EXPECT_COMPILE_FAIL, "true");
335            }
336            if (shouldRun) {
337                testOptions.put(OPTIONS_RUN, "true");
338            }
339            if (runFailure) {
340                testOptions.put(OPTIONS_EXPECT_RUN_FAIL, "true");
341            }
342            if (checkCompilerMsg) {
343                testOptions.put(OPTIONS_CHECK_COMPILE_MSG, "true");
344            }
345            if (!noCompare) {
346                testOptions.put(OPTIONS_COMPARE, "true");
347            }
348            if (ignoreStdError) {
349                testOptions.put(OPTIONS_IGNORE_STD_ERROR, "true");
350            }
351            if (fork) {
352                testOptions.put(OPTIONS_FORK, "true");
353            }
354
355            //if there are explicit optimistic type settings, use those - do not override
356            //the test might only work with optimistic types on or off.
357            if (!explicitOptimistic) {
358                addExplicitOptimisticTypes(engineOptions);
359            }
360
361            tests.add(factory.createTest(framework, testFile.toFile(), engineOptions, testOptions, scriptArguments));
362        } else if (!isNotTest) {
363            orphans.add(name);
364        }
365    }
366
367    //the reverse of the default setting for optimistic types, if enabled, false, otherwise true
368    //thus, true for 8u40, false for 9
369    private static final boolean OPTIMISTIC_OVERRIDE = false;
370
371    /**
372     * Check if there is an optimistic override, that disables the default
373     * false optimistic types and sets them to true, for testing purposes
374     *
375     * @return true if optimistic type override has been set by test suite
376     */
377    public static boolean hasOptimisticOverride() {
378        return Boolean.valueOf(OPTIMISTIC_OVERRIDE).toString().equals(System.getProperty("optimistic.override"));
379    }
380
381    /**
382     * Add an optimistic-types=true option to an argument list if this
383     * is set to override the default false. Add an optimistic-types=true
384     * options to an argument list if this is set to override the default
385     * true
386     *
387     * @args new argument list array
388     */
389    public static String[] addExplicitOptimisticTypes(final String[] args) {
390        if (hasOptimisticOverride()) {
391            final List<String> newList = new ArrayList<>(Arrays.asList(args));
392            newList.add("--optimistic-types=" + Boolean.valueOf(OPTIMISTIC_OVERRIDE));
393            return newList.toArray(new String[0]);
394        }
395        return args;
396    }
397
398    /**
399     * Add an optimistic-types=true option to an argument list if this
400     * is set to override the default false
401     *
402     * @args argument list
403     */
404    public static void addExplicitOptimisticTypes(final List<String> args) {
405        if (hasOptimisticOverride()) {
406            args.add("--optimistic-types=" + Boolean.valueOf(OPTIMISTIC_OVERRIDE));
407        }
408    }
409
410    private static boolean strictModeEnabled() {
411        return Boolean.getBoolean(TEST_JS_ENABLE_STRICT_MODE);
412    }
413
414    private static Set<String> getExcludeSet() throws XPathExpressionException {
415        final String testExcludeList = System.getProperty(TEST_JS_EXCLUDE_LIST);
416
417        String[] testExcludeArray = {};
418        if (testExcludeList != null) {
419            testExcludeArray = testExcludeList.split(" ");
420        }
421        final Set<String> testExcludeSet = new HashSet<>(testExcludeArray.length);
422        for (final String test : testExcludeArray) {
423            testExcludeSet.add(test);
424        }
425
426        final String testExcludesFile = System.getProperty(TEST_JS_EXCLUDES_FILE);
427        if (testExcludesFile != null && !testExcludesFile.isEmpty()) {
428            try {
429                loadExcludesFile(testExcludesFile, testExcludeSet);
430            } catch (final XPathExpressionException e) {
431                System.err.println("Error: unable to load test excludes from " + testExcludesFile);
432                e.printStackTrace();
433                throw e;
434            }
435        }
436        return testExcludeSet;
437    }
438
439    private static void loadExcludesFile(final String testExcludesFile, final Set<String> testExcludeSet) throws XPathExpressionException {
440        final XPath xpath = XPathFactory.newInstance().newXPath();
441        final NodeList testIds = (NodeList)xpath.evaluate("/excludeList/test/@id", new InputSource(testExcludesFile), XPathConstants.NODESET);
442        for (int i = testIds.getLength() - 1; i >= 0; i--) {
443            testExcludeSet.add(testIds.item(i).getNodeValue());
444        }
445    }
446
447    private static Path[] getExcludeDirs() {
448        final String excludeDirs[] = System.getProperty(TEST_JS_EXCLUDE_DIR, "test/script/currently-failing").split(" ");
449        final Path[] excludePaths = new Path[excludeDirs.length];
450        final FileSystem fileSystem = FileSystems.getDefault();
451        int i = 0;
452        for (final String excludeDir : excludeDirs) {
453            excludePaths[i++] = fileSystem.getPath(excludeDir);
454        }
455        return excludePaths;
456    }
457}
458