<commit_before>/*
 * Copyright 2000-2016 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.
 */
package com.intellij.codeInsight.daemon.quickFix;

import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtil;
import com.intellij.testFramework.LightPlatformCodeInsightTestCase;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.UIUtil;
import junit.framework.ComparisonFailure;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

import java.io.File;
import java.io.IOException;
import java.util.List;

public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase {
  @NonNls protected static final String BEFORE_PREFIX = "before";
  @NonNls protected static final String AFTER_PREFIX = "after";

  private static QuickFixTestCase myWrapper;

  @Override
  protected void tearDown() throws Exception {
    myWrapper = null;
    super.tearDown();
  }

  protected boolean shouldBeAvailableAfterExecution() {
    return false;
  }

  private static void doTestFor(@NotNull String testName, @NotNull QuickFixTestCase quickFixTestCase) {
    final String relativePath = ObjectUtils.notNull(quickFixTestCase.getBasePath(), "") + "/" + BEFORE_PREFIX + testName;
    final String testFullPath = quickFixTestCase.getTestDataPath().replace(File.separatorChar, '/') + relativePath;
    final File testFile = new File(testFullPath);
    CommandProcessor.getInstance().executeCommand(quickFixTestCase.getProject(), () -> {
      try {
        String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET));
        quickFixTestCase.configureFromFileText(testFile.getName(), contents);
        quickFixTestCase.bringRealEditorBack();
        final ActionHint actionHint = quickFixTestCase.parseActionHintImpl(quickFixTestCase.getFile(), contents);

        quickFixTestCase.beforeActionStarted(testName, contents);

        try {
          myWrapper = quickFixTestCase;
          quickFixTestCase.doAction(actionHint, testFullPath, testName);
        }
        finally {
          myWrapper = null;
          quickFixTestCase.afterActionCompleted(testName, contents);
        }
      }
      catch (ComparisonFailure e) {
        throw e;
      }
      catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(testName + " failed");
      }
    }, "", "");
  }

  protected void afterActionCompleted(final String testName, final String contents) {
  }

  protected void beforeActionStarted(final String testName, final String contents) {
  }

  public static void doAction(@NotNull ActionHint actionHint,
                              String testFullPath,
                              String testName,
                              QuickFixTestCase quickFix) throws Exception {
    IntentionAction action = actionHint.findAndCheck(quickFix.getAvailableActions(),
                                                     () -> getTestInfo(testFullPath, quickFix));
    if (action != null) {
      String text = action.getText();
      quickFix.invoke(action);
      UIUtil.dispatchAllInvocationEvents();
      UIUtil.dispatchAllInvocationEvents();
      if (!quickFix.shouldBeAvailableAfterExecution()) {
        final IntentionAction afterAction = quickFix.findActionWithText(text);
        if (afterAction != null) {
          fail("Action '" + text + "' is still available after its invocation in test " + testFullPath);
        }
      }
      String expectedFilePath = ObjectUtils.notNull(quickFix.getBasePath(), "") + "/" + AFTER_PREFIX + testName;
      quickFix.checkResultByFile("In file :" + expectedFilePath, expectedFilePath, false);

      String familyName = action.getFamilyName();
      if (StringUtil.isEmptyOrSpaces(familyName)) {
        fail("Action '" + text + "' provides empty family name which means that user would see action with empty presentable text in Inspection Results");
      }
    }
  }

  private static String getTestInfo(String testFullPath, QuickFixTestCase quickFix) {
    String infos = StreamEx.of(quickFix.doHighlighting())
      .filter(info -> info.getSeverity() != HighlightInfoType.SYMBOL_TYPE_SEVERITY)
      .map(info -> {
        String fixes = "";
        if (info.quickFixActionRanges != null) {
          fixes = StreamEx.of(info.quickFixActionRanges)
            .map(p -> p.getSecond()+" "+p.getFirst())
            .mapLastOrElse("|- "::concat, "\\- "::concat)
            .map(str -> "        " + str + "\n")
            .joining();
        }
        return info.getSeverity() +
               ": (" + info.getStartOffset() + "," + info.getEndOffset() + ") '" +
               info.getText() + "': " + info.getDescription() + "\n" + fixes;
      })
      .joining("       ");
    return "Test: " + testFullPath + "\n" +
           "Language level: " + PsiUtil.getLanguageLevel(quickFix.getProject()) + "\n" +<commit_msg>check stub wellformedness after intention invocation in tests<commit_after>/*
 * Copyright 2000-2016 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.
 */
package com.intellij.codeInsight.daemon.quickFix;

import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtil;
import com.intellij.testFramework.LightPlatformCodeInsightTestCase;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.UIUtil;
import junit.framework.ComparisonFailure;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

import java.io.File;
import java.io.IOException;
import java.util.List;

public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase {
  @NonNls protected static final String BEFORE_PREFIX = "before";
  @NonNls protected static final String AFTER_PREFIX = "after";

  private static QuickFixTestCase myWrapper;

  @Override
  protected void tearDown() throws Exception {
    myWrapper = null;
    super.tearDown();
  }

  protected boolean shouldBeAvailableAfterExecution() {
    return false;
  }

  private static void doTestFor(@NotNull String testName, @NotNull QuickFixTestCase quickFixTestCase) {
    final String relativePath = ObjectUtils.notNull(quickFixTestCase.getBasePath(), "") + "/" + BEFORE_PREFIX + testName;
    final String testFullPath = quickFixTestCase.getTestDataPath().replace(File.separatorChar, '/') + relativePath;
    final File testFile = new File(testFullPath);
    CommandProcessor.getInstance().executeCommand(quickFixTestCase.getProject(), () -> {
      try {
        String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET));
        quickFixTestCase.configureFromFileText(testFile.getName(), contents);
        quickFixTestCase.bringRealEditorBack();
        final ActionHint actionHint = quickFixTestCase.parseActionHintImpl(quickFixTestCase.getFile(), contents);

        quickFixTestCase.beforeActionStarted(testName, contents);

        try {
          myWrapper = quickFixTestCase;
          quickFixTestCase.doAction(actionHint, testFullPath, testName);
        }
        finally {
          myWrapper = null;
          quickFixTestCase.afterActionCompleted(testName, contents);
        }
      }
      catch (ComparisonFailure e) {
        throw e;
      }
      catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(testName + " failed");
      }
    }, "", "");
  }

  protected void afterActionCompleted(final String testName, final String contents) {
  }

  protected void beforeActionStarted(final String testName, final String contents) {
  }

  public static void doAction(@NotNull ActionHint actionHint,
                              String testFullPath,
                              String testName,
                              QuickFixTestCase quickFix) throws Exception {
    IntentionAction action = actionHint.findAndCheck(quickFix.getAvailableActions(),
                                                     () -> getTestInfo(testFullPath, quickFix));
    if (action != null) {
      String text = action.getText();
      quickFix.invoke(action);
      UIUtil.dispatchAllInvocationEvents();
      UIUtil.dispatchAllInvocationEvents();
      if (!quickFix.shouldBeAvailableAfterExecution()) {
        final IntentionAction afterAction = quickFix.findActionWithText(text);
        if (afterAction != null) {
          fail("Action '" + text + "' is still available after its invocation in test " + testFullPath);
        }
      }
      
      PsiTestUtil.checkStubsMatchText(quickFix.getFile());
      
      String expectedFilePath = ObjectUtils.notNull(quickFix.getBasePath(), "") + "/" + AFTER_PREFIX + testName;
      quickFix.checkResultByFile("In file :" + expectedFilePath, expectedFilePath, false);

      String familyName = action.getFamilyName();
      if (StringUtil.isEmptyOrSpaces(familyName)) {
        fail("Action '" + text + "' provides empty family name which means that user would see action with empty presentable text in Inspection Results");
      }
    }
  }

  private static String getTestInfo(String testFullPath, QuickFixTestCase quickFix) {
    String infos = StreamEx.of(quickFix.doHighlighting())
      .filter(info -> info.getSeverity() != HighlightInfoType.SYMBOL_TYPE_SEVERITY)
      .map(info -> {
        String fixes = "";
        if (info.quickFixActionRanges != null) {
          fixes = StreamEx.of(info.quickFixActionRanges)
            .map(p -> p.getSecond()+" "+p.getFirst())
            .mapLastOrElse("|- "::concat, "\\- "::concat)
            .map(str -> "        " + str + "\n")
            .joining();
        }
        return info.getSeverity() +
               ": (" + info.getStartOffset() + "," + info.getEndOffset() + ") '" +
               info.getText() + "': " + info.getDescription() + "\n" + fixes;
      })
      .joining("       ");
    return "Test: " + testFullPath + "\n" +
           "Language level: " + PsiUtil.getLanguageLevel(quickFix.getProject()) + "\n" +
{'fraction_non_alphanumeric': 0.1034891064098516, 'fraction_numerical': 0.0020524155352068204, 'mean_word_length': 3.3898128898128896, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '423992', 'n_tokens_mistral': 3521, 'n_tokens_neox': 3452, 'n_words': 784}