aboutsummaryrefslogtreecommitdiff
path: root/test/src/jdk/nashorn/internal/test/framework/ScriptRunnable.java
blob: ee26061ea24bc3c6220053ac929a618c6bf8a859 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.test.framework;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jdk.nashorn.tools.Shell;
import org.testng.Assert;
import org.testng.ITest;
import org.testng.annotations.Test;

/**
 * Compiles a single JavaScript script source file and executes the resulting
 * class. Optionally, output from running the script is compared against the
 * corresponding .EXPECTED file.
 */
public final class ScriptRunnable extends AbstractScriptRunnable implements ITest {
    public ScriptRunnable(final String framework, final File testFile, final List<String> engineOptions, final Map<String, String> testOptions,  final List<String> scriptArguments) {
        super(framework, testFile, engineOptions, testOptions, scriptArguments);

        if (this.shouldRun) {
          // add --dump-on-error option always so that we can get detailed error msg.
          engineOptions.add("-doe");
        }
    }

    @Override
    public String getTestName() {
        return testFile.getAbsolutePath();
    }

    @Test
    @Override
    public void runTest() throws IOException {
        try {
            super.runTest();
        } catch(final AssertionError e) {
            throw new AssertionError("Failed executing test " + testFile, e);
        }
    }

    @Override
    protected void execute() {
        if (fork) {
            executeInNewProcess();
        } else {
            executeInThisProcess();
        }
    }

    // avoid direct System.out.println - use reporter to capture
    @Override
    protected void log(final String msg) {
        org.testng.Reporter.log(msg, true);
    }

    // throw Assert fail - but log as well so that user can see this at console
    @Override
    protected void fail(final String msg) {
        log(msg);
        Assert.fail(msg);
    }

    @Override
    protected void compile() throws IOException {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final ByteArrayOutputStream err = new ByteArrayOutputStream();
        final List<String> args = getCompilerArgs();
        int errors;

        try {
            errors = evaluateScript(out, err, args.toArray(new String[args.size()]));
        } catch (final AssertionError e) {
            final PrintWriter writer = new PrintWriter(err);
            e.printStackTrace(writer);
            writer.flush();
            errors = 1;
        }

        if (errors != 0 || checkCompilerMsg) {
            if (expectCompileFailure || checkCompilerMsg) {
                final PrintStream outputDest = new PrintStream(new FileOutputStream(errorFileName));
                TestHelper.dumpFile(outputDest, new StringReader(new String(err.toByteArray())));
                outputDest.println("--");
            } else {
                log(new String(err.toByteArray()));
            }

            if (errors != 0 && !expectCompileFailure) {
                fail(String.format("%d errors compiling %s", errors, testFile));
            }
            if (checkCompilerMsg) {
                compare(errorFileName, expectedFileName, true);
            }
        }

        if (expectCompileFailure && errors == 0) {
            fail(String.format("No errors encountered compiling negative test %s", testFile));
        }
    }

    private void executeInThisProcess() {
        final List<String> args = getRuntimeArgs();
        final File outputFileHandle = new File(outputFileName);
        final File errorFileHandle  = new File(errorFileName);

        try (OutputStream outputFile = new FileOutputStream(outputFileName); OutputStream errorFile = new FileOutputStream(errorFileName)) {
            final int errors = evaluateScript(outputFile, errorFile, args.toArray(new String[args.size()]));

            if (errors != 0 || errorFileHandle.length() > 0) {
                if (expectRunFailure) {
                    return;
                }

                if (!ignoreStdError) {
                    if (outputFileHandle.length() > 0) {
                        TestHelper.dumpFile(outputFileHandle);
                    }
                    fail(TestHelper.fullContent(errorFileHandle));
                }
            }

            if (compare) {
                compare(outputFileName, expectedFileName, false);
            }
        } catch (final IOException e) {
            if (!expectRunFailure) {
                fail("Failure running test " + testFile + ": " + e.getMessage());
                // else success
            }
        }
    }

    private void executeInNewProcess() {

        final String separator = System.getProperty("file.separator");
        final List<String> cmd = new ArrayList<>();

        cmd.add(System.getProperty("java.home") + separator + "bin" + separator + "java");
        cmd.add("-Djava.ext.dirs=dist");
        for (final String str : forkJVMOptions) {
            if(!str.isEmpty()) {
                cmd.add(str);
        }
        }
        cmd.add(Shell.class.getName());
        // now add the rest of the "in process" runtime arguments
        cmd.addAll(getRuntimeArgs());

        final File outputFileHandle = new File(outputFileName);
        final File errorFileHandle = new File(errorFileName);

        try {
            final ProcessBuilder pb = new ProcessBuilder(cmd);
            pb.redirectOutput(outputFileHandle);
            pb.redirectError(errorFileHandle);
            final Process process = pb.start();

            process.waitFor();

            if (errorFileHandle.length() > 0) {
                if (expectRunFailure) {
                    return;
                }
                if (!ignoreStdError) {
                    if (outputFileHandle.length() > 0) {
                        TestHelper.dumpFile(outputFileHandle);
                    }
                    fail(TestHelper.fullContent(errorFileHandle));
                }
            }

            if (compare) {
                compare(outputFileName, expectedFileName, false);
            }
        } catch (final IOException | InterruptedException e) {
            if (!expectRunFailure) {
                fail("Failure running test " + testFile + ": " + e.getMessage());
                // else success
            }
        }
    }

    private void compare(final String outputFileName0, final String expectedFileName0, final boolean compareCompilerMsg) throws IOException {
        final File expectedFile = new File(expectedFileName0);

        BufferedReader expected;
        if (expectedFile.exists()) {
            expected = new BufferedReader(new InputStreamReader(new FileInputStream(expectedFileName0)));
            // copy expected file overwriting existing file and preserving last
            // modified time of source
            try {
                Files.copy(FileSystems.getDefault().getPath(expectedFileName0),
                        FileSystems.getDefault().getPath(copyExpectedFileName),
                        StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.COPY_ATTRIBUTES);
            } catch (final IOException ex) {
                fail("failed to copy expected " + expectedFileName + " to " + copyExpectedFileName + ": " + ex.getMessage());
            }
        } else {
            expected = new BufferedReader(new StringReader(""));
        }

        final BufferedReader actual = new BufferedReader(new InputStreamReader(new FileInputStream(outputFileName0)));
        compare(actual, expected, compareCompilerMsg);
    }
}