summaryrefslogtreecommitdiff
path: root/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java
blob: 78f980aea83d5f8ce0fed27e5dafc606ef87346a (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: Jul 6, 2005
 * Time: 10:49:05 PM
 */
package com.theoryinpractice.testng.ui;

import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.testframework.*;
import com.intellij.execution.testframework.actions.ScrollToTestSourceAction;
import com.intellij.execution.testframework.ui.TestResultsPanel;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.util.ColorProgressBar;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.ClassUtil;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.table.TableView;
import com.intellij.util.OpenSourceUtil;
import com.intellij.util.config.ToggleBooleanProperty;
import com.theoryinpractice.testng.configuration.TestNGConfiguration;
import com.theoryinpractice.testng.model.*;
import com.theoryinpractice.testng.util.TestNGUtil;
import org.jetbrains.annotations.NonNls;
import org.testng.remote.strprotocol.MessageHelper;
import org.testng.remote.strprotocol.TestResultMessage;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;

public class TestNGResults extends TestResultsPanel implements TestFrameworkRunningModel {
  @NonNls private static final String TESTNG_SPLITTER_PROPERTY = "TestNG.Splitter.Proportion";

  private final TableView resultsTable;

  private final TestNGResultsTableModel model;
  private TestNGTestTreeView tree;

  private final Project project;
  private int count;
  private int total = 0;
  private final Set<TestProxy> failed = new HashSet<TestProxy>();
  private final Map<TestResultMessage, List<TestProxy>> started = new HashMap<TestResultMessage, List<TestProxy>>();
  private TestProxy failedToStart = null;
  private long start;
  private long end;
  private TestTreeBuilder treeBuilder;
  private Animator animator;

  private final TreeRootNode rootNode;
  private static final String NO_PACKAGE = "No Package";
  private TestNGResults.OpenSourceSelectionListener openSourceListener;
  private int myStatus = MessageHelper.PASSED_TEST;
  private Set<String> startedMethods = new HashSet<String>();
  private TestProxy myLastSelected;

  public TestNGResults(final JComponent component,
                       final TestNGConfiguration configuration,
                       final TestNGConsoleView console,
                       final ExecutionEnvironment environment) {
    super(component, console.getConsole().createConsoleActions(), console.getProperties(),
          environment, TESTNG_SPLITTER_PROPERTY, 0.5f);
    this.project = configuration.getProject();

    model = new TestNGResultsTableModel(project);
    resultsTable = new TableView(model);
    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent e) {
        final Object result = resultsTable.getSelectedObject();
        if (result instanceof TestResultMessage) {
          final String testClass = ((TestResultMessage)result).getTestClass();
          final PsiClass psiClass = ClassUtil.findPsiClass(PsiManager.getInstance(project), testClass);
          if (psiClass != null) {
            final String method = ((TestResultMessage)result).getMethod();
            if (method != null) {
              final PsiMethod[] psiMethods = psiClass.findMethodsByName(method, false);
              if (psiMethods.length > 0) {
                psiMethods[0].navigate(true);
              }
            }
            psiClass.navigate(true);
            return true;
          }
        }
        return false;
      }
    }.installOn(resultsTable);

    rootNode = new TreeRootNode();
    console.getUnboundOutput().addChild(rootNode);
  }

  protected JComponent createTestTreeView() {
    tree = new TestNGTestTreeView();

    final TestTreeStructure structure = new TestTreeStructure(project, rootNode);
    tree.attachToModel(this);
    treeBuilder = new TestTreeBuilder(tree, structure);
    Disposer.register(this, treeBuilder);

    animator = new Animator(this, treeBuilder);

    openSourceListener = new OpenSourceSelectionListener();
    tree.getSelectionModel().addTreeSelectionListener(openSourceListener);

    TrackRunningTestUtil.installStopListeners(tree, this, new Pass<AbstractTestProxy>() {
      @Override
      public void pass(AbstractTestProxy abstractTestProxy) {
        myLastSelected = (TestProxy)abstractTestProxy;
      }
    });

    return tree;
  }

  @Override
  protected ToolbarPanel createToolbarPanel() {
    final ToolbarPanel panel = new ToolbarPanel(getProperties(), myEnvironment, this){
      @Override
      protected void appendAdditionalActions(DefaultActionGroup actionGroup,
                                             TestConsoleProperties properties,
                                             ExecutionEnvironment environment, JComponent parent) {
        super.appendAdditionalActions(actionGroup, properties, environment, parent);
        actionGroup.addAction(new ToggleBooleanProperty(
          ExecutionBundle.message("junit.runing.info.include.non.started.in.rerun.failed.action.name"),
                                                    null,
                                                    AllIcons.RunConfigurations.IncludeNonStartedTests_Rerun,
                                                    properties, TestConsoleProperties.INCLUDE_NON_STARTED_IN_RERUN_FAILED)).setAsSecondary(true);
      }
    };
    panel.setModel(this);
    return panel;
  }

  public TestConsoleProperties getProperties() {
    return myProperties;
  }

  protected JComponent createStatisticsPanel() {
    final JPanel panel = new JPanel(new BorderLayout()); //do not remove wrapper panel 
    panel.add(ScrollPaneFactory.createScrollPane(resultsTable), BorderLayout.CENTER);
    return panel;
  }

  private void updateStatusLine() {
    myStatusLine.setText(getStatusLine());
  }

  public int getStatus() {
    return myStatus;
  }

  public String getStatusLine() {
    StringBuffer sb = new StringBuffer();
    if (end == 0 && start > 0) {
      sb.append("Running: ");
    }
    else {
      if (failed.size() > 0) sb.append("Failed: ").append(failed.size()).append("   ");
      sb.append("Done: ");
    }
    sb.append(count).append(" of ").append(total);
    if (end == 0) {
      if (failed.size() > 0) {
        sb.append("   Failed: ").append(failed.size());
      }
    }
    else {
      final long time = end - start;
      sb.append(" (").append(time == 0 ? "0.0 s" : NumberFormat.getInstance().format((double)time / 1000.0) + " s").append(")  ");
    }
    return sb.toString();
  }
  
  public String getTime() {
    final long time = end - start;
    return time == 0 ? "0.0 s" : NumberFormat.getInstance().format((double)time / 1000.0) + " s";
  }

  public TestProxy testStarted(TestResultMessage result) {
    return testStarted(result, true);
  }

  public TestProxy testStarted(TestResultMessage result, boolean registerDups) {
    TestProxy classNode = getPackageClassNodeFor(result);
    TestProxy proxy = new TestProxy();
    proxy.setParent(classNode);
    proxy.setResultMessage(result);
    synchronized (started) {
      if (registerDups) {
        List<TestProxy> dups = started.get(result);
        if (dups == null) {
          dups = new ArrayList<TestProxy>();
          started.put(result, dups);
        }
        dups.add(proxy);
      }
    }
    final String testMethodDescriptor = result.getTestClass() + TestProxy.toDisplayText(result, project);
    if (startedMethods.contains(testMethodDescriptor)) {
      total++;
    }
    else {
      startedMethods.add(testMethodDescriptor);
    }
    animator.setCurrentTestCase(proxy);
    treeBuilder.addItem(classNode, proxy);
    //treeBuilder.repaintWithParents(proxy);
    count++;
    if (count > total) total = count;
    if (myLastSelected == proxy) {
      myLastSelected = null;
    }
    if (myLastSelected == null && TestConsoleProperties.TRACK_RUNNING_TEST.value(myProperties)) {
      selectTest(proxy);
    }
    return proxy;
  }

  public void addTestResult(final TestResultMessage result, int exceptionMark) {
    TestProxy testCase;
    synchronized (started) {
      final List<TestProxy> dups = started.get(result);
      testCase = dups == null || dups.isEmpty() ? null : dups.remove(0);
    }
    if (testCase == null) {
      final PsiElement element = getPackageClassNodeFor(result).getPsiElement();
      if (element instanceof PsiClass) {
        final PsiMethod[] methods = ApplicationManager.getApplication().runReadAction(
          new Computable<PsiMethod[]>() {
            public PsiMethod[] compute() {
              return ((PsiClass)element).findMethodsByName(result.getMethod(), true);
            }
          }
        );
        if (methods.length > 0 &&
            methods[0] != null &&
            !AnnotationUtil.isAnnotated(methods[0], Arrays.asList(TestNGUtil.CONFIG_ANNOTATIONS_FQN))) {
          for (List<TestProxy> proxies : started.values()) {
            if (proxies != null) {
              for (TestProxy proxy : proxies) {
                if (methods[0].equals(proxy.getPsiElement())) {
                  testCase = proxy;
                  break;
                }
              }
            }
          }
          if (testCase == null) {
            testCase = testStarted(result, false);
            testCase.appendStacktrace(result);
          }
        }
      }
    }

    if (testCase != null) {
      testCase.setResultMessage(result);
      testCase.setTearDownFailure(failedToStart != null);
      failedToStart = null;

      if (result.getResult() == MessageHelper.FAILED_TEST) {
        failed.add(testCase);
      }
      model.addTestResult(result);
    }
    else {
      //do not remember testresultmessage: test hierarchy is not set
      testCase = new TestProxy(TestProxy.toDisplayText(result, project));
      testCase.appendStacktrace(result);
      if (failedToStart != null) {
        failedToStart.addChild(testCase);
        failedToStart.setTearDownFailure(true);
      }
      else {
        failedToStart = testCase;
      }
    }

    testCase.setExceptionMark(exceptionMark);
    AbstractTestProxy.flushOutput(testCase);

    if (result.getResult() == MessageHelper.FAILED_TEST) {
      myStatusLine.setStatusColor(ColorProgressBar.RED);
      myStatus = MessageHelper.FAILED_TEST;
    }
    else if (result.getResult() == MessageHelper.SKIPPED_TEST && myStatus == MessageHelper.PASSED_TEST) {
      myStatus = MessageHelper.SKIPPED_TEST;
    }
    myStatusLine.setFraction((double)count / total);
    updateStatusLine();
    TestsUIUtil.showIconProgress(project, count, total, failed.size());
  }

  private TestProxy getPackageClassNodeFor(final TestResultMessage result) {
    TestProxy owner = treeBuilder.getRoot();
    final String packageName1 = StringUtil.getPackageName(result.getTestClass());
    String packageName = packageName1.length() == 0 ? NO_PACKAGE : packageName1;
    owner = getChildNodeNamed(owner, packageName);
    if (owner.getPsiElement() == null) {
      owner.setPsiElement(JavaPsiFacade.getInstance(project).findPackage(packageName));
    }
    owner = getChildNodeNamed(owner, StringUtil.getShortName(result.getTestClass()));
    //look up the psiclass now
    if (owner.getPsiElement() == null) {
      final TestProxy finalOwner = owner;
      ApplicationManager.getApplication().runReadAction(new Runnable() {
        public void run() {
          finalOwner.setPsiElement(ClassUtil.findPsiClass(PsiManager.getInstance(project), result.getTestClass()));
        }
      });
    }
    return owner;
  }

  private TestProxy getChildNodeNamed(TestProxy currentNode, String node) {
    for (TestProxy child : currentNode.getChildren()) {
      if (child.getName().equals(node)) {
        return child;
      }
    }

    TestProxy child = new TestProxy(node);
    treeBuilder.addItem(currentNode, child);
    return child;
  }

  public void selectTest(TestProxy proxy) {
    if (proxy == null) return;
    treeBuilder.select(proxy, null);
  }

  public void setTotal(int total) {
    this.total += total;
  }

  public void start() {
    if (start == 0) {
      start = System.currentTimeMillis();
    }
    treeBuilder.select(rootNode);
    rootNode.setInProgress(true);
    rootNode.setStarted(true);
  }

  public void finish(final boolean started) {
    if (start > 0) {
      end = System.currentTimeMillis();
    }
    LvcsHelper.addLabel(this);

    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        animator.stopMovie();
        updateStatusLine();
        if (total > count || myStatus == MessageHelper.SKIPPED_TEST) {
          myStatusLine.setStatusColor(ColorProgressBar.YELLOW);
        }
        else if (myStatus == MessageHelper.FAILED_TEST) {
          myStatusLine.setStatusColor(ColorProgressBar.RED);
        }
        else {
          myStatusLine.setStatusColor(ColorProgressBar.GREEN);
        }
        rootNode.setInProgress(false);
        TestStatusListener.notifySuiteFinished(rootNode, project);
        if (TestNGConsoleProperties.SELECT_FIRST_DEFECT.value(myProperties)) {
          selectTest(rootNode.getFirstDefect());
        }
        else {
          final DefaultMutableTreeNode node = treeBuilder.getNodeForElement(rootNode);
          if (node != null && myLastSelected == null) {
            tree.getSelectionModel().setSelectionPath(new TreePath(node));
          }
        }
        tree.repaint();
        TestsUIUtil.notifyByBalloon(project, started, rootNode, getProperties(), "in " + getTime());
      }
    });
  }

  public void setFilter(final Filter filter) {
    getTreeStructure().setFilter(filter);
    treeBuilder.updateFromRoot();
  }

  public boolean isRunning() {
    return rootNode.isInProgress();
  }

  public TestTreeView getTreeView() {
    return tree;
  }

  @Override
  public TestTreeBuilder getTreeBuilder() {
    return treeBuilder;
  }

  public boolean hasTestSuites() {
    return rootNode.getChildren().size() > 0;
  }

  public TestProxy getRoot() {
    return rootNode;
  }

  public void selectAndNotify(final AbstractTestProxy testProxy) {
    selectTest((TestProxy)testProxy);
  }

  public TestTreeStructure getTreeStructure() {
    return (TestTreeStructure)treeBuilder.getTreeStructure();
  }

  public void rebuildTree() {
    treeBuilder.updateFromRoot();
    tree.invalidate();
  }

  public void dispose() {
    super.dispose();
    tree.getSelectionModel().removeTreeSelectionListener(openSourceListener);
    TestsUIUtil.clearIconProgress(project);
  }

  public TestProxy getFailedToStart() {
    return failedToStart;
  }

  public void setFailedToStart(TestProxy failedToStart) {
    this.failedToStart = failedToStart;
  }

  public boolean hasFinishedTests() {
    return count > 0;
  }

  private class OpenSourceSelectionListener implements TreeSelectionListener {

    public void valueChanged(TreeSelectionEvent e) {
      TreePath path = e.getPath();
      if (path == null) return;
      TestProxy proxy = (TestProxy)tree.getSelectedTest();
      if (proxy == null) return;
      if (ScrollToTestSourceAction.isScrollEnabled(TestNGResults.this)) {
        OpenSourceUtil.openSourcesFrom(tree, false);
      }
    }
  }
}