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