1414import java .io .IOException ;
1515import java .time .Duration ;
1616import java .util .ArrayList ;
17+ import java .util .Arrays ;
1718import java .util .Collections ;
1819import java .util .List ;
1920import java .util .Map ;
21+ import java .util .stream .Collectors ;
22+ import java .util .stream .Stream ;
2023
2124import static org .junit .jupiter .api .Assertions .assertEquals ;
2225
@@ -61,7 +64,15 @@ protected static Container.ExecResult executeInKernel(String snippet) throws IOE
6164 }
6265
6366 protected static Container .ExecResult executeInKernel (String snippet , Map <String , String > env ) throws IOException , InterruptedException {
67+ long snippetLines = snippet .lines ().count ();
6468 String snippetEscaped = snippet .replace ("\\ " , "\\ \\ " ).replace ("\" " , "\\ \" " );
69+ String snippetFeeding = Arrays .stream (snippetEscaped .split ("\n " ))
70+ .flatMap (line -> Stream .of (
71+ "p.expect(r'In \\ [\\ d+\\ ]:')" ,
72+ "p.sendline(\" " + line + "\" )"
73+ ))
74+ .collect (Collectors .joining ("\n " ));
75+
6576 String pexpectScript = String .join ("\n " ,
6677 "import pexpect, sys, os, time" ,
6778 "env = os.environ.copy()" ,
@@ -70,15 +81,10 @@ protected static Container.ExecResult executeInKernel(String snippet, Map<String
7081 "p=pexpect.spawn('" + venvCommand ("jupyter" ) + "', "
7182 + "['console', '--kernel=java', '--no-confirm-exit'], "
7283 + "env=env, timeout=60, encoding='utf-8')" ,
73- "p.logfile = sys.stdout" ,
74- "p.expect(r'In \\ [\\ d+\\ ]:', timeout=10)" ,
75- "p.send(\" \" \" " + snippetEscaped + "\\ n\" \" \" )" ,
76- "p.expect(r'In \\ [\\ d+\\ ]:')" ,
77- "p.logfile.flush()" ,
78- "time.sleep(0.1)" ,
79- "p.sendeof()" ,
80- "p.expect(pexpect.EOF, timeout=5)" ,
81- "p.close()"
84+ "p.logfile_read = sys.stdout" ,
85+ snippetFeeding ,
86+ "p.expect(r'In \\ [" + (snippetLines + 1 ) + "\\ ]:')" ,
87+ "p.close(force=True)"
8288 );
8389 String [] containerCommand = new String []{venvCommand ("python" ), "-c" , pexpectScript };
8490 Container .ExecResult execResult = container .execInContainer (ExecConfig .builder ()
0 commit comments