@NotNull
 public static ConfigurationContext getFromContext(DataContext dataContext) {
   final ConfigurationContext context = new ConfigurationContext(dataContext);
   final DataManager dataManager = DataManager.getInstance();
   ConfigurationContext sharedContext =
       dataManager.loadFromDataContext(dataContext, SHARED_CONTEXT);
   if (sharedContext == null
       || sharedContext.getLocation() == null
       || context.getLocation() == null
       || !Comparing.equal(
           sharedContext.getLocation().getPsiElement(), context.getLocation().getPsiElement())) {
     sharedContext = context;
     dataManager.saveInDataContext(dataContext, SHARED_CONTEXT, sharedContext);
   }
   return sharedContext;
 }
  @Override
  public boolean isConfigurationFromContext(
      JUnitConfiguration unitConfiguration, ConfigurationContext context) {
    if (RunConfigurationProducer.getInstance(PatternConfigurationProducer.class)
        .isMultipleElementsSelected(context)) {
      return false;
    }
    final RunConfiguration predefinedConfiguration =
        context.getOriginalConfiguration(JUnitConfigurationType.getInstance());
    final Location contextLocation = context.getLocation();

    String paramSetName =
        contextLocation instanceof PsiMemberParameterizedLocation
            ? ((PsiMemberParameterizedLocation) contextLocation).getParamSetName()
            : null;
    assert contextLocation != null;
    Location location = JavaExecutionUtil.stepIntoSingleClass(contextLocation);
    if (location == null) {
      return false;
    }
    final PsiElement element = location.getPsiElement();
    final PsiClass testClass = JUnitUtil.getTestClass(element);
    final PsiMethod testMethod = JUnitUtil.getTestMethod(element, false);
    final PsiPackage testPackage;
    if (element instanceof PsiPackage) {
      testPackage = (PsiPackage) element;
    } else if (element instanceof PsiDirectory) {
      testPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory) element));
    } else {
      testPackage = null;
    }
    PsiDirectory testDir = element instanceof PsiDirectory ? (PsiDirectory) element : null;
    RunnerAndConfigurationSettings template =
        RunManager.getInstance(location.getProject())
            .getConfigurationTemplate(getConfigurationFactory());
    final Module predefinedModule =
        ((JUnitConfiguration) template.getConfiguration()).getConfigurationModule().getModule();
    final String vmParameters =
        predefinedConfiguration instanceof JUnitConfiguration
            ? ((JUnitConfiguration) predefinedConfiguration).getVMParameters()
            : null;

    if (vmParameters != null
        && !Comparing.strEqual(vmParameters, unitConfiguration.getVMParameters())) return false;
    if (paramSetName != null
        && !Comparing.strEqual(paramSetName, unitConfiguration.getProgramParameters()))
      return false;
    final TestObject testobject = unitConfiguration.getTestObject();
    if (testobject != null) {
      if (testobject.isConfiguredByElement(
          unitConfiguration, testClass, testMethod, testPackage, testDir)) {
        final Module configurationModule = unitConfiguration.getConfigurationModule().getModule();
        if (Comparing.equal(location.getModule(), configurationModule)) return true;
        if (Comparing.equal(predefinedModule, configurationModule)) {
          return true;
        }
      }
    }
    return false;
  }
示例#3
0
 protected void updateIcon(final Presentation presentation, final ConfigurationContext context) {
   final List<RuntimeConfigurationProducer> producers =
       PreferedProducerFind.findPreferredProducers(context.getLocation(), context, true);
   if (producers != null
       && producers.size()
           == 1) { // hide fuzzy icon when multiple run configurations are possible
     presentation.setIcon(context.getConfiguration().getFactory().getIcon());
   }
 }
  @Override
  public boolean isConfigurationFromContext(
      SubstepsRunConfiguration substepsRunConfiguration,
      ConfigurationContext configurationContext) {

    // return true, if this config was created from this context
    boolean rtn = false;

    log.debug("isConfigurationFromContext?");

    SubstepsRunnerConfigurationModel model = substepsRunConfiguration.getModel();

    String featureFilePath = configurationContext.getLocation().getVirtualFile().getPath();

    if (model.getPathToFeature().equals(featureFilePath)) {

      // it might be the same...

      PsiElement psiElement = configurationContext.getLocation().getPsiElement();
      if (psiElement instanceof ScenarioImpl) {

        ScenarioImpl scenarioImpl = (ScenarioImpl) psiElement;

        if (model.getScenarioName() != null
            && model.getScenarioName().equals(scenarioImpl.getScenarioName())) {
          rtn = true;
        } else {
          log.debug(
              "non matching scenario name model: "
                  + model.getScenarioName()
                  + " ctx: "
                  + scenarioImpl.getScenarioName());
        }
      } else {
        log.debug("not a scenario impl psi element: " + psiElement.getClass());
        if (model.getScenarioName() == null) {
          rtn = true;
        }
      }
    }
    log.debug("isConfigurationFromContext? : " + rtn);
    return rtn;
  }
 @Override
 protected boolean setupConfigurationFromContext(
     JUnitConfiguration configuration,
     ConfigurationContext context,
     Ref<PsiElement> sourceElement) {
   PsiPackage psiPackage =
       JavaRuntimeConfigurationProducerBase.checkPackage(context.getPsiLocation());
   if (psiPackage == null) return false;
   sourceElement.set(psiPackage);
   if (!LocationUtil.isJarAttached(
       context.getLocation(), psiPackage, JUnitUtil.TESTCASE_CLASS, JUnitUtil.TEST5_ANNOTATION))
     return false;
   final JUnitConfiguration.Data data = configuration.getPersistentData();
   data.PACKAGE_NAME = psiPackage.getQualifiedName();
   data.TEST_OBJECT = JUnitConfiguration.TEST_PACKAGE;
   data.setScope(setupPackageConfiguration(context, configuration, data.getScope()));
   configuration.setGeneratedName();
   return true;
 }
  @Override
  protected boolean setupConfigurationFromContext(
      SubstepsRunConfiguration substepsRunConfiguration,
      ConfigurationContext configurationContext,
      Ref<PsiElement> ref) {

    if (ref != null) {

      log.debug("ref: " + ref.toString());

      // TODO in the project view, a feature is IFileElementType: FeatureElementTypes.FEATURE_FILE
      // structure view on a scenario, the ref: ScenarioImpl(SCENARIO_BLOCK_ELEMENT_TYPE)
      PsiElement psiElement = ref.get();
      if (psiElement != null) {

        String scenarioName = null;
        boolean buildRunConfig = false;

        if (psiElement instanceof ScenarioImpl) {
          ScenarioImpl scenarioImpl = (ScenarioImpl) psiElement;
          buildRunConfig = true;
          scenarioName = scenarioImpl.getScenarioName();
        } else if (psiElement instanceof FeatureFileImpl) {
          buildRunConfig = true;
        }

        if (buildRunConfig) {
          SubstepsRunnerConfigurationModel model = new SubstepsRunnerConfigurationModel();

          model.setScenarioName(scenarioName);

          String featureFilePath = configurationContext.getLocation().getVirtualFile().getPath();
          model.setPathToFeature(featureFilePath);

          String featureName = configurationContext.getLocation().getVirtualFile().getName();

          Module module = configurationContext.getModule();

          final Set<String> stepImplClassNames =
              SubstepLibraryManager.INSTANCE.getStepImplClassNamesFromProjectLibraries(module);

          final Set<String> substepDefDirectory = new HashSet<>();

          AnalysisScope moduleScope = new AnalysisScope(module);
          moduleScope.accept(
              new PsiRecursiveElementVisitor() {
                @Override
                public void visitFile(final PsiFile file) {

                  if (file instanceof PsiJavaFile) {

                    PsiJavaFile psiJavaFile = (PsiJavaFile) file;
                    final PsiClass[] psiClasses = psiJavaFile.getClasses();

                    // final PsiClass psiClass =
                    // JavaPsiFacade.getInstance(thisProject).findClass(fqn,
                    // psiJavaFile.getResolveScope());

                    for (PsiClass psiClass : psiClasses) {

                      if (SubstepsCompletionContributor.isStepImplementationsClass(psiClass)) {

                        stepImplClassNames.add(psiClass.getQualifiedName());
                      }
                    }
                  } else if (file instanceof SubstepsDefinitionFile) {

                    String parentPath = file.getParent().getVirtualFile().getPath();

                    if (substepDefDirectory.isEmpty()) {
                      substepDefDirectory.add(parentPath);
                    } else if (!substepDefDirectory.contains(parentPath)) {
                      // find the common ancestor between what's already in and this parent
                      String current = substepDefDirectory.iterator().next();

                      int commonLength = StringUtils.indexOfDifference(current, parentPath);
                      substepDefDirectory.remove(current);

                      String common = current.substring(0, commonLength);

                      log.debug(
                          "current path for substeps: "
                              + current
                              + " got this time: "
                              + parentPath
                              + " common: "
                              + common);

                      substepDefDirectory.add(common);
                    }
                  }
                }
              });

          model.setWorkingDir(module.getModuleFile().getParent().getCanonicalPath());

          model.setStepImplentationClassNames(
              stepImplClassNames.toArray(new String[stepImplClassNames.size()]));

          model.setSubStepDefinitionDirectory(substepDefDirectory.iterator().next());

          try {
            model
                .getJavaParameters()
                .configureByModule(module, JavaParameters.JDK_AND_CLASSES_AND_TESTS);

            Sdk jdk = model.getJavaParameters().getJdk();

            model.setHomePath(jdk.getHomePath());
            model.setVersionString(jdk.getVersionString());

            log.debug(
                "configuring substeps runtime with classpath:\n"
                    + model.getJavaParameters().getClassPath().getPathsString());

            model.setClassPathString(model.getJavaParameters().getClassPath().getPathsString());

          } catch (CantRunException e) {
            log.error("can't run", e);
            return false;
          }

          //                model.setModule(configurationContext.getModule());

          substepsRunConfiguration.setModel(model);

          if (scenarioName != null) {
            substepsRunConfiguration.setName(featureName + ":" + scenarioName);
          } else {
            substepsRunConfiguration.setName(featureName);
          }

          //                this results in two run configs!
          RunManager runManager = RunManager.getInstance(configurationContext.getProject());
          //                RunnerAndConfigurationSettings runAndConfigSettings =
          // runManager.createConfiguration(substepsRunConfiguration,
          // this.getConfigurationFactory());
          //                runManager.addConfiguration(runAndConfigSettings, false);

          List<RunConfiguration> configurationsList = runManager.getConfigurationsList(configType);

          for (RunConfiguration runConfig : configurationsList) {
            SubstepsRunConfiguration substepsRunConfig = (SubstepsRunConfiguration) runConfig;

            log.debug("got substeps run config: " + substepsRunConfig.getName());
          }
          return true;
        }
      }

      //            if (psiElement != null && psiElement.getContainingFile() != null) {
      //
      //                if (psiElement.getContainingFile() instanceof FeatureFile) {
      //
      //                    SubstepsRunnerConfigurationModel model = new
      // SubstepsRunnerConfigurationModel();
      //
      //                    String featureFilePath =
      // configurationContext.getLocation().getVirtualFile().getPath();
      //                    model.setPathToFeature(featureFilePath);
      //
      //                    String featureName =
      // configurationContext.getLocation().getVirtualFile().getName();
      //
      //                    Module module = configurationContext.getModule();
      //
      //                    final Set<String> stepImplClassNames =
      // SubstepLibraryManager.INSTANCE.getStepImplClassNamesFromProjectLibraries(module);
      //
      //                    final Set<String> substepDefDirectory = new HashSet<>();
      //
      //                    AnalysisScope moduleScope = new AnalysisScope(module);
      //                    moduleScope.accept(new PsiRecursiveElementVisitor() {
      //                        @Override
      //                        public void visitFile(final PsiFile file) {
      //
      //                        if (file instanceof PsiJavaFile) {
      //
      //                            PsiJavaFile psiJavaFile = (PsiJavaFile) file;
      //                            final PsiClass[] psiClasses = psiJavaFile.getClasses();
      //
      //                            //final PsiClass psiClass =
      // JavaPsiFacade.getInstance(thisProject).findClass(fqn, psiJavaFile.getResolveScope());
      //
      //                            for (PsiClass psiClass : psiClasses) {
      //
      //                                if
      // (SubstepsCompletionContributor.isStepImplementationsClass(psiClass)) {
      //
      //                                    stepImplClassNames.add(psiClass.getQualifiedName());
      //                                }
      //                            }
      //                        } else if (file instanceof SubstepsDefinitionFile) {
      //
      //                            String parentPath = file.getParent().getVirtualFile().getPath();
      //
      //                            if (substepDefDirectory.isEmpty()) {
      //                                substepDefDirectory.add(parentPath);
      //                            } else if (!substepDefDirectory.contains(parentPath)) {
      //                                // find the common ancestor between what's already in and
      // this parent
      //                                String current = substepDefDirectory.iterator().next();
      //
      //                                int commonLength = StringUtils.indexOfDifference(current,
      // parentPath);
      //                                substepDefDirectory.remove(current);
      //
      //                                String common = current.substring(0, commonLength);
      //
      //                                log.debug("current path for substeps: " + current + " got
      // this time: " + parentPath + " common: " + common);
      //
      //                                substepDefDirectory.add(common);
      //
      //                            }
      //                        }
      //                        }
      //                    });
      //
      //
      //
      // model.setWorkingDir(module.getModuleFile().getParent().getCanonicalPath());
      //
      //
      //                    model.setStepImplentationClassNames(stepImplClassNames.toArray(new
      // String[stepImplClassNames.size()]));
      //
      //
      // model.setSubStepDefinitionDirectory(substepDefDirectory.iterator().next());
      //
      //                    try {
      //                        model.getJavaParameters().configureByModule(module,
      // JavaParameters.JDK_AND_CLASSES_AND_TESTS);
      //
      //                        Sdk jdk = model.getJavaParameters().getJdk();
      //
      //                        model.setHomePath(jdk.getHomePath());
      //                        model.setVersionString(jdk.getVersionString());
      //
      //                        log.debug("configuring substeps runtime with classpath:\n" +
      // model.getJavaParameters().getClassPath().getPathsString());
      //
      //
      // model.setClassPathString(model.getJavaParameters().getClassPath().getPathsString());
      //
      //                    } catch (CantRunException e) {
      //                        log.error("can't run", e);
      //                        return false;
      //                    }
      //
      ////                model.setModule(configurationContext.getModule());
      //
      //                    substepsRunConfiguration.setModel(model);
      //
      //                    substepsRunConfiguration.setName(featureName);
      //
      ////                this results in two run configs!
      //                    RunManager runManager =
      // RunManager.getInstance(configurationContext.getProject());
      ////                RunnerAndConfigurationSettings runAndConfigSettings =
      // runManager.createConfiguration(substepsRunConfiguration, this.getConfigurationFactory());
      ////                runManager.addConfiguration(runAndConfigSettings, false);
      //
      //                    List<RunConfiguration> configurationsList =
      // runManager.getConfigurationsList(configType);
      //
      //                    for (RunConfiguration runConfig : configurationsList) {
      //                        SubstepsRunConfiguration substepsRunConfig =
      // (SubstepsRunConfiguration) runConfig;
      //
      //                        log.debug("got substeps run config: " +
      //                                substepsRunConfig.getName());
      //
      //                    }
      //                    return true;
      //                }
      //            }
    }
    return false;
  }
  public boolean runMethodInAbstractClass(
      final ConfigurationContext context,
      final Runnable performRunnable,
      final PsiMethod psiMethod,
      final PsiClass containingClass,
      final Condition<PsiClass> acceptAbstractCondition) {
    if (containingClass != null
        && containingClass.hasModifierProperty(PsiModifier.ABSTRACT)
        && acceptAbstractCondition.value(containingClass)) {
      final Location location = context.getLocation();
      if (location instanceof MethodLocation) {
        final PsiClass aClass = ((MethodLocation) location).getContainingClass();
        if (aClass != null && !aClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
          return false;
        }
      } else if (location instanceof PsiMemberParameterizedLocation) {
        return false;
      }

      final List<PsiClass> classes = new ArrayList<PsiClass>();
      if (!ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              new Runnable() {
                @Override
                public void run() {
                  ClassInheritorsSearch.search(containingClass)
                      .forEach(
                          new Processor<PsiClass>() {
                            @Override
                            public boolean process(PsiClass aClass) {
                              if (PsiClassUtil.isRunnableClass(aClass, true, true)) {
                                classes.add(aClass);
                              }
                              return true;
                            }
                          });
                }
              },
              "Search for " + containingClass.getQualifiedName() + " inheritors",
              true,
              containingClass.getProject())) {
        return true;
      }

      if (classes.size() == 1) {
        runForClass(classes.get(0), psiMethod, context, performRunnable);
        return true;
      }
      if (classes.isEmpty()) return false;
      final FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(context.getDataContext());
      if (fileEditor instanceof TextEditor) {
        final Document document = ((TextEditor) fileEditor).getEditor().getDocument();
        final PsiFile containingFile =
            PsiDocumentManager.getInstance(context.getProject()).getPsiFile(document);
        if (containingFile instanceof PsiClassOwner) {
          final List<PsiClass> psiClasses =
              new ArrayList<PsiClass>(Arrays.asList(((PsiClassOwner) containingFile).getClasses()));
          psiClasses.retainAll(classes);
          if (psiClasses.size() == 1) {
            runForClass(psiClasses.get(0), psiMethod, context, performRunnable);
            return true;
          }
        }
      }
      final PsiClassListCellRenderer renderer =
          new PsiClassListCellRenderer() {
            @Override
            protected boolean customizeNonPsiElementLeftRenderer(
                ColoredListCellRenderer renderer,
                JList list,
                Object value,
                int index,
                boolean selected,
                boolean hasFocus) {
              if (value == null) {
                renderer.append("All");
                return true;
              }
              return super.customizeNonPsiElementLeftRenderer(
                  renderer, list, value, index, selected, hasFocus);
            }
          };
      Collections.sort(classes, renderer.getComparator());

      // suggest to run all inherited tests
      classes.add(0, null);
      final JBList list = new JBList(classes);
      list.setCellRenderer(renderer);
      JBPopupFactory.getInstance()
          .createListPopupBuilder(list)
          .setTitle(
              "Choose executable classes to run "
                  + (psiMethod != null ? psiMethod.getName() : containingClass.getName()))
          .setMovable(false)
          .setResizable(false)
          .setRequestFocus(true)
          .setItemChoosenCallback(
              new Runnable() {
                public void run() {
                  final Object[] values = list.getSelectedValues();
                  if (values == null) return;
                  chooseAndPerform(values, psiMethod, context, performRunnable, classes);
                }
              })
          .createPopup()
          .showInBestPositionFor(context.getDataContext());
      return true;
    }
    return false;
  }
  @Override
  protected boolean setupConfigurationFromContext(
      TestNGConfiguration configuration,
      ConfigurationContext context,
      Ref<PsiElement> sourceElement) {
    // TODO: check TestNG Pattern running first, before method/class (see
    // TestNGInClassConfigurationProducer for logic)
    // TODO: and PsiClassOwner not handled, which is in TestNGInClassConfigurationProducer

    Location location = context.getLocation();
    if (location == null) {
      return false;
    }

    Project project = context.getProject();
    PsiElement leaf = location.getPsiElement();

    if (!ProjectRootsUtil.isInProjectOrLibSource(leaf)) {
      return false;
    }

    if (!(leaf.getContainingFile() instanceof KtFile)) {
      return false;
    }

    KtFile jetFile = (KtFile) leaf.getContainingFile();

    if (ProjectStructureUtil.isJsKotlinModule(jetFile)) {
      return false;
    }

    KtNamedDeclaration declarationToRun = getDeclarationToRun(leaf);

    if (declarationToRun instanceof KtNamedFunction) {
      KtNamedFunction function = (KtNamedFunction) declarationToRun;

      @SuppressWarnings("unchecked")
      KtElement owner = PsiTreeUtil.getParentOfType(function, KtFunction.class, KtClass.class);

      if (owner instanceof KtClass) {
        PsiClass delegate = LightClassUtil.INSTANCE.getPsiClass((KtClass) owner);
        if (delegate != null) {
          for (PsiMethod method : delegate.getMethods()) {
            if (method.getNavigationElement() == function) {
              if (TestNGUtil.hasTest(method)) {
                return configure(configuration, location, context, project, delegate, method);
              }
              break;
            }
          }
        }
      }
    }

    if (declarationToRun instanceof KtClass) {
      PsiClass delegate = LightClassUtil.INSTANCE.getPsiClass((KtClassOrObject) declarationToRun);
      if (!isTestNGClass(delegate)) {
        return false;
      }

      return configure(configuration, location, context, project, delegate, null);
    }

    return false;
  }