Path: blob/master/test/langtools/jdk/jshell/ExternalEditorTest.java
40930 views
/*1* Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary Testing external editor.26* @bug 8143955 8080843 8163816 8143006 8169828 8171130 8162989 821080827* @modules jdk.jshell/jdk.internal.jshell.tool28* @build ReplToolTesting CustomEditor EditorTestBase29* @run testng ExternalEditorTest30* @key intermittent31*/3233import java.io.BufferedWriter;34import java.io.DataInputStream;35import java.io.DataOutputStream;36import java.io.IOException;37import java.io.UncheckedIOException;38import java.net.ServerSocket;39import java.net.Socket;40import java.net.SocketTimeoutException;41import java.nio.charset.StandardCharsets;42import java.nio.file.Files;43import java.nio.file.Path;44import java.nio.file.Paths;45import java.util.concurrent.ExecutionException;46import java.util.concurrent.Future;47import java.util.function.Consumer;4849import org.testng.annotations.AfterClass;50import org.testng.annotations.BeforeClass;51import org.testng.annotations.Test;5253import static org.testng.Assert.assertEquals;54import static org.testng.Assert.assertFalse;55import static org.testng.Assert.assertTrue;56import static org.testng.Assert.fail;5758public class ExternalEditorTest extends EditorTestBase {5960private static Path executionScript;61private static ServerSocket listener;6263private DataInputStream inputStream;64private DataOutputStream outputStream;6566@Override67public void writeSource(String s) {68try {69outputStream.writeInt(CustomEditor.SOURCE_CODE);70byte[] bytes = s.getBytes(StandardCharsets.UTF_8);71outputStream.writeInt(bytes.length);72outputStream.write(bytes);73} catch (IOException e) {74throw new UncheckedIOException(e);75}76}7778@Override79public String getSource() {80return readString(CustomEditor.GET_SOURCE_CODE);81}8283private void sendCode(int code) {84try {85outputStream.writeInt(code);86} catch (IOException e) {87throw new UncheckedIOException(e);88}89}9091@Override92public void accept() {93sendCode(CustomEditor.ACCEPT_CODE);94}9596@Override97public void exit() {98sendCode(CustomEditor.EXIT_CODE);99inputStream = null;100outputStream = null;101}102103@Override104public void cancel() {105sendCode(CustomEditor.CANCEL_CODE);106}107108protected String getFilename() {109return readString(CustomEditor.GET_FILENAME);110}111112private String readString(int code) {113try {114outputStream.writeInt(code);115int length = inputStream.readInt();116byte[] bytes = new byte[length];117inputStream.readFully(bytes);118return new String(bytes, StandardCharsets.UTF_8);119} catch (IOException e) {120throw new UncheckedIOException(e);121}122}123124@Override125public void testEditor(boolean defaultStartup, String[] args, ReplTest... tests) {126ReplTest[] t = new ReplTest[tests.length + 1];127t[0] = a -> assertCommandCheckOutput(a, "/set editor " + executionScript,128assertStartsWith("| Editor set to: " + executionScript));129System.arraycopy(tests, 0, t, 1, tests.length);130super.testEditor(defaultStartup, args, t);131}132133@Test134public void testStatementSemicolonAddition() {135testEditor(136a -> assertCommand(a, "if (true) {}", ""),137a -> assertCommand(a, "if (true) {} else {}", ""),138a -> assertCommand(a, "Object o", "o ==> null"),139a -> assertCommand(a, "if (true) o = new Object() { int x; }", ""),140a -> assertCommand(a, "if (true) o = new Object() { int y; }", ""),141a -> assertCommand(a, "System.err.flush()", ""), // test still ; for expression statement142a -> assertEditOutput(a, "/ed", "", () -> {143assertEquals(getSource(),144"if (true) {}\n" +145"if (true) {} else {}\n" +146"Object o;\n" +147"if (true) o = new Object() { int x; };\n" +148"if (true) o = new Object() { int y; };\n" +149"System.err.flush();\n");150exit();151})152);153}154155@Test156public void testTempFileDeleted() {157String[] fna = new String[1];158testEditor(159a -> assertVariable(a, "int", "a", "0", "0"),160a -> assertEditOutput(a, "/ed 1", "a ==> 10", () -> {161fna[0] = getFilename();162assertTrue(Files.exists(Paths.get(fna[0])), "Test set-up failed: " + fna[0]);163writeSource("\n\n\nint a = 10;\n\n\n");164exit();165}),166a -> assertCommand(a, "if (true) {} else {}", "")167);168assertFalse(Files.exists(Paths.get(fna[0])), "File not deleted: " + fna[0]);169}170171private static boolean isWindows() {172return System.getProperty("os.name").startsWith("Windows");173}174175@BeforeClass176public static void setUpExternalEditorTest() throws IOException {177listener = new ServerSocket(0);178listener.setSoTimeout(30000);179int localPort = listener.getLocalPort();180181executionScript = Paths.get(isWindows() ? "editor.bat" : "editor.sh").toAbsolutePath();182Path java = Paths.get(System.getProperty("java.home")).resolve("bin").resolve("java");183try (BufferedWriter writer = Files.newBufferedWriter(executionScript)) {184if(!isWindows()) {185writer.append(java.toString()).append(" ")186.append(" -cp ").append(System.getProperty("java.class.path"))187.append(" CustomEditor ").append(Integer.toString(localPort)).append(" $@");188executionScript.toFile().setExecutable(true);189} else {190writer.append(java.toString()).append(" ")191.append(" -cp ").append(System.getProperty("java.class.path"))192.append(" CustomEditor ").append(Integer.toString(localPort)).append(" %*");193}194}195}196197private Future<?> task;198@Override199void assertEdit(boolean after, String cmd,200Consumer<String> checkInput, Consumer<String> checkOutput, Action action) {201if (!after) {202setCommandInput(cmd + "\n");203task = getExecutor().submit(() -> {204try (Socket socket = listener.accept()) {205inputStream = new DataInputStream(socket.getInputStream());206outputStream = new DataOutputStream(socket.getOutputStream());207checkInput.accept(getSource());208action.accept();209} catch (SocketTimeoutException e) {210fail("Socket timeout exception.\n Output: " + getCommandOutput() +211"\n, error: " + getCommandErrorOutput());212} catch (Throwable e) {213shutdownEditor();214if (e instanceof AssertionError) {215throw (AssertionError) e;216}217throw new RuntimeException(e);218}219});220} else {221try {222task.get();223checkOutput.accept(getCommandOutput());224} catch (ExecutionException e) {225if (e.getCause() instanceof AssertionError) {226throw (AssertionError) e.getCause();227}228throw new RuntimeException(e);229} catch (Exception e) {230throw new RuntimeException(e);231}232}233}234235@Override236public void shutdownEditor() {237if (outputStream != null) {238exit();239}240}241242@Test243public void setUnknownEditor() {244test(245a -> assertCommand(a, "/set editor UNKNOWN", "| Editor set to: UNKNOWN"),246a -> assertCommand(a, "int a;", null),247a -> assertCommandOutputStartsWith(a, "/ed 1",248"| Edit Error:")249);250}251252@Test(enabled = false) // TODO 8159229253public void testRemoveTempFile() {254test(new String[]{"--no-startup"},255a -> assertCommandCheckOutput(a, "/set editor " + executionScript,256assertStartsWith("| Editor set to: " + executionScript)),257a -> assertVariable(a, "int", "a", "0", "0"),258a -> assertEditOutput(a, "/ed 1", assertStartsWith("| Edit Error: Failure in read edit file:"), () -> {259sendCode(CustomEditor.REMOVE_CODE);260exit();261}),262a -> assertCommandCheckOutput(a, "/vars", assertVariables())263);264}265266@AfterClass267public static void shutdown() throws IOException {268executorShutdown();269if (listener != null) {270listener.close();271}272}273}274275276