private void monitorTestCase(TestCase testCase) {
    testCase.addTestRunListener(testRunListener);

    for (int v = 0; v < testCase.getLoadTestCount(); v++) {
      testCase.getLoadTestAt(v).addLoadTestRunListener(loadTestRunListener);
    }
  }
  @Override
  public void perform(WsdlTestSuite testSuite, Object param) {

    if (IntegrationUtils.forceSaveProject(testSuite.getProject())) {

      if (!StartLoadUI.testCajoConnection()) {
        if (UISupport.confirm(
            StartLoadUI.LOADUI_LAUNCH_QUESTION, StartLoadUI.LOADUI_LAUNCH_TITLE)) {
          StartLoadUI.launchLoadUI();
        }
        return;
      }

      XFormDialog dialog = ADialogBuilder.buildDialog(TestSuiteForm.class);

      dialog.setOptions(TestSuiteForm.LOADUIPROJECT, IntegrationUtils.getAvailableProjects());
      if (!StringUtils.isNullOrEmpty(IntegrationUtils.getOpenedProjectName())) {
        dialog.setValue(TestSuiteForm.LOADUIPROJECT, IntegrationUtils.getOpenedProjectName());
      } else {
        dialog.setValue(TestSuiteForm.LOADUIPROJECT, IntegrationUtils.CREATE_NEW_OPTION);
      }
      List<String> testSuiteLoadTests = new ArrayList<String>();
      for (TestCase testCase : testSuite.getTestCaseList()) {
        for (LoadTest loadTest : testCase.getLoadTestList()) {
          testSuiteLoadTests.add(testCase.getName() + " - " + loadTest.getName());
        }
      }
      String[] names = new String[testSuiteLoadTests.size()];
      for (int c = 0; c < names.length; c++) {
        names[c] = testSuiteLoadTests.get(c);
      }
      dialog.setOptions(TestSuiteForm.LOADTESTS, names);
      if (dialog.show()) {
        if (dialog.getReturnValue() == XFormDialog.OK_OPTION) {
          String loadUIProject = dialog.getValue(TestSuiteForm.LOADUIPROJECT);
          String openedProjectName = IntegrationUtils.getOpenedProjectName();
          if (!StringUtils.isNullOrEmpty(openedProjectName)
              && !loadUIProject.equals(openedProjectName)
              && IntegrationUtils.checkOpenedLoadUIProjectForClose()) {
            return;
          }
          String[] soapuiLoadTests =
              StringUtils.toStringArray(
                  ((XFormMultiSelectList) dialog.getFormField(TestSuiteForm.LOADTESTS))
                      .getSelectedOptions());
          if (soapuiLoadTests.length == 0) {
            UISupport.showErrorMessage("No LoadTests selected.");
            return;
          }
          try {
            IntegrationUtils.exportMultipleLoadTestToLoadUI(
                testSuite, soapuiLoadTests, loadUIProject);
          } catch (IOException e) {
            UISupport.showInfoMessage("Error while opening selected loadUI project");
            return;
          }
        }
      }
    }
  }
  private void unmonitorTestCase(TestCase testCase) {
    testCase.removeTestRunListener(testRunListener);

    for (int c = 0; c < testCase.getLoadTestCount(); c++) {
      unmonitorLoadTest(testCase.getLoadTestAt(c));
    }
  }
 /**
  * Runs one soapUI TestCase
  *
  * @param testCase single TestCase
  */
 protected void run(TestCase testCase) {
   testCase.addTestRunListener(listener);
   TestRunner runner = testCase.run(new PropertiesMap(), false);
   assertThat(runner.getStatus())
       .describedAs(
           "TestCase [" + testCase.getLabel() + "] failed because of [" + runner.getReason() + "]")
       .isEqualTo(TestRunner.Status.FINISHED);
 }
 protected void addListeners(TestCase tc) {
   tc.addTestRunListener(this);
   if (junitReport) {
     tc.addTestRunListener(reportCollector);
   }
   if (printAlertSiteReport) {
     tc.addTestRunListener(testCaseRunLogReport);
   }
 }
  @Override
  public void afterRun(TestCaseRunner testRunner, SecurityTestRunContext runContext) {
    TestCase testCase = testRunner.getTestCase();

    SecurityTest securityTest = ((SecurityTestRunner) testRunner).getSecurityTest();

    JUnitReport report = new JUnitReport();
    report.setIncludeTestProperties(includeTestPropertiesInReport);

    String reportName = securityTest.getName();
    report.setTestSuiteName(reportName);
    report.setPackage(testCase.getTestSuite().getProject().getName());
    int errorCount = 0;

    for (TestStep ts : testCase.getTestStepList()) {
      SecurityTestStepResult secuTestStepResult =
          securityTest.getSecurityTestStepResultMap().get(ts);
      if (secuTestStepResult != null) {
        for (SecurityScanResult scanResult : secuTestStepResult.getSecurityScanResultList()) {

          HashMap<String, String> testProperties = getTestPropertiesAsHashMap(securityTest);

          List<SecurityScanRequestResult> resultList = scanResult.getSecurityRequestResultList();
          Testcase secTestCase =
              report.addTestCase(
                  ts.getName() + " - " + scanResult.getSecurityScanName(),
                  scanResult.getTimeTaken(),
                  testProperties);

          secTestCase.setPackage(testCase.getTestSuite().getProject().getName());

          for (int i = 0; i < resultList.size(); i++) {
            SecurityScanRequestResult scanRequestResult = resultList.get(i);
            if (scanRequestResult.getStatus() == ResultStatus.FAILED) {
              StringBuffer result = new StringBuffer();
              result
                  .append("<pre>")
                  .append(XmlUtils.entitize(scanRequestResult.getChangedParamsInfo(i + 1)))
                  .append("</pre>");

              for (String message : scanRequestResult.getMessages()) {
                result.append("<pre>").append(XmlUtils.entitize(message)).append("</pre>");
              }

              secTestCase.addNewError().setStringValue(result.toString());
              errorCount++;
            }
          }
        }
      }

      report.setNoofErrorsInTestSuite(errorCount);
      report.setTotalTime(testRunner.getTimeTaken());

      reports.put(reportName, report);
    }
  }
  public static MockRunnerManager getInstance(TestCase testCase) {
    if (managers.containsKey(testCase.getId())) {
      return managers.get(testCase.getId());
    } else {
      MockRunnerManager manager = new MockRunnerManagerImpl(testCase.getTestSuite().getProject());
      managers.put(testCase.getId(), manager);

      return manager;
    }
  }
  public void testAssert() throws Exception {
    WsdlProject project =
        new WsdlProject(
            "src"
                + File.separatorChar
                + "test-resources"
                + File.separatorChar
                + "sample-soapui-project.xml");
    TestSuite testSuite = project.getTestSuiteByName("Test Suite");
    com.eviware.soapui.model.testsuite.TestCase testCase =
        testSuite.getTestCaseByName("Test Conversions");

    WsdlTestRequestStep testStep =
        (WsdlTestRequestStep) testCase.getTestStepByName("SEK to USD Test");

    MockTestRunner testRunner = new MockTestRunner((WsdlTestCase) testStep.getTestCase());
    MockTestRunContext testRunContext = new MockTestRunContext(testRunner, (WsdlTestStep) testStep);

    TestStepResult result = testStep.run(testRunner, testRunContext);

    WsdlTestRequestStepResult wsdlResult = (WsdlTestRequestStepResult) result;
    assertNotNull(wsdlResult);
    // assertEquals(TestStepResult.TestStepStatus.OK, wsdlResult.getStatus());
  }
 @Override
 public void release() {
   super.release();
   testCase.getTestSuite().removeTestSuiteListener(listener);
 }
 @Override
 public void testCaseRemoved(TestCase testCase) {
   if (testCase == WsdlTestStepsModelItem.this.testCase) {
     testCase.getTestSuite().removeTestSuiteListener(listener);
   }
 }
 private static String createLabel(TestCase testCase) {
   return "Test Steps (" + testCase.getTestStepCount() + ")";
 }
 public Settings getSettings() {
   return testCase.getSettings();
 }
  @Override
  public boolean runRunner() throws Exception {
    AnalyticsHelper.initializeAnalytics();
    Analytics.trackSessionStart();

    initGroovyLog();

    assertions.clear();

    String projectFile = getProjectFile();

    WsdlProject project =
        (WsdlProject)
            ProjectFactoryRegistry.getProjectFactory("wsdl")
                .createNew(projectFile, getProjectPassword());

    if (project.isDisabled()) {
      throw new Exception("Failed to load SoapUI project file [" + projectFile + "]");
    }

    initProject(project);
    ensureOutputFolder(project);

    if (this.printAlertSiteReport) {
      testCaseRunLogReport = new TestCaseRunLogReport(getAbsoluteOutputFolder(project));
    }

    log.info("Running SoapUI tests in project [" + project.getName() + "]");

    long startTime = System.nanoTime();

    List<TestCase> testCasesToRun = new ArrayList<TestCase>();

    // validate testSuite argument
    if (testSuite != null && project.getTestSuiteByName(testSuite) == null) {
      throw new Exception(
          "TestSuite with name ["
              + testSuite
              + "] is missing in Project ["
              + project.getName()
              + "]");
    }

    // start by listening to all testcases.. (since one testcase can call
    // another)
    for (int c = 0; c < project.getTestSuiteCount(); c++) {
      TestSuite suite = project.getTestSuiteAt(c);
      for (int i = 0; i < suite.getTestCaseCount(); i++) {
        TestCase tc = suite.getTestCaseAt(i);
        if ((testSuite == null || suite.getName().equals(testSuite))
            && testCase != null
            && tc.getName().equals(testCase)) {
          testCasesToRun.add(tc);
        }

        addListeners(tc);
      }
    }

    try {
      // validate testSuite argument
      if (testCase != null && testCasesToRun.size() == 0) {
        if (testSuite == null) {
          throw new Exception(
              "TestCase with name ["
                  + testCase
                  + "] is missing in Project ["
                  + project.getName()
                  + "]");
        } else {
          throw new Exception(
              "TestCase with name ["
                  + testCase
                  + "] in TestSuite ["
                  + testSuite
                  + "] is missing in Project ["
                  + project.getName()
                  + "]");
        }
      }

      // decide what to run
      if (testCasesToRun.size() > 0) {
        for (TestCase testCase : testCasesToRun) {
          runTestCase((WsdlTestCase) testCase);
        }
      } else if (testSuite != null) {
        WsdlTestSuite ts = project.getTestSuiteByName(testSuite);
        if (ts == null) {
          throw new Exception("TestSuite with name [" + testSuite + "] not found in project");
        } else {
          runSuite(ts);
        }
      } else {
        runProject(project);
      }

      long timeTaken = (System.nanoTime() - startTime) / 1000000;

      if (printReport) {
        printReport(timeTaken);
      }

      exportReports(project);

      if (saveAfterRun && !project.isRemote()) {
        try {
          project.save();
        } catch (Throwable t) {
          log.error("Failed to save project", t);
        }
      }

      if ((assertions.size() > 0 || failedTests.size() > 0) && !ignoreErrors) {
        throwFailureException();
      }

      return true;
    } finally {
      for (int c = 0; c < project.getTestSuiteCount(); c++) {
        TestSuite suite = project.getTestSuiteAt(c);
        for (int i = 0; i < suite.getTestCaseCount(); i++) {
          TestCase tc = suite.getTestCaseAt(i);
          removeListeners(tc);
        }
      }
    }
  }
  public WsdlTestStepsModelItem(TestCase testCase) {
    super(createLabel(testCase), UISupport.createImageIcon("/teststeps.gif"));
    this.testCase = testCase;

    testCase.getTestSuite().addTestSuiteListener(listener);
  }
 protected void removeListeners(TestCase tc) {
   tc.removeTestRunListener(this);
   if (junitReport) {
     tc.removeTestRunListener(reportCollector);
   }
 }
  @Override
  public void afterStep(
      TestCaseRunner testRunner, TestCaseRunContext runContext, TestStepResult result) {
    super.afterStep(testRunner, runContext, result);
    TestStep currentStep = runContext.getCurrentStep();

    if (currentStep instanceof Assertable) {
      Assertable requestStep = (Assertable) currentStep;
      for (int c = 0; c < requestStep.getAssertionCount(); c++) {
        TestAssertion assertion = requestStep.getAssertionAt(c);
        log.info("Assertion [" + assertion.getName() + "] has status " + assertion.getStatus());
        if (assertion.getStatus() == AssertionStatus.FAILED) {
          for (AssertionError error : assertion.getErrors()) {
            log.error("ASSERTION FAILED -> " + error.getMessage());
          }

          assertions.add(assertion);
          assertionResults.put(assertion, (WsdlTestStepResult) result);
        }

        testAssertionCount++;
      }
    }

    String countPropertyName = currentStep.getName() + " run count";
    Long count = (Long) runContext.getProperty(countPropertyName);
    if (count == null) {
      count = new Long(0);
    }

    runContext.setProperty(countPropertyName, new Long(count.longValue() + 1));

    if (result.getStatus() == TestStepStatus.FAILED || exportAll) {
      try {
        String exportSeparator = System.getProperty(SOAPUI_EXPORT_SEPARATOR, "-");

        TestCase tc = currentStep.getTestCase();
        String nameBase =
            StringUtils.createFileName(tc.getTestSuite().getName(), '_')
                + exportSeparator
                + StringUtils.createFileName(tc.getName(), '_')
                + exportSeparator
                + StringUtils.createFileName(currentStep.getName(), '_')
                + "-"
                + count.longValue()
                + "-"
                + result.getStatus();

        WsdlTestCaseRunner callingTestCaseRunner =
            (WsdlTestCaseRunner) runContext.getProperty("#CallingTestCaseRunner#");

        if (callingTestCaseRunner != null) {
          WsdlTestCase ctc = callingTestCaseRunner.getTestCase();
          WsdlRunTestCaseTestStep runTestCaseTestStep =
              (WsdlRunTestCaseTestStep) runContext.getProperty("#CallingRunTestCaseStep#");

          nameBase =
              StringUtils.createFileName(ctc.getTestSuite().getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(ctc.getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(runTestCaseTestStep.getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(tc.getTestSuite().getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(tc.getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(currentStep.getName(), '_')
                  + "-"
                  + count.longValue()
                  + "-"
                  + result.getStatus();
        }

        String absoluteOutputFolder = getAbsoluteOutputFolder(ModelSupport.getModelItemProject(tc));
        String fileName = absoluteOutputFolder + File.separator + nameBase + ".txt";

        if (result.getStatus() == TestStepStatus.FAILED) {
          log.error(currentStep.getName() + " failed, exporting to [" + fileName + "]");
        }

        new File(fileName).getParentFile().mkdirs();

        PrintWriter writer = new PrintWriter(fileName);
        result.writeTo(writer);
        writer.close();

        // write attachments
        if (result instanceof MessageExchange) {
          Attachment[] attachments = ((MessageExchange) result).getResponseAttachments();
          if (attachments != null && attachments.length > 0) {
            for (int c = 0; c < attachments.length; c++) {
              fileName = nameBase + "-attachment-" + (c + 1) + ".";

              Attachment attachment = attachments[c];
              String contentType = attachment.getContentType();
              if (!"application/octet-stream".equals(contentType)
                  && contentType != null
                  && contentType.indexOf('/') != -1) {
                fileName += contentType.substring(contentType.lastIndexOf('/') + 1);
              } else {
                fileName += "dat";
              }

              fileName = absoluteOutputFolder + File.separator + fileName;

              FileOutputStream outFile = new FileOutputStream(fileName);
              Tools.writeAll(outFile, attachment.getInputStream());
              outFile.close();
            }
          }
        }

        exportCount++;
      } catch (Exception e) {
        log.error("Error saving failed result: " + e, e);
      }
    }

    testStepCount++;
  }
 @Override
 public void testCaseRemoved(final TestCase testCase) {
   getBridge(testCase).deleteTestCaseByIdPrxy(testCase.getId());
 }
 @Override
 public void testCaseAdded(final TestCase testCase) {
   Utils.log("Adding TestCase \"" + testCase.getLabel() + "\" to model");
   getBridge(testCase).addTestCasePrxy(testCase);
 }
 private static ModelBridge getBridge(final TestCase tc) {
   return ModelBridge.getOrCreateEnvBridge(tc.getTestSuite().getProject());
 }