summaryrefslogtreecommitdiff
path: root/python/testSrc/com/jetbrains/env/python/console/PyConsoleTask.java
blob: 9a242934042d327f213401c0fa8793ea6fe245d5 (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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package com.jetbrains.env.python.console;

import com.google.common.collect.Lists;
import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.frame.XValueChildrenList;
import com.jetbrains.env.PyExecutionFixtureTestTask;
import com.jetbrains.python.console.*;
import com.jetbrains.python.console.pydev.ConsoleCommunicationListener;
import com.jetbrains.python.debugger.PyDebugValue;
import com.jetbrains.python.debugger.PyDebuggerException;
import com.jetbrains.python.sdkTools.SdkCreationType;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @author traff
 */
public class PyConsoleTask extends PyExecutionFixtureTestTask {
  private boolean myProcessCanTerminate;

  protected PyConsoleProcessHandler myProcessHandler;
  protected PydevConsoleCommunication myCommunication;

  private boolean shouldPrintOutput = false;
  private PythonConsoleView myConsoleView;
  private Semaphore mySemaphore;
  private Semaphore mySemaphore0;
  private PydevConsoleExecuteActionHandler myExecuteHandler;

  public PyConsoleTask() {
    setWorkingFolder(getTestDataPath());
  }

  public PythonConsoleView getConsoleView() {
    return myConsoleView;
  }

  @Override
  public void setUp(final String testName) throws Exception {
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        try {
          if (myFixture == null) {
            PyConsoleTask.super.setUp(testName);
          }
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });
  }

  @NotNull
  protected String output() {
    return myConsoleView.getConsole().getHistoryViewer().getDocument().getText();
  }

  public void setProcessCanTerminate(boolean processCanTerminate) {
    myProcessCanTerminate = processCanTerminate;
  }

  @Override
  public void tearDown() throws Exception {
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        try {
          if (myConsoleView != null) {
            disposeConsole();
          }
          PyConsoleTask.super.tearDown();
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });
  }

  private void disposeConsole() throws InterruptedException {
    if (myCommunication != null) {
      UIUtil.invokeAndWaitIfNeeded(new Runnable() {
        @Override
        public void run() {
          try {
            myCommunication.close();
          }
          catch (Exception e) {
            e.printStackTrace();
          }
          myCommunication = null;
        }
      });
    }

    disposeConsoleProcess();

    if (myConsoleView != null) {
      new WriteAction() {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
          Disposer.dispose(myConsoleView);
          myConsoleView = null;
        }
      }.execute();
    }
  }

  @Override
  public void runTestOn(final String sdkHome) throws Exception {
    final Project project = getProject();

    final Sdk sdk = createTempSdk(sdkHome, SdkCreationType.EMPTY_SDK);

    setProcessCanTerminate(false);

    PydevConsoleRunner consoleRunner = PydevConsoleRunner.create(project, sdk, PyConsoleType.PYTHON, getWorkingFolder());
    before();

    mySemaphore0 = new Semaphore(0);

    consoleRunner.addConsoleListener(new PydevConsoleRunner.ConsoleListener() {
      @Override
      public void handleConsoleInitialized(LanguageConsoleView consoleView) {
        mySemaphore0.release();
      }
    });

    consoleRunner.run();

    waitFor(mySemaphore0);

    mySemaphore = new Semaphore(0);

    myConsoleView = consoleRunner.getConsoleView();
    myProcessHandler = (PyConsoleProcessHandler)consoleRunner.getProcessHandler();

    myExecuteHandler = (PydevConsoleExecuteActionHandler)consoleRunner.getConsoleExecuteActionHandler();

    myCommunication = consoleRunner.getPydevConsoleCommunication();

    myCommunication.addCommunicationListener(new ConsoleCommunicationListener() {
      @Override
      public void commandExecuted(boolean more) {
        mySemaphore.release();
      }

      @Override
      public void inputRequested() {
      }
    });

    myProcessHandler.addProcessListener(new ProcessAdapter() {
      @Override
      public void processTerminated(ProcessEvent event) {
        if (event.getExitCode() != 0 && !myProcessCanTerminate) {
          Assert.fail("Process terminated unexpectedly\n" + output());
        }
      }
    });

    OutputPrinter myOutputPrinter = null;
    if (shouldPrintOutput) {
      myOutputPrinter = new OutputPrinter();
      myOutputPrinter.start();
    }

    waitForOutput("PyDev console");

    try {
      testing();
      after();
    }
    finally {
      setProcessCanTerminate(true);

      if (myOutputPrinter != null) {
        myOutputPrinter.stop();
      }

      disposeConsole();
    }
  }

  private void disposeConsoleProcess() throws InterruptedException {
    myProcessHandler.destroyProcess();

    waitFor(myProcessHandler);

    if (!myProcessHandler.isProcessTerminated()) {
      if (!waitFor(myProcessHandler)) {
        if (!myProcessHandler.isProcessTerminated()) {
          throw new RuntimeException("Cannot stop console process");
        }
      }
    }
    myProcessHandler = null;
  }

  /**
   * Waits until all passed strings appear in output.
   * If they don't appear in time limit, then exception is raised.
   *
   * @param string
   * @throws InterruptedException
   */
  public void waitForOutput(String... string) throws InterruptedException {
    int count = 0;
    while (true) {
      List<String> missing = Lists.newArrayList();
      String out = output();
      boolean flag = true;
      for (String s : string) {
        if (!out.contains(s)) {
          flag = false;
          missing.add(s);
        }
      }
      if (flag) {
        break;
      }
      if (count > 10) {
        Assert.fail("Strings: <--\n" + StringUtil.join(missing, "\n---\n") + "-->" + "are not present in output.\n" + output());
      }
      Thread.sleep(2000);
      count++;
    }
  }

  protected void waitForReady() throws InterruptedException {
    int count = 0;
    while (!myExecuteHandler.isEnabled() || !canExecuteNow()) {
      if (count > 10) {
        Assert.fail("Console is not ready");
      }
      Thread.sleep(300);
      count++;
    }
  }

  protected boolean canExecuteNow() {
    return myExecuteHandler.canExecuteNow();
  }

  public void setShouldPrintOutput(boolean shouldPrintOutput) {
    this.shouldPrintOutput = shouldPrintOutput;
  }

  private class OutputPrinter {
    private Thread myThread;
    private int myLen = 0;

    public void start() {
      myThread = new Thread(new Runnable() {
        @Override
        public void run() {
          doJob();
        }
      });
      myThread.setDaemon(true);
      myThread.start();
    }

    private void doJob() {
      try {
        while (true) {
          printToConsole();

          Thread.sleep(500);
        }
      }
      catch (Exception ignored) {
      }
    }

    private synchronized void printToConsole() {
      String s = output();
      if (s.length() > myLen) {
        System.out.print(s.substring(myLen));
      }
      myLen = s.length();
    }

    public void stop() {
      printToConsole();
      myThread.interrupt();
    }
  }

  protected void exec(String command) throws InterruptedException {
    waitForReady();
    int p = mySemaphore.availablePermits();
    myConsoleView.executeInConsole(command);
    mySemaphore.acquire(p + 1);
    //waitForOutput(">>> " + command);
  }

  protected boolean hasValue(String varName, String value) throws PyDebuggerException {
    PyDebugValue val = getValue(varName);
    return val != null && value.equals(val.getValue());
  }

  protected void setValue(String varName, String value) throws PyDebuggerException {
    PyDebugValue val = getValue(varName);
    myCommunication.changeVariable(val, value);
  }
  
  protected PyDebugValue getValue(String varName) throws PyDebuggerException {
    XValueChildrenList l = myCommunication.loadFrame();

    if (l == null) {
      return null;
    }
    for (int i = 0; i < l.size(); i++) {
      String name = l.getName(i);
      if (varName.equals(name)) {
        return (PyDebugValue)l.getValue(i);
      }
    }
    
    return null;
  }
  
  protected List<String> getCompoundValueChildren(PyDebugValue value) throws PyDebuggerException {
    XValueChildrenList list = myCommunication.loadVariable(value);
    List<String> result = Lists.newArrayList();
    for (int i = 0; i<list.size(); i++) {
      result.add(((PyDebugValue)list.getValue(i)).getValue());
    }
    return result;
  }

  protected void input(String text) {
    myConsoleView.executeInConsole(text);
  }

  protected void waitForFinish() throws InterruptedException {
    waitFor(mySemaphore);
  }

  protected void execNoWait(final String command) {
    UIUtil.invokeLaterIfNeeded(new Runnable() {
      @Override
      public void run() {
        myConsoleView.executeCode(command, null);
      }
    });
  }

  protected void interrupt() {
    myCommunication.interrupt();
  }


  public void addTextToEditor(final String text) {
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        getConsoleView().getLanguageConsole().setInputText(text);
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      }
    }
    );
  }
}